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 as_ihex(self, number_of_data_bytes=32, address_length_bits=32): """Format the binary file as Intel HEX records and return them as a string. `number_of_data_b...
def i32hex(address, extended_linear_address, data_address): if address > 0xffffffff: raise Error( 'cannot address more than 4 GB in I32HEX files (32 ' 'bits addresses)') address_upper_16_bits = (address >> 16) address...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_ti_txt(self): """Format the binary file as a TI-TXT file and return it as a string. @0100 21 46 01 36 01 21 47 01 36 00 7E FE 09 D2 19 01 21 46 01 7E 17 C...
lines = [] for segment in self._segments: lines.append('@{:04X}'.format(segment.address)) for _, data in segment.chunks(TI_TXT_BYTES_PER_LINE): lines.append(' '.join('{:02X}'.format(byte) for byte in data)) lines.append('q') return '\n'.join(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_binary(self, minimum_address=None, maximum_address=None, padding=None): """Return a byte string of all data within given address range. `minimum_address` ...
if len(self._segments) == 0: return b'' if minimum_address is None: current_maximum_address = self.minimum_address else: current_maximum_address = minimum_address if maximum_address is None: maximum_address = self.maximum_address ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_array(self, minimum_address=None, padding=None, separator=', '): """Format the binary file as a string values separated by given separator `separator`. Th...
binary_data = self.as_binary(minimum_address, padding=padding) words = [] for offset in range(0, len(binary_data), self.word_size_bytes): word = 0 for byte in binary_data[offset:offset + self.word_size_bytes]: word ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_hexdump(self): """Format the binary file as a hexdump and return it as a string. 00000130 3f 01 56 70 2b 5e 71 2b 72 2b 73 21 46 01 34 21 |?.Vp+^q+r+s!F.4...
# Empty file? if len(self) == 0: return '\n' non_dot_characters = set(string.printable) non_dot_characters -= set(string.whitespace) non_dot_characters |= set(' ') def align16(address): return address - (address % 16) def padding(lengt...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fill(self, value=b'\xff'): """Fill all empty space between segments with given value `value`. """
previous_segment_maximum_address = None fill_segments = [] for address, data in self._segments: maximum_address = address + len(data) if previous_segment_maximum_address is not None: fill_size = address - previous_segment_maximum_address ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exclude(self, minimum_address, maximum_address): """Exclude given range and keep the rest. `minimum_address` is the first word address to exclude (including)...
if maximum_address < minimum_address: raise Error('bad address range') minimum_address *= self.word_size_bytes maximum_address *= self.word_size_bytes self._segments.remove(minimum_address, maximum_address)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def crop(self, minimum_address, maximum_address): """Keep given range and discard the rest. `minimum_address` is the first word address to keep (including). `max...
minimum_address *= self.word_size_bytes maximum_address *= self.word_size_bytes maximum_address_address = self._segments.maximum_address self._segments.remove(0, minimum_address) self._segments.remove(maximum_address, maximum_address_address)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def info(self): """Return a string of human readable information about the binary file. .. code-block:: python Data ranges: 0x00000100 - 0x00000140 (64 bytes) ""...
info = '' if self._header is not None: if self._header_encoding is None: header = '' for b in bytearray(self.header): if chr(b) in string.printable: header += chr(b) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _precompute(self, tree): """ Collect metric info in a single preorder traversal. """
d = {} for n in tree.preorder_internal_node_iter(): d[n] = namedtuple('NodeDist', ['dist_from_root', 'edges_from_root']) if n.parent_node: d[n].dist_from_root = d[n.parent_node].dist_from_root + n.edge_length d[n].edges_from_root = d[n.parent_node...
<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_vectors(self, tree, precomputed_info): """ Populate the vectors m and M. """
little_m = [] big_m = [] leaf_nodes = sorted(tree.leaf_nodes(), key=lambda x: x.taxon.label) # inner nodes, sorted order for leaf_a, leaf_b in combinations(leaf_nodes, 2): mrca = tree.mrca(taxa=[leaf_a.taxon, leaf_b.taxon]) little_m.append(precomputed_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 remove_empty(rec): """ Deletes sequences that were marked for deletion by convert_to_IUPAC """
for header, sequence in rec.mapping.items(): if all(char == 'X' for char in sequence): rec.headers.remove(header) rec.sequences.remove(sequence) rec.update() return rec
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transliterate(text): """ Utility to properly transliterate text. """
text = unidecode(six.text_type(text)) text = text.replace('@', 'a') 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 slugify(mapping, bind, values): """ Transform all values into URL-capable slugs. """
for value in values: if isinstance(value, six.string_types): value = transliterate(value) value = normality.slugify(value) yield value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def latinize(mapping, bind, values): """ Transliterate a given string into the latin alphabet. """
for v in values: if isinstance(v, six.string_types): v = transliterate(v) 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 join(mapping, bind, values): """ Merge all the strings. Put space between them. """
return [' '.join([six.text_type(v) for v in values if v 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 hash(mapping, bind, values): """ Generate a sha1 for each of the given values. """
for v in values: if v is None: continue if not isinstance(v, six.string_types): v = six.text_type(v) yield sha1(v.encode('utf-8')).hexdigest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean(mapping, bind, values): """ Perform several types of string cleaning for titles etc.. """
categories = {'C': ' '} for value in values: if isinstance(value, six.string_types): value = normality.normalize(value, lowercase=False, collapse=True, decompose=False, replace_categories=categories) yie...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isconnected(mask): """ Checks that all nodes are reachable from the first node - i.e. that the graph is fully connected. """
nodes_to_check = list((np.where(mask[0, :])[0])[1:]) seen = [True] + [False] * (len(mask) - 1) while nodes_to_check and not all(seen): node = nodes_to_check.pop() reachable = np.where(mask[node, :])[0] for i in reachable: if not seen[i]: nodes_to_check.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 normalise_rows(matrix): """ Scales all rows to length 1. Fails when row is 0-length, so it leaves these unchanged """
lengths = np.apply_along_axis(np.linalg.norm, 1, matrix) if not (lengths > 0).all(): # raise ValueError('Cannot normalise 0 length vector to length 1') # print(matrix) lengths[lengths == 0] = 1 return matrix / lengths[:, np.newaxis]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kdists(matrix, k=7, ix=None): """ Returns the k-th nearest distances, row-wise, as a column vector """
ix = ix or kindex(matrix, k) return matrix[ix][np.newaxis].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 kindex(matrix, k): """ Returns indices to select the kth nearest neighbour"""
ix = (np.arange(len(matrix)), matrix.argsort(axis=0)[k]) return ix
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kmask(matrix, k=7, dists=None, logic='or'): """ Creates a boolean mask to include points within k nearest neighbours, and exclude the rest. Logic can be OR o...
dists = (kdists(matrix, k=k) if dists is None else dists) mask = (matrix <= dists) if logic == 'or' or logic == '|': return mask | mask.T elif logic == 'and' or logic == '&': return mask & mask.T return mask
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kscale(matrix, k=7, dists=None): """ Returns the local scale based on the k-th nearest neighbour """
dists = (kdists(matrix, k=k) if dists is None else dists) scale = dists.dot(dists.T) return 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 shift_and_scale(matrix, shift, scale): """ Shift and scale matrix so its minimum value is placed at `shift` and its maximum value is scaled to `scale` """
zeroed = matrix - matrix.min() scaled = (scale - shift) * (zeroed / zeroed.max()) return scaled + shift
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def coords_by_dimension(self, dimensions=3): """ Returns fitted coordinates in specified number of dimensions, and the amount of variance explained) """
coords_matrix = self.vecs[:, :dimensions] varexp = self.cve[dimensions - 1] return coords_matrix, varexp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_value(mapping, bind, data): """ Given a mapping and JSON schema spec, extract a value from ``data`` and apply certain transformations to normalize th...
columns = mapping.get('columns', [mapping.get('column')]) values = [data.get(c) for c in columns] for transform in mapping.get('transforms', []): # any added transforms must also be added to the schema. values = list(TRANSFORMS[transform](mapping, bind, values)) format_str = mapping.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 convert_value(bind, value): """ Type casting. """
type_name = get_type(bind) try: return typecast.cast(type_name, value) except typecast.ConverterError: return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def peaks(x, y, lookahead=20, delta=0.00003): """ A wrapper around peakdetect to pack the return values in a nicer format """
_max, _min = peakdetect(y, x, lookahead, delta) x_peaks = [p[0] for p in _max] y_peaks = [p[1] for p in _max] x_valleys = [p[0] for p in _min] y_valleys = [p[1] for p in _min] _peaks = [x_peaks, y_peaks] _valleys = [x_valleys, y_valleys] return {"peaks": _peaks, "valleys": _valleys...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _restricted_growth_notation(l): """ The clustering returned by the hcluster module gives group membership without regard for numerical order This function pr...
list_length = len(l) d = defaultdict(list) for (i, element) in enumerate(l): d[element].append(i) l2 = [None] * list_length for (name, index_list) in enumerate(sorted(d.values(), key=min)): for index in index_list: l2[index] = 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_membership(self): """ Alternative representation of group membership - creates a list with one tuple per group; each tuple contains the indices of its me...
result = defaultdict(list) for (position, value) in enumerate(self.partition_vector): result[value].append(position) return sorted([tuple(x) for x in result.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 extend_peaks(self, prop_thresh=50): """Each peak in the peaks of the object is checked for its presence in other octaves. If it does not exist, it is created...
# octave propagation of the reference peaks temp_peaks = [i + 1200 for i in self.peaks["peaks"][0]] temp_peaks.extend([i - 1200 for i in self.peaks["peaks"][0]]) extended_peaks = [] extended_peaks.extend(self.peaks["peaks"][0]) for i in temp_peaks: # if a pe...
<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(self, intervals=None, new_fig=True): """This function plots histogram together with its smoothed version and peak information if provided. Just intonati...
import pylab as p if new_fig: p.figure() #step 1: plot histogram p.plot(self.x, self.y, ls='-', c='b', lw='1.5') #step 2: plot peaks first_peak = None last_peak = None if self.peaks: first_peak = min(self.peaks["peaks"][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 threadpool_map(task, args, message, concurrency, batchsize=1, nargs=None): """ Helper to map a function over a range of inputs, using a threadpool, with a pr...
import concurrent.futures njobs = get_njobs(nargs, args) show_progress = bool(message) batches = grouper(batchsize, tupleise(args)) batched_task = lambda batch: [task(*job) for job in batch] if show_progress: message += ' (TP:{}w:{}b)'.format(concurrency, batchsize) pbar = 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 insort_no_dup(lst, item): """ If item is not in lst, add item to list at its sorted position """
import bisect ix = bisect.bisect_left(lst, item) if lst[ix] != item: lst[ix:ix] = [item]
<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_gamma_model(alignment, missing_data=None, ncat=4): """ Create a phylo_utils.likelihood.GammaMixture for calculating likelihood on a tree, from a treeC...
model = alignment.parameters.partitions.model freqs = alignment.parameters.partitions.frequencies alpha = alignment.parameters.partitions.alpha if model == 'LG': subs_model = LG(freqs) elif model == 'WAG': subs_model = WAG(freqs) elif model == 'GTR': rates = alignment.pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sample_wr(lst): """ Sample from lst, with replacement """
arr = np.array(lst) indices = np.random.randint(len(lst), size=len(lst)) sample = np.empty(arr.shape, dtype=arr.dtype) for i, ix in enumerate(indices): sample[i] = arr[ix] return list(sample)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _preprocess_inputs(x, weights): """ Coerce inputs into compatible format """
if weights is None: w_arr = np.ones(len(x)) else: w_arr = np.array(weights) x_arr = np.array(x) if x_arr.ndim == 2: if w_arr.ndim == 1: w_arr = w_arr[:, np.newaxis] return x_arr, w_arr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def amean(x, weights=None): """ Return the weighted arithmetic mean of x """
w_arr, x_arr = _preprocess_inputs(x, weights) return (w_arr*x_arr).sum(axis=0) / w_arr.sum(axis=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 gmean(x, weights=None): """ Return the weighted geometric mean of x """
w_arr, x_arr = _preprocess_inputs(x, weights) return np.exp((w_arr*np.log(x_arr)).sum(axis=0) / w_arr.sum(axis=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 hmean(x, weights=None): """ Return the weighted harmonic mean of x """
w_arr, x_arr = _preprocess_inputs(x, weights) return w_arr.sum(axis=0) / (w_arr/x_arr).sum(axis=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 records(self): """ Returns a list of records in SORT_KEY order """
return [self._records[i] for i in range(len(self._records))]
<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_trees(self, input_dir): """ Read a directory full of tree files, matching them up to the already loaded alignments """
if self.show_progress: pbar = setup_progressbar("Loading trees", len(self.records)) pbar.start() for i, rec in enumerate(self.records): hook = os.path.join(input_dir, '{}.nwk*'.format(rec.name)) filename = glob.glob(hook) 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 read_parameters(self, input_dir): """ Read a directory full of json parameter files, matching them up to the already loaded alignments """
if self.show_progress: pbar = setup_progressbar("Loading parameters", len(self.records)) pbar.start() for i, rec in enumerate(self.records): hook = os.path.join(input_dir, '{}.json*'.format(rec.name)) filename = glob.glob(hook) 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 calc_trees(self, indices=None, task_interface=None, jobhandler=default_jobhandler, batchsize=1, show_progress=True, **kwargs): """ Infer phylogenetic trees f...
if indices is None: indices = list(range(len(self))) if task_interface is None: task_interface = tasks.RaxmlTaskInterface() records = [self[i] for i in indices] # Scrape args from records args, to_delete = task_interface.scrape_args(records, **kwargs) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def num_species(self): """ Returns the number of species found over all records """
all_headers = reduce(lambda x, y: set(x) | set(y), (rec.get_names() for rec in self.records)) return len(all_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 permuted_copy(self, partition=None): """ Return a copy of the collection with all alignment columns permuted """
def take(n, iterable): return [next(iterable) for _ in range(n)] if partition is None: partition = Partition([1] * len(self)) index_tuples = partition.get_membership() alignments = [] for ix in index_tuples: concat = Concatenation(self, ix)...
<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_id(self, grp): """ Return a hash of the tuple of indices that specify the group """
thehash = hex(hash(grp)) if ISPY3: # use default encoding to get bytes thehash = thehash.encode() return self.cache.get(grp, hashlib.sha1(thehash).hexdigest())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_work_done(self, grp): """ Check for the existence of alignment and result files. """
id_ = self.get_id(grp) concat_file = os.path.join(self.cache_dir, '{}.phy'.format(id_)) result_file = os.path.join(self.cache_dir, '{}.{}.json'.format(id_, self.task_interface.name)) return os.path.exists(concat_file), os.path.exists(result_file)
<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_group(self, grp, overwrite=False, **kwargs): """ Write the concatenated alignment to disk in the location specified by self.cache_dir """
id_ = self.get_id(grp) alignment_done, result_done = self.check_work_done(grp) self.cache[grp] = id_ al_filename = os.path.join(self.cache_dir, '{}.phy'.format(id_)) qfile_filename = os.path.join(self.cache_dir, '{}.partitions.txt'.format(id_)) if overwrite or not (align...
<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_group_result(self, grp, **kwargs): """ Retrieve the results for a group. Needs this to already be calculated - errors out if result not available. """
id_ = self.get_id(grp) self.cache[grp] = id_ # Check if this file is already processed alignment_written, results_written = self.check_work_done(grp) if not results_written: if not alignment_written: self.write_group(grp, **kwargs) logge...
<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_partition_score(self, p): """ Assumes analysis is done and written to id.json! """
scores = [] for grp in p.get_membership(): try: result = self.get_group_result(grp) scores.append(result['likelihood']) except ValueError: scores.append(None) return sum(scores)
<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_partition_trees(self, p): """ Return the trees associated with a partition, p """
trees = [] for grp in p.get_membership(): try: result = self.get_group_result(grp) trees.append(result['ml_tree']) except ValueError: trees.append(None) logger.error('No tree found for group {}'.format(grp)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expect(self, use_proportions=True): """ The Expectation step of the CEM algorithm """
changed = self.get_changed(self.partition, self.prev_partition) lk_table = self.generate_lktable(self.partition, changed, use_proportions) self.table = self.likelihood_table_to_probs(lk_table)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def classify(self, table, weighted_choice=False, transform=None): """ The Classification step of the CEM algorithm """
assert table.shape[1] == self.numgrp if weighted_choice: if transform is not None: probs = transform_fn(table.copy(), transform) # else: probs = table.copy() cmprobs = probs.cumsum(1) logger.info('Probabilities\n{}'.format...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def maximise(self, **kwargs): """ The Maximisation step of the CEM algorithm """
self.scorer.write_partition(self.partition) self.scorer.analyse_cache_dir(**kwargs) self.likelihood = self.scorer.get_partition_score(self.partition) self.scorer.clean_cache() changed = self.get_changed(self.partition, self.prev_partition) self.update_perlocus_likelihood...
<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_partition(self, partition): """ Store the partition in self.partition, and move the old self.partition into self.prev_partition """
assert len(partition) == self.numgrp self.partition, self.prev_partition = partition, self.partition
<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_changed(self, p1, p2): """ Return the loci that are in clusters that have changed between partitions p1 and p2 """
if p1 is None or p2 is None: return list(range(len(self.insts))) return set(flatten_list(set(p1) - set(p2)))
<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_likelihood_model(self, inst, partition_parameters, tree): """ Set parameters of likelihood model - inst - using values in dictionary - partition_para...
# Build transition matrix from dict model = partition_parameters['model'] freqs = partition_parameters.get('frequencies') if model == 'LG': subs_model = phylo_utils.models.LG(freqs) elif model == 'WAG': subs_model = phylo_utils.models.WAG(freqs) e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fill_empty_groups_old(self, probs, assignment): """ Does the simple thing - if any group is empty, but needs to have at least one member, assign the data po...
new_assignment = np.array(assignment.tolist()) for k in range(self.numgrp): if np.count_nonzero(assignment==k) == 0: logger.info('Group {} became empty'.format(k)) best = np.where(probs[:,k]==probs[:,k].max())[0][0] new_assignment[best] = 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 jac(x,a): """ Jacobian matrix given Christophe's suggestion of f """
return (x-a) / np.sqrt(((x-a)**2).sum(1))[:,np.newaxis]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gradient(x, a, c): """ J'.G """
return jac(x, a).T.dot(g(x, a, 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 hessian(x, a): """ J'.J """
j = jac(x, a) return j.T.dot(j)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def grad_desc_update(x, a, c, step=0.01): """ Given a value of x, return a better x using gradient descent """
return x - step * gradient(x,a,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 optimise_levenberg_marquardt(x, a, c, damping=0.001, tolerance=0.001): """ Optimise value of x using levenberg-marquardt """
x_new = x x_old = x-1 # dummy value f_old = f(x_new, a, c) while np.abs(x_new - x_old).sum() > tolerance: x_old = x_new x_tmp = levenberg_marquardt_update(x_old, a, c, damping) f_new = f(x_tmp, a, c) if f_new < f_old: damping = np.max(damping/10., 1e-20) ...
<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_out_of_sample_mds(boot_collection, ref_collection, ref_distance_matrix, index, dimensions, task=_fast_geo, rooted=False, **kwargs): """ index = index of ...
fit = np.empty((len(boot_collection), dimensions)) if ISPY3: query_trees = [PhyloTree(tree.encode(), rooted) for tree in boot_collection.trees] ref_trees = [PhyloTree(tree.encode(), rooted) for tree in ref_collection.trees] else: query_trees = [PhyloTree(tree, rooted) for tree in bo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stress(ref_cds, est_cds): """ Kruskal's stress """
ref_dists = pdist(ref_cds) est_dists = pdist(est_cds) return np.sqrt(((ref_dists - est_dists)**2).sum() / (ref_dists**2).sum())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rmsd(ref_cds, est_cds): """ Root-mean-squared-difference """
ref_dists = pdist(ref_cds) est_dists = pdist(est_cds) return np.sqrt(((ref_dists - est_dists)**2).mean())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def levenberg_marquardt(self, start_x=None, damping=1.0e-3, tolerance=1.0e-6): """ Optimise value of x using levenberg marquardt """
if start_x is None: start_x = self._analytical_fitter.fit(self._c) return optimise_levenberg_marquardt(start_x, self._a, self._c, tolerance)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _make_A_and_part_of_b_adjacent(self, ref_crds): """ Make A and part of b. See docstring of this class for answer to "What are A and b?" """
rot = self._rotate_rows(ref_crds) A = 2*(rot - ref_crds) partial_b = (rot**2 - ref_crds**2).sum(1) return A, partial_b
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_schema_mapping(resolver, schema_uri, depth=1): """ Try and recursively iterate a JSON schema and to generate an ES mapping that encasulates it. """
visitor = SchemaVisitor({'$ref': schema_uri}, resolver) return _generate_schema_mapping(visitor, set(), depth)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def phyml_task(alignment_file, model, **kwargs): """ Kwargs are passed to the Phyml process command line """
import re fl = os.path.abspath(alignment_file) ph = Phyml(verbose=False) if model in ['JC69', 'K80', 'F81', 'F84', 'HKY85', 'TN93', 'GTR']: datatype = 'nt' elif re.search('[01]{6}', model) is not None: datatype = 'nt' else: datatype = 'aa' cmd = '-i {} -m {} -d {} -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 validate_mapping(mapping): """ Validate a mapping configuration file against the relevant schema. """
file_path = os.path.join(os.path.dirname(__file__), 'schemas', 'mapping.json') with open(file_path, 'r') as fh: validator = Draft4Validator(json.load(fh)) validator.validate(mapping) return mapping
<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(self, partition=None, cmap=CM.Blues): """ Plots a visual representation of a distance matrix """
if isinstance(self.dm, DistanceMatrix): length = self.dm.values.shape[0] else: length = self.dm.shape[0] datamax = float(np.abs(self.dm).max()) fig = plt.figure() ax = fig.add_subplot(111) ticks_at = [0, 0.5 * datamax, datamax] if partiti...
<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_tree_collection_strings(self, scale=1, guide_tree=None): """ Function to get input strings for tree_collection tree_collection needs distvar, genome_map ...
records = [self.collection[i] for i in self.indices] return TreeCollectionTaskInterface().scrape_args(records)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_json(buffer, auto_flatten=True, raise_for_index=True): """Parses a JSON string into either a view or an index. If auto flatten is enabled a sourcemap in...
buffer = to_bytes(buffer) view_out = _ffi.new('lsm_view_t **') index_out = _ffi.new('lsm_index_t **') buffer = to_bytes(buffer) rv = rustcall( _lib.lsm_view_or_index_from_json, buffer, len(buffer), view_out, index_out) if rv == 1: return View._from_ptr(view_out[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 from_memdb(buffer): """Creates a sourcemap view from MemDB bytes."""
buffer = to_bytes(buffer) return View._from_ptr(rustcall( _lib.lsm_view_from_memdb, buffer, len(buffer)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_memdb_file(path): """Creates a sourcemap view from MemDB at a given file."""
path = to_bytes(path) return View._from_ptr(rustcall(_lib.lsm_view_from_memdb_file, path))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump_memdb(self, with_source_contents=True, with_names=True): """Dumps a sourcemap in MemDB format into bytes."""
len_out = _ffi.new('unsigned int *') buf = rustcall( _lib.lsm_view_dump_memdb, self._get_ptr(), len_out, with_source_contents, with_names) try: rv = _ffi.unpack(buf, len_out[0]) finally: _lib.lsm_buffer_free(buf) 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 lookup_token(self, line, col): """Given a minified location, this tries to locate the closest token that is a match. Returns `None` if no match can be found....
# Silently ignore underflows if line < 0 or col < 0: return None tok_out = _ffi.new('lsm_token_t *') if rustcall(_lib.lsm_view_lookup_token, self._get_ptr(), line, col, tok_out): return convert_token(tok_out[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_original_function_name(self, line, col, minified_name, minified_source): """Given a token location and a minified function name and the minified source f...
# Silently ignore underflows if line < 0 or col < 0: return None minified_name = minified_name.encode('utf-8') sout = _ffi.new('const char **') try: slen = rustcall(_lib.lsm_view_get_original_function_name, self._get_ptr(), lin...
<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_source_contents(self, src_id): """Given a source ID this returns the embedded sourcecode if there is. The sourcecode is returned as UTF-8 bytes for more ...
len_out = _ffi.new('unsigned int *') must_free = _ffi.new('int *') rv = rustcall(_lib.lsm_view_get_source_contents, self._get_ptr(), src_id, len_out, must_free) if rv: try: return _ffi.unpack(rv, len_out[0]) finally: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_source_contents(self, src_id): """Checks if some sources exist."""
return bool(rustcall(_lib.lsm_view_has_source_contents, self._get_ptr(), src_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_source_name(self, src_id): """Returns the name of the given source."""
len_out = _ffi.new('unsigned int *') rv = rustcall(_lib.lsm_view_get_source_name, self._get_ptr(), src_id, len_out) if rv: return decode_rust_str(rv, len_out[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 iter_sources(self): """Iterates over all source names and IDs."""
for src_id in xrange(self.get_source_count()): yield src_id, self.get_source_name(src_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 from_json(buffer): """Creates an index from a JSON string."""
buffer = to_bytes(buffer) return Index._from_ptr(rustcall( _lib.lsm_index_from_json, buffer, len(buffer)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def into_view(self): """Converts the index into a view"""
try: return View._from_ptr(rustcall( _lib.lsm_index_into_view, self._get_ptr())) finally: self._ptr = 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 from_path(filename): """Creates a sourcemap view from a file path."""
filename = to_bytes(filename) if NULL_BYTE in filename: raise ValueError('null byte in path') return ProguardView._from_ptr(rustcall( _lib.lsm_proguard_mapping_from_path, filename + b'\x00'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply(self, data): """ Apply the given mapping to ``data``, recursively. The return type is a tuple of a boolean and the resulting data element. The boolean ...
if self.visitor.is_object: obj = {} if self.visitor.parent is None: obj['$schema'] = self.visitor.path obj_empty = True for child in self.children: empty, value = child.apply(data) if empty and child.optional: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def translate(self, text): """ Translate text, returns the modified text. """
# Reset substitution counter self.count = 0 # Process text return self._make_regex().sub(self, 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 cluster(self, n, embed_dim=None, algo=spectral.SPECTRAL, method=methods.KMEANS): """ Cluster the embedded coordinates using spectral clustering Parameters n:...
if n == 1: return Partition([1] * len(self.get_dm(False))) if embed_dim is None: embed_dim = n if algo == spectral.SPECTRAL: self._coords = self.spectral_embedding(embed_dim) elif algo == spectral.KPCA: self._coords = self.kpca_embedding...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spectral_embedding(self, n): """ Embed the points using spectral decomposition of the laplacian of the affinity matrix Parameters n: int The number of dimens...
coords = spectral_embedding(self._affinity, n) return CoordinateMatrix(normalise_rows(coords))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kpca_embedding(self, n): """ Embed the points using kernel PCA of the affinity matrix Parameters n: int The number of dimensions """
return self.dm.embedding(n, 'kpca', affinity_matrix=self._affinity)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cluster(self, n, embed_dim=None, algo=mds.CLASSICAL, method=methods.KMEANS): """ Cluster the embedded coordinates using multidimensional scaling Parameters n...
if n == 1: return Partition([1] * len(self.get_dm(False))) if embed_dim is None: embed_dim = n if algo == mds.CLASSICAL: self._coords = self.dm.embedding(embed_dim, 'cmds') elif algo == mds.METRIC: self._coords = self.dm.embedding(embed_...
<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_thread(self, pipe, queue): """ Start a thread logging output from pipe """
# thread function to log subprocess output (LOG is a queue) def enqueue_output(out, q): for line in iter(out.readline, b''): q.put(line.rstrip()) out.close() # start thread t = threading.Thread(target=enqueue_output, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _search_for_executable(self, executable): """ Search for file give in "executable". If it is not found, we try the environment PATH. Returns either the absol...
if os.path.isfile(executable): return os.path.abspath(executable) else: envpath = os.getenv('PATH') if envpath is None: return for path in envpath.split(os.pathsep): exe = os.path.join(path, executable) if o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _command_template(self, switches, objectInput=None): """Template for Tika app commands Args: switches (list): list of switches to Tika app Jar objectInput (...
command = ["java", "-jar", self.file_jar, "-eUTF-8"] if self.memory_allocation: command.append("-Xmx{}".format(self.memory_allocation)) command.extend(switches) if not objectInput: objectInput = subprocess.PIPE log.debug("Subprocess command: {}".format(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def detect_content_type(self, path=None, payload=None, objectInput=None): """ Return the content type of passed file or payload. Args: path (string): Path of fi...
# From Python detection content type from stdin doesn't work TO FIX if objectInput: message = "Detection content type with file object is not stable." log.exception(message) raise TikaAppError(message) f = file_path(path, payload, objectInput) switch...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_only_content(self, path=None, payload=None, objectInput=None): """ Return only the text content of passed file. These parameters are in OR. Only one ...
if objectInput: switches = ["-t"] result = self._command_template(switches, objectInput) return result, True, None else: f = file_path(path, payload) switches = ["-t", f] result = self._command_template(switches) 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 extract_all_content( self, path=None, payload=None, objectInput=None, pretty_print=False, convert_to_obj=False, ): """ This function returns a JSON of all co...
f = file_path(path, payload, objectInput) switches = ["-J", "-t", "-r", f] if not pretty_print: switches.remove("-r") result = self._command_template(switches) if result and convert_to_obj: result = json.loads(result, encoding="utf-8") return re...