text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def optimize_order(self, data, min_p=1, max_p=None): """Determine optimal model order by minimizing the mean squared generalization error. Parameters data : arra...
data = np.asarray(data) if data.shape[0] < 2: raise ValueError("At least two trials are required.") msge, prange = [], [] par, func = parallel_loop(_get_msge_with_gradient, n_jobs=self.n_jobs, verbose=self.verbose) if self.n_jobs i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fromvector(cls, v): """Initialize from euclidean vector"""
w = v.normalized() return cls(w.x, w.y, w.z)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list(self): """position in 3d space"""
return [self._pos3d.x, self._pos3d.y, self._pos3d.z]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def distance(self, other): """Distance to another point on the sphere"""
return math.acos(self._pos3d.dot(other.vector))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def distances(self, points): """Distance to other points on the sphere"""
return [math.acos(self._pos3d.dot(p.vector)) for p in points]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fromiterable(cls, itr): """Initialize from iterable"""
x, y, z = itr return cls(x, y, z)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fromvector(cls, v): """Copy another vector"""
return cls(v.x, v.y, v.z)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def norm2(self): """Squared norm of the vector"""
return self.x * self.x + self.y * self.y + self.z * self.z
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rotate(self, l, u): """rotate l radians around axis u"""
cl = math.cos(l) sl = math.sin(l) x = (cl + u.x * u.x * (1 - cl)) * self.x + (u.x * u.y * (1 - cl) - u.z * sl) * self.y + ( u.x * u.z * (1 - cl) + u.y * sl) * self.z y = (u.y * u.x * (1 - cl) + u.z * sl) * self.x + (cl + u.y * u.y * (1 - cl)) * self.y + ( u.y * u.z * (1 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cuthill_mckee(matrix): """Implementation of the Cuthill-McKee algorithm. Permute a symmetric binary matrix into a band matrix form with a small bandwidth. Pa...
matrix = np.atleast_2d(matrix) n, m = matrix.shape assert(n == m) # make sure the matrix is really symmetric. This is equivalent to # converting a directed adjacency matrix into a undirected adjacency matrix. matrix = np.logical_or(matrix, matrix.T) degree = np.sum(matrix, 0) order = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connectivity(measure_names, b, c=None, nfft=512): """Calculate connectivity measures. Parameters measure_names : str or list of str Name(s) of the connectivi...
con = Connectivity(b, c, nfft) try: return getattr(con, measure_names)() except TypeError: return dict((m, getattr(con, m)()) for m in measure_names)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Cinv(self): """Inverse of the noise covariance."""
try: return np.linalg.inv(self.c) except np.linalg.linalg.LinAlgError: print('Warning: non-invertible noise covariance matrix c.') return np.eye(self.c.shape[0])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def A(self): """Spectral VAR coefficients. .. math:: \mathbf{A}(f) = \mathbf{I} - \sum_{k=1}^{p} \mathbf{a}^{(k)} \mathrm{e}^{-2\pi f} """
return fft(np.dstack([np.eye(self.m), -self.b]), self.nfft * 2 - 1)[:, :, :self.nfft]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def S(self): """Cross-spectral density. .. math:: \mathbf{S}(f) = \mathbf{H}(f) \mathbf{C} \mathbf{H}'(f) """
if self.c is None: raise RuntimeError('Cross-spectral density requires noise ' 'covariance matrix c.') H = self.H() # TODO: can we do that more efficiently? S = np.empty(H.shape, dtype=H.dtype) for f in range(H.shape[2]): S[...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def G(self): """Inverse cross-spectral density. .. math:: \mathbf{G}(f) = \mathbf{A}(f) \mathbf{C}^{-1} \mathbf{A}'(f) """
if self.c is None: raise RuntimeError('Inverse cross spectral density requires ' 'invertible noise covariance matrix c.') A = self.A() # TODO: can we do that more efficiently? G = np.einsum('ji..., jk... ->ik...', A.conj(), self.Cinv()) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pCOH(self): """Partial coherence. .. math:: \mathrm{pCOH}_{ij}(f) = \\frac{G_{ij}(f)} {\sqrt{G_{ii}(f) G_{jj}(f)}} References P. J. Franaszczuk, K. J. Blinow...
G = self.G() # TODO: can we do that more efficiently? return G / np.sqrt(np.einsum('ii..., jj... ->ij...', G, G))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def PDC(self): """Partial directed coherence. .. math:: \mathrm{PDC}_{ij}(f) = \\frac{A_{ij}(f)} {\sqrt{A_{:j}'(f) A_{:j}(f)}} References L. A. Baccalá, K. Sames...
A = self.A() return np.abs(A / np.sqrt(np.sum(A.conj() * A, axis=0, keepdims=True)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ffPDC(self): """Full frequency partial directed coherence. .. math:: \mathrm{ffPDC}_{ij}(f) = \\frac{A_{ij}(f)}{\sqrt{\sum_f A_{:j}'(f) A_{:j}(f)}} """
A = self.A() return np.abs(A * self.nfft / np.sqrt(np.sum(A.conj() * A, axis=(0, 2), keepdims=True)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def PDCF(self): """Partial directed coherence factor. .. math:: \mathrm{PDCF}_{ij}(f) = \\frac{A_{ij}(f)}{\sqrt{A_{:j}'(f) \mathbf{C}^{-1} A_{:j}(f)}} References...
A = self.A() # TODO: can we do that more efficiently? return np.abs(A / np.sqrt(np.einsum('aj..., ab..., bj... ->j...', A.conj(), self.Cinv(), A)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GPDC(self): """Generalized partial directed coherence. .. math:: \mathrm{GPDC}_{ij}(f) = \\frac{|A_{ij}(f)|} {\sigma_i \sqrt{A_{:j}'(f) \mathrm{diag}(\mathbf...
A = self.A() tmp = A / np.sqrt(np.einsum('aj..., a..., aj..., ii... ->ij...', A.conj(), 1 / np.diag(self.c), A, self.c)) return np.abs(tmp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def DTF(self): """Directed transfer function. .. math:: \mathrm{DTF}_{ij}(f) = \\frac{H_{ij}(f)} {\sqrt{H_{i:}(f) H_{i:}'(f)}} References M. J. Kaminski, K. J. B...
H = self.H() return np.abs(H / np.sqrt(np.sum(H * H.conj(), axis=1, keepdims=True)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ffDTF(self): """Full frequency directed transfer function. .. math:: \mathrm{ffDTF}_{ij}(f) = \\frac{H_{ij}(f)}{\sqrt{\sum_f H_{i:}(f) H_{i:}'(f)}} Reference...
H = self.H() return np.abs(H * self.nfft / np.sqrt(np.sum(H * H.conj(), axis=(1, 2), keepdims=True)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GDTF(self): """Generalized directed transfer function. .. math:: \mathrm{GPDC}_{ij}(f) = \\frac{\sigma_j |H_{ij}(f)|} {\sqrt{H_{i:}(f) \mathrm{diag}(\mathbf{...
H = self.H() tmp = H / np.sqrt(np.einsum('ia..., aa..., ia..., j... ->ij...', H.conj(), self.c, H, 1 / self.c.diagonal())) return np.abs(tmp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enrich(self, expected=None, provided=None, path=None, validator=None): """ Enrich this error with additional information. This works with both Invalid and Mu...
for e in self: # defaults on fields if e.expected is None and expected is not None: e.expected = expected if e.provided is None and provided is not None: e.provided = provided if e.validator is None and validator is not None: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flatten(cls, errors): """ Unwind `MultipleErrors` to have a plain list of `Invalid` :type errors: list[Invalid|MultipleInvalid] :rtype: list[Invalid] """
ers = [] for e in errors: if isinstance(e, MultipleInvalid): ers.extend(cls.flatten(e.errors)) else: ers.append(e) return ers
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def warp_locations(locations, y_center=None, return_ellipsoid=False, verbose=False): """ Warp EEG electrode locations to spherical layout. EEG Electrodes are war...
locations = np.asarray(locations) if y_center is None: c, r = _fit_ellipsoid_full(locations) else: c, r = _fit_ellipsoid_partial(locations, y_center) elliptic_locations = _project_on_ellipsoid(c, r, locations) if verbose: print('Head ellipsoid center:', c) print('...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _project_on_ellipsoid(c, r, locations): """displace locations to the nearest point on ellipsoid surface"""
p0 = locations - c # original locations l2 = 1 / np.sum(p0**2 / r**2, axis=1, keepdims=True) p = p0 * np.sqrt(l2) # initial approximation (projection of points towards center of ellipsoid) fun = lambda x: np.sum((x.reshape(p0.shape) - p0)**2) # minimize distance between new and old poi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cut_segments(x2d, tr, start, stop): """Cut continuous signal into segments. Parameters x2d : array, shape (m, n) Input data with m signals and n samples. tr ...
if start != int(start): raise ValueError("start index must be an integer") if stop != int(stop): raise ValueError("stop index must be an integer") x2d = np.atleast_2d(x2d) tr = np.asarray(tr, dtype=int).ravel() win = np.arange(start, stop, dtype=int) return np.concatenate([x2d[...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cat_trials(x3d): """Concatenate trials along time axis. Parameters x3d : array, shape (t, m, n) Segmented input data with t trials, m signals, and n samples....
x3d = atleast_3d(x3d) t = x3d.shape[0] return np.concatenate(np.split(x3d, t, 0), axis=2).squeeze(0)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dot_special(x2d, x3d): """Segment-wise dot product. This function calculates the dot product of x2d with each trial of x3d. Parameters x2d : array, shape (p,...
x3d = atleast_3d(x3d) x2d = np.atleast_2d(x2d) return np.concatenate([x2d.dot(x3d[i, ...])[np.newaxis, ...] for i in range(x3d.shape[0])])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def randomize_phase(data, random_state=None): """Phase randomization. This function randomizes the spectral phase of the input data along the last dimension. Par...
rng = check_random_state(random_state) data = np.asarray(data) data_freq = np.fft.rfft(data) data_freq = np.abs(data_freq) * np.exp(1j*rng.random_sample(data_freq.shape)*2*np.pi) return np.fft.irfft(data_freq, data.shape[-1])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def acm(x, l): """Compute autocovariance matrix at lag l. This function calculates the autocovariance matrix of `x` at lag `l`. Parameters x : array, shape (n_tr...
x = atleast_3d(x) if l > x.shape[2]-1: raise AttributeError("lag exceeds data length") ## subtract mean from each trial #for t in range(x.shape[2]): # x[:, :, t] -= np.mean(x[:, :, t], axis=0) if l == 0: a, b = x, x else: a = x[:, :, l:] b = x[:, :, 0:-...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def jackknife_connectivity(measures, data, var, nfft=512, leaveout=1, n_jobs=1, verbose=0): """Calculate jackknife estimates of connectivity. For each jackknife ...
data = atleast_3d(data) t, m, n = data.shape assert(t > 1) if leaveout < 1: leaveout = int(leaveout * t) num_blocks = t // leaveout mask = lambda block: [i for i in range(t) if i < block*leaveout or i >= (block + 1) * leaveout] p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bootstrap_connectivity(measures, data, var, nfft=512, repeats=100, num_samples=None, n_jobs=1, verbose=0, random_state=None): """Calculate bootstrap estimate...
rng = check_random_state(random_state) data = atleast_3d(data) n, m, t = data.shape assert(t > 1) if num_samples is None: num_samples = t mask = lambda r: rng.random_integers(0, data.shape[0]-1, num_samples) par, func = parallel_loop(_calc_bootstrap, n_jobs=n_jobs, verbose=verbo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def significance_fdr(p, alpha): """Calculate significance by controlling for the false discovery rate. This function determines which of the p-values in `p` can ...
i = np.argsort(p, axis=None) m = i.size - np.sum(np.isnan(p)) j = np.empty(p.shape, int) j.flat[i] = np.arange(1, i.size + 1) mask = p <= alpha * j / m if np.sum(mask) == 0: return mask # find largest k so that p_k <= alpha*k/m k = np.max(j[mask]) # reject all H_i for i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_type_name(t, name): """ Register a human-friendly name for the given type. This will be used in Invalid errors :param t: The type to register :type ...
assert isinstance(t, type) assert isinstance(name, unicode) __type_names[t] = name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_type_name(t): """ Get a human-friendly name for the given type. :type t: type|None :rtype: unicode """
# Lookup in the mapping try: return __type_names[t] except KeyError: # Specific types if issubclass(t, six.integer_types): return _(u'Integer number') # Get name from the Type itself return six.text_type(t.__name__).capitalize()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_callable_name(c): """ Get a human-friendly name for the given callable. :param c: The callable to get the name for :type c: callable :rtype: unicode """
if hasattr(c, 'name'): return six.text_type(c.name) elif hasattr(c, '__name__'): return six.text_type(c.__name__) + u'()' else: return six.text_type(c)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_primitive_name(schema): """ Get a human-friendly name for the given primitive. :param schema: Schema :type schema: * :rtype: unicode """
try: return { const.COMPILED_TYPE.LITERAL: six.text_type, const.COMPILED_TYPE.TYPE: get_type_name, const.COMPILED_TYPE.ENUM: get_type_name, const.COMPILED_TYPE.CALLABLE: get_callable_name, const.COMPILED_TYPE.ITERABLE: lambda x: _(u'{type}[{conten...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def primitive_type(schema): """ Get schema type for the primitive argument. Note: it does treats markers & schemas as callables! :param schema: Value of a primit...
schema_type = type(schema) # Literal if schema_type in const.literal_types: return const.COMPILED_TYPE.LITERAL # Enum elif Enum is not None and isinstance(schema, (EnumMeta, Enum)): return const.COMPILED_TYPE.ENUM # Type elif issubclass(schema_type, six.class_types): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def commajoin_as_strings(iterable): """ Join the given iterable with ',' """
return _(u',').join((six.text_type(i) for i in iterable))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_topoplots(topo, values): """Prepare multiple topo maps for cached plotting. .. note:: Parameter `topo` is modified by the function by calling :func:`...
values = np.atleast_2d(values) topomaps = [] for i in range(values.shape[0]): topo.set_values(values[i, :]) topo.create_map() topomaps.append(topo.get_map()) return topomaps
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_topo(axis, topo, topomap, crange=None, offset=(0,0), plot_locations=True, plot_head=True): """Draw a topoplot in given axis. .. note:: Parameter `topo` ...
topo.set_map(topomap) h = topo.plot_map(axis, crange=crange, offset=offset) if plot_locations: topo.plot_locations(axis, offset=offset) if plot_head: topo.plot_head(axis, offset=offset) return h
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_sources(topo, mixmaps, unmixmaps, global_scale=None, fig=None): """Plot all scalp projections of mixing- and unmixing-maps. .. note:: Parameter `topo` i...
urange, mrange = None, None m = len(mixmaps) if global_scale: tmp = np.asarray(unmixmaps) tmp = tmp[np.logical_not(np.isnan(tmp))] umax = np.percentile(np.abs(tmp), global_scale) umin = -umax urange = [umin, umax] tmp = np.asarray(mixmaps) tmp = tm...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_connectivity_topos(layout='diagonal', topo=None, topomaps=None, fig=None): """Place topo plots in a figure suitable for connectivity visualization. .. n...
m = len(topomaps) if fig is None: fig = new_figure() if layout == 'diagonal': for i in range(m): ax = fig.add_subplot(m, m, i*(1+m) + 1) plot_topo(ax, topo, topomaps[i]) ax.set_yticks([]) ax.set_xticks([]) ax.set_frame_on(False)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_connectivity_significance(s, fs=2, freq_range=(-np.inf, np.inf), diagonal=0, border=False, fig=None): """Plot significance. Significance is drawn as a b...
a = np.atleast_3d(s) [_, m, f] = a.shape freq = np.linspace(0, fs / 2, f) left = max(freq_range[0], freq[0]) right = min(freq_range[1], freq[-1]) imext = (freq[0], freq[-1], -1e25, 1e25) if fig is None: fig = new_figure() axes = [] for i in range(m): if diagonal...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_whiteness(var, h, repeats=1000, axis=None): """ Draw distribution of the Portmanteu whiteness test. Parameters var : :class:`~scot.var.VARBase`-like obj...
pr, q0, q = var.test_whiteness(h, repeats, True) if axis is None: axis = current_axis() pdf, _, _ = axis.hist(q0, 30, normed=True, label='surrogate distribution') axis.plot([q,q], [0,np.max(pdf)], 'r-', label='fitted model') #df = m*m*(h-p) #x = np.linspace(np.min(q0)*0.0, np.max(q0)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def singletrial(num_trials, skipstep=1): """ Single-trial cross-validation schema Use one trial for training, all others for testing. Parameters num_trials : int...
for t in range(0, num_trials, skipstep): trainset = [t] testset = [i for i in range(trainset[0])] + \ [i for i in range(trainset[-1] + 1, num_trials)] testset = sort([t % num_trials for t in testset]) yield trainset, testset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def splitset(num_trials, skipstep=None): """ Split-set cross validation Use half the trials for training, and the other half for testing. Then repeat the other w...
split = num_trials // 2 a = list(range(0, split)) b = list(range(split, num_trials)) yield a, b yield b, a
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_data(self, data, cl=None, time_offset=0): """ Assign data to the workspace. This function assigns a new data set to the workspace. Doing so invalidates c...
self.data_ = atleast_3d(data) self.cl_ = np.asarray(cl if cl is not None else [None]*self.data_.shape[0]) self.time_offset_ = time_offset self.var_model_ = None self.var_cov_ = None self.connectivity_ = None self.trial_mask_ = np.ones(self.cl_.size, dtype=bool) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_used_labels(self, labels): """ Specify which trials to use in subsequent analysis steps. This function masks trials based on their class labels. Paramete...
mask = np.zeros(self.cl_.size, dtype=bool) for l in labels: mask = np.logical_or(mask, self.cl_ == l) self.trial_mask_ = mask return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_sources(self, sources): """ Remove sources from the decomposition. This function removes sources from the decomposition. Doing so invalidates currentl...
if self.unmixing_ is None or self.mixing_ is None: raise RuntimeError("No sources available (run do_mvarica first)") self.mixing_ = np.delete(self.mixing_, sources, 0) self.unmixing_ = np.delete(self.unmixing_, sources, 1) if self.activations_ is not None: self.a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def keep_sources(self, keep): """Keep only the specified sources in the decomposition. """
if self.unmixing_ is None or self.mixing_ is None: raise RuntimeError("No sources available (run do_mvarica first)") n_sources = self.mixing_.shape[0] self.remove_sources(np.setdiff1d(np.arange(n_sources), np.array(keep))) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fit_var(self): """ Fit a VAR model to the source activations. Returns ------- self : Workspace The Workspace object. Raises ------ RuntimeError If the :class...
if self.activations_ is None: raise RuntimeError("VAR fitting requires source activations (run do_mvarica first)") self.var_.fit(data=self.activations_[self.trial_mask_, :, :]) self.connectivity_ = Connectivity(self.var_.coef, self.var_.rescov, self.nfft_) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_connectivity(self, measure_name, plot=False): """ Calculate spectral connectivity measure. Parameters measure_name : str Name of the connectivity measure...
if self.connectivity_ is None: raise RuntimeError("Connectivity requires a VAR model (run do_mvarica or fit_var first)") cm = getattr(self.connectivity_, measure_name)() cm = np.abs(cm) if np.any(np.iscomplex(cm)) else cm if plot is None or plot: fig = plot ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_surrogate_connectivity(self, measure_name, repeats=100, plot=False, random_state=None): """ Calculate spectral connectivity measure under the assumption ...
cs = surrogate_connectivity(measure_name, self.activations_[self.trial_mask_, :, :], self.var_, self.nfft_, repeats, random_state=random_state) if plot is None or plot: fig = plot if self.plot_diagonal == 'fill': diagonal = 0 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_bootstrap_connectivity(self, measure_names, repeats=100, num_samples=None, plot=False, random_state=None): """ Calculate bootstrap estimates of spectral ...
if num_samples is None: num_samples = np.sum(self.trial_mask_) cb = bootstrap_connectivity(measure_names, self.activations_[self.trial_mask_, :, :], self.var_, self.nfft_, repeats, num_samples, random_state=random_state) if plot is None or plot:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_source_topos(self, common_scale=None): """ Plot topography of the Source decomposition. Parameters common_scale : float, optional If set to None, each t...
if self.unmixing_ is None and self.mixing_ is None: raise RuntimeError("No sources available (run do_mvarica first)") self._prepare_plots(True, True) self.plotting.plot_sources(self.topo_, self.mixmaps_, self.unmixmaps_, common_scale)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_connectivity_topos(self, fig=None): """ Plot scalp projections of the sources. This function only plots the topos. Use in combination with connectivity ...
self._prepare_plots(True, False) if self.plot_outside_topo: fig = self.plotting.plot_connectivity_topos('outside', self.topo_, self.mixmaps_, fig) elif self.plot_diagonal == 'topo': fig = self.plotting.plot_connectivity_topos('diagonal', self.topo_, self.mixmaps_, fig) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_connectivity_surrogate(self, measure_name, repeats=100, fig=None): """ Plot spectral connectivity measure under the assumption of no actual connectivity...
cb = self.get_surrogate_connectivity(measure_name, repeats) self._prepare_plots(True, False) cu = np.percentile(cb, 95, axis=0) fig = self.plotting.plot_connectivity_spectrum([cu], self.fs_, freq_range=self.plot_f_range, fig=fig) return fig
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parallel_loop(func, n_jobs=1, verbose=1): """run loops in parallel, if joblib is available. Parameters func : function function to be executed in parallel n_...
if n_jobs: try: from joblib import Parallel, delayed except ImportError: try: from sklearn.externals.joblib import Parallel, delayed except ImportError: n_jobs = None if not n_jobs: if verbose: print('runni...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _convert_errors(func): """ Decorator to convert throws errors to Voluptuous format."""
cast_Invalid = lambda e: Invalid( u"{message}, expected {expected}".format( message=e.message, expected=e.expected) if e.expected != u'-none-' else e.message, e.path, six.text_type(e)) @wraps(func) def wrapper(*args, **kwargs): try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_compiled(self, name=None, key_schema=None, value_schema=None, as_mapping_key=None): """ When CompiledSchema compiles this marker, it sets informational va...
if self.name is None: self.name = name if self.key_schema is None: self.key_schema = key_schema if self.value_schema is None: self.value_schema = value_schema if as_mapping_key: self.as_mapping_key = True return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def colorlogs(format="short"): """Append a rainbow logging handler and a formatter to the root logger"""
try: from rainbow_logging_handler import RainbowLoggingHandler import sys # setup `RainbowLoggingHandler` logger = logging.root # same as default if format == "short": fmt = "%(message)s " else: fmt = "[%(asctime)s] %(name)s %(funcName...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """main bmi runner program"""
arguments = docopt.docopt(__doc__, version=__version__) colorlogs() # Read input file file wrapper = BMIWrapper( engine=arguments['<engine>'], configfile=arguments['<config>'] or '' ) # add logger if required if not arguments['--disable-logger']: logging.root.set...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_def_conf(): '''return default configurations as simple dict''' ret = dict() for k,v in defConf.items(): ret[k] = v[0] return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move(self): """ Advance game by single move, if possible. @return: logical indicator if move was performed. """
if len(self.moves) == MAX_MOVES: return False elif len(self.moves) % 2: active_engine = self.black_engine active_engine_name = self.black inactive_engine = self.white_engine inactive_engine_name = self.white else: active_en...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bestmove(self): """ Get proposed best move for current position. @return: dictionary with 'move', 'ponder', 'info' containing best move's UCI notation, ponde...
self.go() last_info = "" while True: text = self.stdout.readline().strip() split_text = text.split(' ') print(text) if split_text[0] == "info": last_info = Engine._bestmove_get_info(text) if split_text[0] == "bestmove":...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _bestmove_get_info(text): """ Parse stockfish evaluation output as dictionary. Examples of input: "info depth 2 seldepth 3 multipv 1 score cp -656 nodes 43 n...
result_dict = Engine._get_info_pv(text) result_dict.update(Engine._get_info_score(text)) single_value_fields = ['depth', 'seldepth', 'multipv', 'nodes', 'nps', 'tbhits', 'time'] for field in single_value_fields: result_dict.update(Engine._get_info_singlevalue_subfield(text,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isready(self): """ Used to synchronize the python engine object with the back-end engine. Sends 'isready' and waits for 'readyok.' """
self.put('isready') while True: text = self.stdout.readline().strip() if text == 'readyok': return text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def project_activity(index, start, end): """Compute the metrics for the project activity section of the enriched github pull requests index. Returns a dictionary...
results = { "metrics": [SubmittedPRs(index, start, end), ClosedPRs(index, start, end)] } return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def aggregations(self): """Get the single valued aggregations with respect to the previous time interval."""
prev_month_start = get_prev_month(self.end, self.query.interval_) self.query.since(prev_month_start) agg = super().aggregations() if agg is None: agg = 0 # None is because NaN in ES. Let's convert to 0 return agg
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def timeseries(self, dataframe=False): """Get BMIPR as a time series."""
closed_timeseries = self.closed.timeseries(dataframe=dataframe) opened_timeseries = self.opened.timeseries(dataframe=dataframe) return calculate_bmi(closed_timeseries, opened_timeseries)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_query(self, evolutionary=False): """ Basic query to get the metric values :param evolutionary: if True the metric values time series is returned. If Fals...
if not evolutionary: interval = None offset = None else: interval = self.interval offset = self.offset if not interval: raise RuntimeError("Evolutionary query without an interval.") query = ElasticQuery.get_agg(field=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_list(self): """ Extract from a DSL aggregated response the values for each bucket :return: a list with the values in a DSL aggregated response """
field = self.FIELD_NAME query = ElasticQuery.get_agg(field=field, date_field=self.FIELD_DATE, start=self.start, end=self.end, filters=self.esfilters) logger.debug("Metric: '%s' (%s); Q...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_metrics_data(self, query): """ Get the metrics data from Elasticsearch given a DSL query :param query: query to be sent to Elasticsearch :return: a dict ...
if self.es_url.startswith("http"): url = self.es_url else: url = 'http://' + self.es_url es = Elasticsearch(url) s = Search(using=es, index=self.es_index) s = s.update_from_dict(query) try: response = s.execute() return res...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_ts(self): """ Returns a time series of a specific class A timeseries consists of a unixtime date, labels, some other fields and the data of the specific ...
query = self.get_query(True) res = self.get_metrics_data(query) # Time to convert it to our grimoire timeseries format ts = {"date": [], "value": [], "unixtime": []} agg_id = ElasticQuery.AGGREGATION_ID if 'buckets' not in res['aggregations'][str(agg_id)]: r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_agg(self): """ Returns the aggregated value for the metric :return: the value of the metric """
""" Returns an aggregated value """ query = self.get_query(False) res = self.get_metrics_data(query) # We need to extract the data from the JSON res # If we have agg data use it agg_id = str(ElasticQuery.AGGREGATION_ID) if 'aggregations' in res and 'values' in re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_trend(self): """ Get the trend for the last two metric values using the interval defined in the metric :return: a tuple with the metric value for the las...
""" """ # TODO: We just need the last two periods, not the full ts ts = self.get_ts() last = ts['value'][len(ts['value']) - 1] prev = ts['value'][len(ts['value']) - 2] trend = last - prev trend_percentage = None if last == 0: if prev > 0: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _load_preset(self, path): ''' load, validate and store a single preset file''' try: with open(path, 'r') as f: presetBody = json.load(f) except IOError as e: raise PresetException("IOError: " + e.strerror) except ValueError as e: r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def validate(self, data): ''' Checks if `data` respects this preset specification It will check that every required property is present and for every property type it will make some specific control. ''' for prop in self.properties: if prop.id in data: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def requestedFormat(request,acceptedFormat): """Return the response format requested by client Client could specify requested format using: (options are processe...
if 'format' in request.args: fieldFormat = request.args.get('format') if fieldFormat not in acceptedFormat: raise ValueError("requested format not supported: "+ fieldFormat) return fieldFormat else: return request.accept_mimetypes.best_mat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def routes_collector(gatherer): """Decorator utility to collect flask routes in a dictionary. This function together with :func:`add_routes` provides an easy way...
def hatFunc(rule, **options): def decorator(f): rule_dict = {'rule':rule, 'view_func':f} rule_dict.update(options) gatherer.append(rule_dict) return decorator return hatFunc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_routes(fapp, routes, prefix=""): """Batch routes registering Register routes to a blueprint/flask_app previously collected with :func:`routes_collector`....
for r in routes: r['rule'] = prefix + r['rule'] fapp.add_url_rule(**r)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_centered_pagination(current, total, visible=5): ''' Return the range of pages to render in a pagination menu. The current page is always kept in the middle except for the edge cases. Reeturns a dict { prev, first, current, last, next } :param current: the curre...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fwhm(x, y, k=10): # http://stackoverflow.com/questions/10582795/finding-the-full-width-half-maximum-of-a-peak """ Determine full-with-half-maximum of a peake...
class MultiplePeaks(Exception): pass class NoPeaksFound(Exception): pass half_max = np.amax(y) / 2.0 s = splrep(x, y - half_max) roots = sproot(s) if len(roots) > 2: raise MultiplePeaks("The dataset appears to have multiple peaks, and " "t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(arguments): """ Main function of smatch score calculation """
global verbose global veryVerbose global iteration_num global single_score global pr_flag global match_triple_dict # set the iteration number # total iteration number = restart number + 1 iteration_num = arguments.r + 1 if arguments.ms: single_score = False if argume...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def normalize_volume(volume): '''convert volume metadata from es to archivant format This function makes side effect on input volume output example:: { 'id': 'AU0paPZOMZchuDv1iDv8', 'type': 'volume', 'metadata': {'_language': '...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def normalize_attachment(attachment): ''' Convert attachment metadata from es to archivant format This function makes side effect on input attachment ''' res = dict() res['type'] = 'attachment' res['id'] = attachment['id'] del(attachment['id']) res['u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def denormalize_volume(volume): '''convert volume metadata from archivant to es format''' id = volume.get('id', None) res = dict() res.update(volume['metadata']) denorm_attachments = list() for a in volume['attachments']: denorm_attachments.append(Archivant.de...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def denormalize_attachment(attachment): '''convert attachment metadata from archivant to es format''' res = dict() ext = ['id', 'url'] for k in ext: if k in attachment['metadata']: raise ValueError("metadata section could not contain special key '{}'".format(k...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def iter_all_volumes(self): '''iterate over all stored volumes''' for raw_volume in self._db.iterate_all(): v = self.normalize_volume(raw_volume) del v['score'] yield v
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def delete_attachments(self, volumeID, attachmentsID): ''' delete attachments from a volume ''' log.debug("deleting attachments from volume '{}': {}".format(volumeID, attachmentsID)) rawVolume = self._req_raw_volume(volumeID) insID = [a['id'] for a in rawVolume['_source']['_attachments']...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def insert_attachments(self, volumeID, attachments): ''' add attachments to an already existing volume ''' log.debug("adding new attachments to volume '{}': {}".format(volumeID, attachments)) if not attachments: return rawVolume = self._req_raw_volume(volumeID) attsID...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def insert_volume(self, metadata, attachments=[]): '''Insert a new volume Returns the ID of the added volume `metadata` must be a dict containg metadata of the volume:: { "_language" : "it", # language of the metadata "key1" : "value1", # attribute ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _assemble_attachment(self, file, metadata): ''' store file and return a dict containing assembled metadata param `file` must be a path or a File Object param `metadata` must be a dict: { "name" : "nome_buffo.ext" # name of the file (extensi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def update_volume(self, volumeID, metadata): '''update existing volume metadata the given metadata will substitute the old one ''' log.debug('updating volume metadata: {}'.format(volumeID)) rawVolume = self._req_raw_volume(volumeID) normalized = self.normalize_volume(r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def update_attachment(self, volumeID, attachmentID, metadata): '''update an existing attachment the given metadata dict will be merged with the old one. only the following fields could be updated: [name, mime, notes, download_count] ''' log.debug('updating metadata of at...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dangling_files(self): '''iterate over fsdb files no more attached to any volume''' for fid in self._fsdb: if not self._db.file_is_attached('fsdb:///' + fid): yield fid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_string(data, position, obj_end, dummy): """Decode a BSON string to python unicode string."""
length = _UNPACK_INT(data[position:position + 4])[0] position += 4 if length < 1 or obj_end - position < length: raise InvalidBSON("invalid string length") end = position + length - 1 if data[end:end + 1] != b"\x00": raise InvalidBSON("invalid end of string") return _utf_8_decod...