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 selection(self): """A complete |Selection| object of all "supplying" and "routing" elements and required nodes. Selection("complete", nodes=("node_1123", "no...
return selectiontools.Selection( self.selection_name, self.nodes, self.elements)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chars2str(chars) -> List[str]: """Inversion function of function |str2chars|. ['zeros', 'ones'] [] """
strings = collections.deque() for subchars in chars: substrings = collections.deque() for char in subchars: if char: substrings.append(char.decode('utf-8')) else: substrings.append('') strings.append(''.join(substrings)) return...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_dimension(ncfile, name, length) -> None: """Add a new dimension with the given name and length to the given NetCDF file. Essentially, |create_dimension...
try: ncfile.createDimension(name, length) except BaseException: objecttools.augment_excmessage( 'While trying to add dimension `%s` with length `%d` ' 'to the NetCDF file `%s`' % (name, length, get_filepath(ncfile)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_variable(ncfile, name, datatype, dimensions) -> None: """Add a new variable with the given name, datatype, and dimensions to the given NetCDF file. Ess...
default = fillvalue if (datatype == 'f8') else None try: ncfile.createVariable( name, datatype, dimensions=dimensions, fill_value=default) ncfile[name].long_name = name except BaseException: objecttools.augment_excmessage( 'While trying to add variable `%s` w...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query_variable(ncfile, name) -> netcdf4.Variable: """Return the variable with the given name from the given NetCDF file. Essentially, |query_variable| just pe...
try: return ncfile[name] except (IndexError, KeyError): raise OSError( 'NetCDF file `%s` does not contain variable `%s`.' % (get_filepath(ncfile), 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 query_timegrid(ncfile) -> timetools.Timegrid: """Return the |Timegrid| defined by the given NetCDF file. Timegrid('1996-01-01 00:00:00', '2007-01-01 00:00:00'...
timepoints = ncfile[varmapping['timepoints']] refdate = timetools.Date.from_cfunits(timepoints.units) return timetools.Timegrid.from_timepoints( timepoints=timepoints[:], refdate=refdate, unit=timepoints.units.strip().split()[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 query_array(ncfile, name) -> numpy.ndarray: """Return the data of the variable with the given name from the given NetCDF file. The following example shows tha...
variable = query_variable(ncfile, name) maskedarray = variable[:] fillvalue_ = getattr(variable, '_FillValue', numpy.nan) if not numpy.isnan(fillvalue_): maskedarray[maskedarray.mask] = numpy.nan return maskedarray.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 log(self, sequence, infoarray) -> None: """Prepare a |NetCDFFile| object suitable for the given |IOSequence| object, when necessary, and pass the given argume...
if isinstance(sequence, sequencetools.ModelSequence): descr = sequence.descr_model else: descr = 'node' if self._isolate: descr = '%s_%s' % (descr, sequence.descr_sequence) if ((infoarray is not None) and (infoarray.info['type'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self) -> None: """Call method |NetCDFFile.read| of all handled |NetCDFFile| objects. """
for folder in self.folders.values(): for file_ in folder.values(): file_.read()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self) -> None: """Call method |NetCDFFile.write| of all handled |NetCDFFile| objects. """
if self.folders: init = hydpy.pub.timegrids.init timeunits = init.firstdate.to_cfunits('hours') timepoints = init.to_timepoints('hours') for folder in self.folders.values(): for file_ in folder.values(): file_.write(timeunits, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: """A |tuple| of names of all handled |NetCDFFile| objects."""
return tuple(sorted(set(itertools.chain( *(_.keys() for _ in self.folders.values())))))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log(self, sequence, infoarray) -> None: """Pass the given |IoSequence| to a suitable instance of a |NetCDFVariableBase| subclass. When writing data, the secon...
aggregated = ((infoarray is not None) and (infoarray.info['type'] != 'unmodified')) descr = sequence.descr_sequence if aggregated: descr = '_'.join([descr, infoarray.info['type']]) if descr in self.variables: var_ = self.variables[descr] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filepath(self) -> str: """The NetCDF file path."""
return os.path.join(self._dirpath, self.name + '.nc')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self) -> None: """Open an existing NetCDF file temporarily and call method |NetCDFVariableDeep.read| of all handled |NetCDFVariableBase| objects."""
try: with netcdf4.Dataset(self.filepath, "r") as ncfile: timegrid = query_timegrid(ncfile) for variable in self.variables.values(): variable.read(ncfile, timegrid) except BaseException: objecttools.augment_excmessage( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, timeunit, timepoints) -> None: """Open a new NetCDF file temporarily and call method |NetCDFVariableBase.write| of all handled |NetCDFVariableBase...
with netcdf4.Dataset(self.filepath, "w") as ncfile: ncfile.Conventions = 'CF-1.6' self._insert_timepoints(ncfile, timepoints, timeunit) for variable in self.variables.values(): variable.write(ncfile)
<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_index(self, name_subdevice) -> int: """Item access to the wrapped |dict| object with a specialized error message."""
try: return self.dict_[name_subdevice] except KeyError: raise OSError( 'No data for sequence `%s` and (sub)device `%s` ' 'in NetCDF file `%s` available.' % (self.name_sequence, name_subdevice, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log(self, sequence, infoarray) -> None: """Log the given |IOSequence| object either for reading or writing data. The optional `array` argument allows for pass...
descr_device = sequence.descr_device self.sequences[descr_device] = sequence self.arrays[descr_device] = infoarray
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort_timeplaceentries(self, timeentry, placeentry) -> Tuple[Any, Any]: """Return a |tuple| containing the given `timeentry` and `placeentry` sorted in agreeme...
if self._timeaxis: return placeentry, timeentry return timeentry, placeentry
<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_timeplaceslice(self, placeindex) -> \ Union[Tuple[slice, int], Tuple[int, slice]]: """Return a |tuple| for indexing a complete time series of a certain lo...
return self.sort_timeplaceentries(slice(None), int(placeindex))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: """A |tuple| containing the device names."""
self: NetCDFVariableBase return tuple(self.sequences.keys())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: """Return a |tuple| of one |int| and some |slice| objects to accesses all values of a certain device within |NetCDFVariableDeep.array|. (2, slice(None, None, None...
slices = list(self.get_timeplaceslice(idx)) for length in shape: slices.append(slice(0, length)) return tuple(slices)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: """Required shape of |NetCDFVariableDeep.array|. For the default configuration, the first axis corresponds to the number of devices, and the second one to the num...
nmb_place = len(self.sequences) nmb_time = len(hydpy.pub.timegrids.init) nmb_others = collections.deque() for sequence in self.sequences.values(): nmb_others.append(sequence.shape) nmb_others_max = tuple(numpy.max(nmb_others, axis=0)) return self.sort_timepla...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def array(self) -> numpy.ndarray: """The series data of all logged |IOSequence| objects contained in one single |numpy.ndarray|. The documentation on |NetCDFVaria...
array = numpy.full(self.shape, fillvalue, dtype=float) for idx, (descr, subarray) in enumerate(self.arrays.items()): sequence = self.sequences[descr] array[self.get_slices(idx, sequence.shape)] = subarray return array
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shape(self) -> Tuple[int, int]: """Required shape of |NetCDFVariableAgg.array|. For the default configuration, the first axis corresponds to the number of dev...
return self.sort_timeplaceentries( len(hydpy.pub.timegrids.init), len(self.sequences))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def array(self) -> numpy.ndarray: """The aggregated data of all logged |IOSequence| objects contained in one single |numpy.ndarray| object. The documentation on |...
array = numpy.full(self.shape, fillvalue, dtype=float) for idx, subarray in enumerate(self.arrays.values()): array[self.get_timeplaceslice(idx)] = subarray return array
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shape(self) -> Tuple[int, int]: """Required shape of |NetCDFVariableFlat.array|. For 0-dimensional sequences like |lland_inputs.Nied| and for the default conf...
return self.sort_timeplaceentries( len(hydpy.pub.timegrids.init), sum(len(seq) for seq in self.sequences.values()))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def array(self) -> numpy.ndarray: """The series data of all logged |IOSequence| objects contained in one single |numpy.ndarray| object. The documentation on |NetC...
array = numpy.full(self.shape, fillvalue, dtype=float) idx0 = 0 idxs: List[Any] = [slice(None)] for seq, subarray in zip(self.sequences.values(), self.arrays.values()): for prod in self._product(seq.shape): subsubarray = subar...
<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(self): """Determine the number of substeps. Initialize a llake model and assume a simulation step size of 12 hours: If the maximum internal step size ...
maxdt = self.subpars.pars.control.maxdt seconds = self.simulationstep.seconds self.value = numpy.ceil(seconds/maxdt)
<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(self): """Calulate the auxilary term. vq(toy_1_1_0_0_0=[0.0, 243200.0, 2086400.0], toy_7_1_0_0_0=[0.0, 286400.0, 2216000.0]) """
con = self.subpars.pars.control der = self.subpars for (toy, qs) in con.q: setattr(self, str(toy), 2.*con.v+der.seconds/der.nmbsubsteps*qs) self.refresh()
<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_io_example_1() -> Tuple[devicetools.Nodes, devicetools.Elements]: # noinspection PyUnresolvedReferences """Prepare an IO example configuration. (1) Pr...
from hydpy import TestIO TestIO.clear() from hydpy.core.filetools import SequenceManager hydpy.pub.sequencemanager = SequenceManager() with TestIO(): hydpy.pub.sequencemanager.inputdirpath = 'inputpath' hydpy.pub.sequencemanager.fluxdirpath = 'outputpath' hydpy.pub.sequencem...
<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_postalcodes_around_radius(self, pc, radius): postalcodes = self.get(pc) if postalcodes is None: raise PostalCodeNotFoundException("Could not find postal code you're searching for.") else: pc = postalcodes[0] radius = float(radius) ...
<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_all_team_ids(): """Returns a pandas DataFrame with all Team IDs"""
df = get_all_player_ids("all_data") df = pd.DataFrame({"TEAM_NAME": df.TEAM_NAME.unique(), "TEAM_ID": df.TEAM_ID.unique()}) return df
<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_team_id(team_name): """ Returns the team ID associated with the team name that is passed in. Parameters team_name : str The team name whose ID we want. N...
df = get_all_team_ids() df = df[df.TEAM_NAME == team_name] if len(df) == 0: er = "Invalid team name or there is no team with that name." raise ValueError(er) team_id = df.TEAM_ID.iloc[0] return team_id
<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_game_logs(self): """Returns team game logs as a pandas DataFrame"""
logs = self.response.json()['resultSets'][0]['rowSet'] headers = self.response.json()['resultSets'][0]['headers'] df = pd.DataFrame(logs, columns=headers) df.GAME_DATE = pd.to_datetime(df.GAME_DATE) return df
<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_game_id(self, date): """Returns the Game ID associated with the date that is passed in. Parameters date : str The date associated with the game whose Gam...
df = self.get_game_logs() game_id = df[df.GAME_DATE == date].Game_ID.values[0] return game_id
<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_params(self, parameters): """Pass in a dictionary to update url parameters for NBA stats API Parameters parameters : dict A dict containing key, value...
self.url_paramaters.update(parameters) self.response = requests.get(self.base_url, params=self.url_paramaters, headers=HEADERS) # raise error if status code is not 200 self.response.raise_for_status() 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_shots(self): """Returns the shot chart data as a pandas DataFrame."""
shots = self.response.json()['resultSets'][0]['rowSet'] headers = self.response.json()['resultSets'][0]['headers'] return pd.DataFrame(shots, columns=headers)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unsubscribe(self, subscription, max=None): """ Unsubscribe will remove interest in the given subject. If max is provided an automatic Unsubscribe that is pro...
if max is None: self._send('UNSUB %d' % subscription.sid) self._subscriptions.pop(subscription.sid) else: subscription.max = max self._send('UNSUB %d %s' % (subscription.sid, max))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def request(self, subject, callback, msg=None): """ ublish a message with an implicit inbox listener as the reply. Message is optional. Args: subject (string): ...
inbox = self._build_inbox() s = self.subscribe(inbox, callback) self.unsubscribe(s, 1) self.publish(subject, msg, inbox) return 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 draw_court(ax=None, color='gray', lw=1, outer_lines=False): """Returns an axes with a basketball court drawn onto to it. This function draws a court based on...
if ax is None: ax = plt.gca() # Create the various parts of an NBA basketball court # Create the basketball hoop hoop = Circle((0, 0), radius=7.5, linewidth=lw, color=color, fill=False) # Create backboard backboard = Rectangle((-30, -12.5), 60, 0, linewidth=lw, color=color) # Th...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shot_chart(x, y, kind="scatter", title="", color="b", cmap=None, xlim=(-250, 250), ylim=(422.5, -47.5), court_color="gray", court_lw=1, outer_lines=False, fli...
if ax is None: ax = plt.gca() if cmap is None: cmap = sns.light_palette(color, as_cmap=True) if not flip_court: ax.set_xlim(xlim) ax.set_ylim(ylim) else: ax.set_xlim(xlim[::-1]) ax.set_ylim(ylim[::-1]) ax.tick_params(labelbottom="off", labelleft="...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shot_chart_jointplot(x, y, data=None, kind="scatter", title="", color="b", cmap=None, xlim=(-250, 250), ylim=(422.5, -47.5), court_color="gray", court_lw=1, o...
# If a colormap is not provided, then it is based off of the color if cmap is None: cmap = sns.light_palette(color, as_cmap=True) if kind not in ["scatter", "kde", "hex"]: raise ValueError("kind must be 'scatter', 'kde', or 'hex'.") grid = sns.jointplot(x=x, y=y, data=data, stat_func...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def heatmap(x, y, z, title="", cmap=plt.cm.YlOrRd, bins=20, xlim=(-250, 250), ylim=(422.5, -47.5), facecolor='lightgray', facecolor_alpha=0.4, court_color="black"...
# Bin the FGA (x, y) and Calculcate the mean number of times shot was # made (z) within each bin # mean is the calculated FG percentage for each bin mean, xedges, yedges, binnumber = binned_statistic_2d(x=x, y=y, values=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 bokeh_draw_court(figure, line_color='gray', line_width=1): """Returns a figure with the basketball court lines drawn onto it This function draws a court base...
# hoop figure.circle(x=0, y=0, radius=7.5, fill_alpha=0, line_color=line_color, line_width=line_width) # backboard figure.line(x=range(-30, 31), y=-12.5, line_color=line_color) # The paint # outerbox figure.rect(x=0, y=47.5, width=160, height=190, fill_alpha=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 bokeh_shot_chart(data, x="LOC_X", y="LOC_Y", fill_color="#1f77b4", scatter_size=10, fill_alpha=0.4, line_alpha=0.4, court_line_color='gray', court_line_width=...
source = ColumnDataSource(data) fig = figure(width=700, height=658, x_range=[-250, 250], y_range=[422.5, -47.5], min_border=0, x_axis_type=None, y_axis_type=None, outline_line_color="black", **kwargs) fig.scatter(x, y, source=source, size=scatter_size, color=fill_color, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _kmedoids_run(X, n_clusters, distance, max_iter, tol, rng): """ Run a single trial of k-medoids clustering on dataset X, and given number of clusters """
membs = np.empty(shape=X.shape[0], dtype=int) centers = kmeans._kmeans_init(X, n_clusters, method='', rng=rng) sse_last = 9999.9 n_iter = 0 for it in range(1,max_iter): membs = kmeans._assign_clusters(X, centers) centers,sse_arr = _update_centers(X, membs, n_clusters, distance) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _init_mixture_params(X, n_mixtures, init_method): """ Initialize mixture density parameters with equal priors random means identity covariance matrices """
init_priors = np.ones(shape=n_mixtures, dtype=float) / n_mixtures if init_method == 'kmeans': km = _kmeans.KMeans(n_clusters = n_mixtures, n_trials=20) km.fit(X) init_means = km.centers_ else: inx_rand = np.random.choice(X.shape[0], size=n_mixtures) init_means = X...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __log_density_single(x, mean, covar): """ This is just a test function to calculate the normal density at x given mean and covariance matrix. Note: this func...
n_dim = mean.shape[0] dx = x - mean covar_inv = scipy.linalg.inv(covar) covar_det = scipy.linalg.det(covar) den = np.dot(np.dot(dx.T, covar_inv), dx) + n_dim*np.log(2*np.pi) + np.log(covar_det) return(-1/2 * den)
<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_params(priors, means, covars): """ Validation Check for M.L. paramateres """
for i,(p,m,cv) in enumerate(zip(priors, means, covars)): if np.any(np.isinf(p)) or np.any(np.isnan(p)): raise ValueError("Component %d of priors is not valid " % i) if np.any(np.isinf(m)) or np.any(np.isnan(m)): raise ValueError("Component %d of means is not valid " % 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 fit(self, X): """ Fit mixture-density parameters with EM algorithm """
params_dict = _fit_gmm_params(X=X, n_mixtures=self.n_clusters, \ n_init=self.n_trials, init_method=self.init_method, \ n_iter=self.max_iter, tol=self.tol) self.priors_ = params_dict['priors'] self.means_ = params_dict['means'] self.covars...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _kmeans_init(X, n_clusters, method='balanced', rng=None): """ Initialize k=n_clusters centroids randomly """
n_samples = X.shape[0] if rng is None: cent_idx = np.random.choice(n_samples, replace=False, size=n_clusters) else: #print('Generate random centers using RNG') cent_idx = rng.choice(n_samples, replace=False, size=n_clusters) centers = X[cent_idx,:] mean_X = np.mean(X, 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 _cal_dist2center(X, center): """ Calculate the SSE to the cluster center """
dmemb2cen = scipy.spatial.distance.cdist(X, center.reshape(1,X.shape[1]), metric='seuclidean') return(np.sum(dmemb2cen))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _kmeans_run(X, n_clusters, max_iter, tol): """ Run a single trial of k-means clustering on dataset X, and given number of clusters """
membs = np.empty(shape=X.shape[0], dtype=int) centers = _kmeans_init(X, n_clusters) sse_last = 9999.9 n_iter = 0 for it in range(1,max_iter): membs = _assign_clusters(X, centers) centers,sse_arr = _update_centers(X, membs, n_clusters) sse_total = np.sum(sse_arr) if ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _kmeans(X, n_clusters, max_iter, n_trials, tol): """ Run multiple trials of k-means clustering, and outputt he best centers, and cluster labels """
n_samples, n_features = X.shape[0], X.shape[1] centers_best = np.empty(shape=(n_clusters,n_features), dtype=float) labels_best = np.empty(shape=n_samples, dtype=int) for i in range(n_trials): centers, labels, sse_tot, sse_arr, n_iter = _kmeans_run(X, n_clusters, max_iter, tol) if 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 _cut_tree(tree, n_clusters, membs): """ Cut the tree to get desired number of clusters as n_clusters 2 <= n_desired <= n_clusters """
## starting from root, ## a node is added to the cut_set or ## its children are added to node_set assert(n_clusters >= 2) assert(n_clusters <= len(tree.leaves())) cut_centers = dict() #np.empty(shape=(n_clusters, ndim), dtype=float) for i in range(n_clusters-1): if i==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 _add_tree_node(tree, label, ilev, X=None, size=None, center=None, sse=None, parent=None): """ Add a node to the tree if parent is not known, the node is a ro...
if size is None: size = X.shape[0] if (center is None): center = np.mean(X, axis=0) if (sse is None): sse = _kmeans._cal_dist2center(X, center) center = list(center) datadict = { 'size' : size, 'center': center, 'label' : label, 'sse' : ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _bisect_kmeans(X, n_clusters, n_trials, max_iter, tol): """ Apply Bisecting Kmeans clustering to reach n_clusters number of clusters """
membs = np.empty(shape=X.shape[0], dtype=int) centers = dict() #np.empty(shape=(n_clusters,X.shape[1]), dtype=float) sse_arr = dict() #-1.0*np.ones(shape=n_clusters, dtype=float) ## data structure to store cluster hierarchies tree = treelib.Tree() tree = _add_tree_node(tree, 0, ilev=0, X=X) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def comparison_table(self, caption=None, label="tab:model_comp", hlines=True, aic=True, bic=True, dic=True, sort="bic", descending=True): # pragma: no cover """ ...
if sort == "bic": assert bic, "You cannot sort by BIC if you turn it off" if sort == "aic": assert aic, "You cannot sort by AIC if you turn it off" if sort == "dic": assert dic, "You cannot sort by DIC if you turn it off" if caption is 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 plot_walks(self, parameters=None, truth=None, extents=None, display=False, filename=None, chains=None, convolve=None, figsize=None, plot_weights=True, plot_po...
chains, parameters, truth, extents, _ = self._sanitise(chains, parameters, truth, extents) n = len(parameters) extra = 0 if plot_weights: plot_weights = plot_weights and np.any([np.any(c.weights != 1.0) for c in chains]) plot_posterior = plot_posterior and np.any(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gelman_rubin(self, chain=None, threshold=0.05): r""" Runs the Gelman Rubin diagnostic on the supplied chains. Parameters chain : int|str, optional Which chai...
if chain is None: return np.all([self.gelman_rubin(k, threshold=threshold) for k in range(len(self.parent.chains))]) index = self.parent._get_chain(chain) assert len(index) == 1, "Please specify only one chain, have %d chains" % len(index) chain = self.parent.chains[index[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 geweke(self, chain=None, first=0.1, last=0.5, threshold=0.05): """ Runs the Geweke diagnostic on the supplied chains. Parameters chain : int|str, optional Wh...
if chain is None: return np.all([self.geweke(k, threshold=threshold) for k in range(len(self.parent.chains))]) index = self.parent._get_chain(chain) assert len(index) == 1, "Please specify only one chain, have %d chains" % len(index) chain = self.parent.chains[index[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_latex_table(self, parameters=None, transpose=False, caption=None, label="tab:model_params", hlines=True, blank_fill="--"): # pragma: no cover """ Generat...
if parameters is None: parameters = self.parent._all_parameters for p in parameters: assert isinstance(p, str), \ "Generating a LaTeX table requires all parameters have labels" num_parameters = len(parameters) num_chains = len(self.parent.chains) ...
<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_summary(self, squeeze=True, parameters=None, chains=None): """ Gets a summary of the marginalised parameter distributions. Parameters squeeze : bool, opt...
results = [] if chains is None: chains = self.parent.chains else: if isinstance(chains, (int, str)): chains = [chains] chains = [self.parent.chains[i] for c in chains for i in self.parent._get_chain(c)] for chain in chains: ...
<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_max_posteriors(self, parameters=None, squeeze=True, chains=None): """ Gets the maximum posterior point in parameter space from the passed parameters. Req...
results = [] if chains is None: chains = self.parent.chains else: if isinstance(chains, (int, str)): chains = [chains] chains = [self.parent.chains[i] for c in chains for i in self.parent._get_chain(c)] if isinstance(parameters, str)...
<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_correlations(self, chain=0, parameters=None): """ Takes a chain and returns the correlation between chain parameters. Parameters chain : int|str, optiona...
parameters, cov = self.get_covariance(chain=chain, parameters=parameters) diag = np.sqrt(np.diag(cov)) divisor = diag[None, :] * diag[:, None] correlations = cov / divisor return parameters, correlations
<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_covariance(self, chain=0, parameters=None): """ Takes a chain and returns the covariance between chain parameters. Parameters chain : int|str, optional T...
index = self.parent._get_chain(chain) assert len(index) == 1, "Please specify only one chain, have %d chains" % len(index) chain = self.parent.chains[index[0]] if parameters is None: parameters = chain.parameters data = chain.get_data(parameters) cov = np.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 get_correlation_table(self, chain=0, parameters=None, caption="Parameter Correlations", label="tab:parameter_correlations"): """ Gets a LaTeX table of parame...
parameters, cor = self.get_correlations(chain=chain, parameters=parameters) return self._get_2d_latex_table(parameters, cor, caption, label)
<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_covariance_table(self, chain=0, parameters=None, caption="Parameter Covariance", label="tab:parameter_covariance"): """ Gets a LaTeX table of parameter c...
parameters, cov = self.get_covariance(chain=chain, parameters=parameters) return self._get_2d_latex_table(parameters, cov, caption, label)
<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_parameter_text(self, lower, maximum, upper, wrap=False): """ Generates LaTeX appropriate text from marginalised parameter bounds. Parameters lower : floa...
if lower is None or upper is None: return "" upper_error = upper - maximum lower_error = maximum - lower if upper_error != 0 and lower_error != 0: resolution = min(np.floor(np.log10(np.abs(upper_error))), np.floor(np.log10(np.abs(lower...
<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_chain(self, chain=-1): """ Removes a chain from ChainConsumer. Calling this will require any configurations set to be redone! Parameters chain : int|s...
if isinstance(chain, str) or isinstance(chain, int): chain = [chain] chain = sorted([i for c in chain for i in self._get_chain(c)])[::-1] assert len(chain) == len(list(set(chain))), "Error, you are trying to remove a chain more than once." for index in chain: d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure_truth(self, **kwargs): # pragma: no cover """ Configure the arguments passed to the ``axvline`` and ``axhline`` methods when plotting truth values....
if kwargs.get("ls") is None and kwargs.get("linestyle") is None: kwargs["ls"] = "--" kwargs["dashes"] = (3, 3) if kwargs.get("color") is None: kwargs["color"] = "#000000" self.config_truth = kwargs self._configured_truth = 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 divide_chain(self, chain=0): """ Returns a ChainConsumer instance containing all the walks of a given chain as individual chains themselves. This method migh...
indexes = self._get_chain(chain) con = ChainConsumer() for index in indexes: chain = self.chains[index] assert chain.walkers is not None, "The chain you have selected was not added with any walkers!" num_walkers = chain.walkers data = np.split(ch...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def threshold(args): """Calculate motif score threshold for a given FPR."""
if args.fpr < 0 or args.fpr > 1: print("Please specify a FPR between 0 and 1") sys.exit(1) motifs = read_motifs(args.pwmfile) s = Scanner() s.set_motifs(args.pwmfile) s.set_threshold(args.fpr, filename=args.inputfile) print("Motif\tScore\tCutoff") for motif in motifs:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def values_to_labels(fg_vals, bg_vals): """ Convert two arrays of values to an array of labels and an array of scores. Parameters fg_vals : array_like The list o...
y_true = np.hstack((np.ones(len(fg_vals)), np.zeros(len(bg_vals)))) y_score = np.hstack((fg_vals, bg_vals)) return y_true, y_score
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def max_enrichment(fg_vals, bg_vals, minbg=2): """ Computes the maximum enrichment. Parameters fg_vals : array_like The list of values for the positive set. bg_v...
scores = np.hstack((fg_vals, bg_vals)) idx = np.argsort(scores) x = np.hstack((np.ones(len(fg_vals)), np.zeros(len(bg_vals)))) xsort = x[idx] l_fg = len(fg_vals) l_bg = len(bg_vals) m = 0 s = 0 for i in range(len(scores), 0, -1): bgcount = float(len(xsort[i:][xsort[i:] == 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 roc_auc_xlim(x_bla, y_bla, xlim=0.1): """ Computes the ROC Area Under Curve until a certain FPR value. Parameters fg_vals : array_like list of values for pos...
x = x_bla[:] y = y_bla[:] x.sort() y.sort() u = {} for i in x + y: u[i] = 1 vals = sorted(u.keys()) len_x = float(len(x)) len_y = float(len(y)) new_x = [] new_y = [] x_p = 0 y_p = 0 for val in vals[::-1]: while len(x) > 0 and x[-...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def max_fmeasure(fg_vals, bg_vals): """ Computes the maximum F-measure. Parameters fg_vals : array_like The list of values for the positive set. bg_vals : array_...
x, y = roc_values(fg_vals, bg_vals) x, y = x[1:], y[1:] # don't include origin p = y / (y + x) filt = np.logical_and((p * y) > 0, (p + y) > 0) p = p[filt] y = y[filt] f = (2 * p * y) / (p + y) if len(f) > 0: #return np.nanmax(f), np.nanmax(y[f == np.nanmax(f)]) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ks_pvalue(fg_pos, bg_pos=None): """ Computes the Kolmogorov-Smirnov p-value of position distribution. Parameters fg_pos : array_like The list of values for t...
if len(fg_pos) == 0: return 1.0 a = np.array(fg_pos, dtype="float") / max(fg_pos) p = kstest(a, "uniform")[1] return 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 ks_significance(fg_pos, bg_pos=None): """ Computes the -log10 of Kolmogorov-Smirnov p-value of position distribution. Parameters fg_pos : array_like The list...
p = ks_pvalue(fg_pos, max(fg_pos)) if p > 0: return -np.log10(p) else: return np.inf
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_data(): """Load and shape data for training with Keras + Pescador. Returns ------- input_shape : tuple, len=3 Shape of each sample; adapts to channel c...
# The data, shuffled and split between train and test sets (x_train, y_train), (x_test, y_test) = mnist.load_data() if K.image_data_format() == 'channels_first': x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_col...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_model(input_shape): """Create a compiled Keras model. Parameters input_shape : tuple, len=3 Shape of each image sample. Returns ------- model : keras.M...
model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(Conv2D(64, kernel_size=(3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def sampler(X, y): '''A basic generator for sampling data. Parameters ---------- X : np.ndarray, len=n_samples, ndim=4 Image data. y : np.ndarray, len=n_samples, ndim=2 One-hot encoded class vectors. Yields ------ data : dict Single image sample, like {X: np.nd...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def additive_noise(stream, key='X', scale=1e-1): '''Add noise to a data stream. Parameters ---------- stream : iterable A stream that yields data objects. key : string, default='X' Name of the field to add noise. scale : float, default=0.1 Scale factor for gaussian noi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_denovo_params(user_params=None): """Return default GimmeMotifs parameters. Defaults will be replaced with parameters defined in user_params. Parameters...
config = MotifConfig() if user_params is None: user_params = {} params = config.get_default_params() params.update(user_params) if params.get("torque"): logger.debug("Using torque") else: logger.debug("Using multiprocessing") params["background"] = [x.strip() for ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rankagg(df, method="stuart"): """Return aggregated ranks. Implementation is ported from the RobustRankAggreg R package References: Kolde et al., 2012, DOI: 1...
rmat = pd.DataFrame(index=df.iloc[:,0]) step = 1 / rmat.shape[0] for col in df.columns: rmat[col] = pd.DataFrame({col:np.arange(step, 1 + step, step)}, index=df[col]).loc[rmat.index] rmat = rmat.apply(sorted, 1, result_type="expand") p = rmat.apply(qStuart, 1) df = pd.DataFrame( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def data_gen(n_ops=100): """Yield data, while optionally burning compute cycles. Parameters n_ops : int, default=100 Number of operations to run between yielding...
while True: X = np.random.uniform(size=(64, 64)) yield dict(X=costly_function(X, n_ops), y=np.random.randint(10, size=(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 mp_calc_stats(motifs, fg_fa, bg_fa, bg_name=None): """Parallel calculation of motif statistics."""
try: stats = calc_stats(motifs, fg_fa, bg_fa, ncpus=1) except Exception as e: raise sys.stderr.write("ERROR: {}\n".format(str(e))) stats = {} if not bg_name: bg_name = "default" return bg_name, stats
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _run_tool(job_name, t, fastafile, params): """Parallel motif prediction."""
try: result = t.run(fastafile, params, mytmpdir()) except Exception as e: result = ([], "", "{} failed to run: {}".format(job_name, e)) return job_name, result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def predict_motifs(infile, bgfile, outfile, params=None, stats_fg=None, stats_bg=None): """ Predict motifs, input is a FASTA-file"""
# Parse parameters required_params = ["tools", "available_tools", "analysis", "genome", "use_strand", "max_time"] if params is None: params = parse_denovo_params() else: for p in required_params: if p not in params: params = ...
<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_motifs(self, args): """Add motifs to the result object."""
self.lock.acquire() # Callback function for motif programs if args is None or len(args) != 2 or len(args[1]) != 3: try: job = args[0] logger.warn("job %s failed", job) self.finished.append(job) except Exception: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_for_stats(self): """Make sure all jobs are finished."""
logging.debug("waiting for statistics to finish") for job in self.stat_jobs: job.get() sleep(2)
<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_stats(self, args): """Callback to add motif statistics."""
bg_name, stats = args logger.debug("Stats: %s %s", bg_name, stats) for motif_id in stats.keys(): if motif_id not in self.stats: self.stats[motif_id] = {} self.stats[motif_id][bg_name] = stats[motif_id]
<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_denovo_input_narrowpeak(inputfile, params, outdir): """Prepare a narrowPeak file for de novo motif prediction. All regions to same size; split in tes...
bedfile = os.path.join(outdir, "input.from.narrowpeak.bed") p = re.compile(r'^(#|track|browser)') width = int(params["width"]) logger.info("preparing input (narrowPeak to BED, width %s)", width) warn_no_summit = True with open(bedfile, "w") as f_out: with open(inputfile) as f_in: ...
<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_denovo_input_bed(inputfile, params, outdir): """Prepare a BED file for de novo motif prediction. All regions to same size; split in test and validati...
logger.info("preparing input (BED)") # Create BED file with regions of equal size width = int(params["width"]) bedfile = os.path.join(outdir, "input.bed") write_equalwidth_bedfile(inputfile, width, bedfile) abs_max = int(params["abs_max"]) fraction = float(params["fraction"]) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_background(bg_type, fafile, outfile, genome="hg18", width=200, nr_times=10, custom_background=None): """Create background of a specific type. Paramete...
width = int(width) config = MotifConfig() fg = Fasta(fafile) if bg_type in ["genomic", "gc"]: if not genome: logger.error("Need a genome to create background") sys.exit(1) if bg_type == "random": f = MarkovFasta(fg, k=1, n=nr_times * len(fg)) lo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_backgrounds(outdir, background=None, genome="hg38", width=200, custom_background=None): """Create different backgrounds for motif prediction and valid...
if background is None: background = ["random"] nr_sequences = {} # Create background for motif prediction if "gc" in background: pred_bg = "gc" else: pred_bg = background[0] create_background( pred_bg, os.path.join(outdi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter_significant_motifs(fname, result, bg, metrics=None): """Filter significant motifs based on several statistics. Parameters fname : str Filename of outp...
sig_motifs = [] with open(fname, "w") as f: for motif in result.motifs: stats = result.stats.get( "%s_%s" % (motif.id, motif.to_consensus()), {}).get(bg, {} ) if _is_significant(stats, metrics): f.write("%s\n" % motif.to_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 best_motif_in_cluster(single_pwm, clus_pwm, clusters, fg_fa, background, stats=None, metrics=("roc_auc", "recall_at_fdr")): """Return the best motif per clus...
# combine original and clustered motifs motifs = read_motifs(single_pwm) + read_motifs(clus_pwm) motifs = dict([(str(m), m) for m in motifs]) # get the statistics for those motifs that were not yet checked clustered_motifs = [] for clus,singles in clusters: for motif in set([clus] + si...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rename_motifs(motifs, stats=None): """Rename motifs to GimmeMotifs_1..GimmeMotifs_N. If stats object is passed, stats will be copied."""
final_motifs = [] for i, motif in enumerate(motifs): old = str(motif) motif.id = "GimmeMotifs_{}".format(i + 1) final_motifs.append(motif) if stats: stats[str(motif)] = stats[old].copy() if stats: return final_motifs, stats else: return f...
<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_db(cls, dbname): """Register method to keep list of dbs."""
def decorator(subclass): """Register as decorator function.""" cls._dbs[dbname] = subclass subclass.name = dbname return subclass return decorator