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 loadDHCPOptions(self, address_family, options): """ Create a high level DHCPOptions object :param str address_family: Address family of the options. Can be e...
import ns1.ipam return ns1.ipam.DHCPOptions(address_family, options)
<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_tree(comments): """ Insert extra comments in the comments list, so that the root path of the first comment is always visible. Use this in comments' pagi...
if not comments: return it = iter(comments) first = next(it) extra_path_items = imap(_mark_as_root_path, first.root_path) return chain(extra_path_items, [first], it)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def annotate_tree_properties(comments): """ iterate through nodes and adds some magic properties to each of them representing opening list of children and closin...
if not comments: return it = iter(comments) # get the first item, this will fail if no items ! old = next(it) # first item starts a new thread old.open = True last = set() for c in it: # if this comment has a parent, store its last child for future reference 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 run_spades(self, stop_at_first_success=False): '''Runs spades on all kmers. Each a separate run because SPAdes dies if any kmer does not work. Chooses the 'best' assembly to be the one with the biggest N50''' n50 = {} kmer_to_dir = {} for k in self.spades_kmers: ...
<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_canu(self): '''Runs canu instead of spades''' cmd = self._make_canu_command(self.outdir,'canu') ok, errs = common.syscall(cmd, verbose=self.verbose, allow_fail=False) if not ok: raise Error('Error running Canu.') original_contigs = os.path.join(self.outdir, '...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def aligned_read_to_read(read, revcomp=True, qual=None, ignore_quality=False): '''Returns Fasta or Fastq sequence from pysam aligned read''' if read.qual is None or ignore_quality: if qual is None or ignore_quality: seq = pyfastaq.sequences.Fasta(read.qname, common.decode(read.seq)) ...
<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_ref_lengths(self): '''Gets the length of each reference sequence from the header of the bam. Returns dict name => length''' sam_reader = pysam.Samfile(self.bam, "rb") return dict(zip(sam_reader.references, sam_reader.lengths))
<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_contigs_to_use(self, contigs_to_use): '''If contigs_to_use is a set, returns that set. If it's None, returns an empty set. Otherwise, assumes it's a file name, and gets names from the file''' if type(contigs_to_use) == set: return contigs_to_use elif contigs_to_use 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 _all_reads_from_contig(self, contig, fout): '''Gets all reads from contig called "contig" and writes to fout''' sam_reader = pysam.Samfile(self.bam, "rb") for read in sam_reader.fetch(contig): print(mapping.aligned_read_to_read(read, ignore_quality=not self.fastq_out), file=fout)
<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_unmapped_reads(self, fout): '''Writes all unmapped reads to fout''' sam_reader = pysam.Samfile(self.bam, "rb") for read in sam_reader.fetch(until_eof=True): if read.is_unmapped: print(mapping.aligned_read_to_read(read, ignore_quality=not self.fastq_out), ...
<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_region(self, contig, start, end, fout): '''Writes reads not mapping to the given region of contig, start and end as per python convention''' sam_reader = pysam.Samfile(self.bam, "rb") exclude_interval = pyfastaq.intervals.Interval(start, end - 1) for read in sam_reader.fetch...
<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_region(self, contig, start, end, fout, min_length=250): '''Writes reads mapping to given region of contig, trimming part of read not in the region''' sam_reader = pysam.Samfile(self.bam, "rb") trimming_end = (start == 0) for read in sam_reader.fetch(contig, start, end): ...
<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_contigs_to_keep(self, filename): '''Returns a set of names from file called filename. If filename is None, returns an empty set''' if filename is None: return set() with open(filename) as f: return {line.rstrip() for line in 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 _remove_small_contigs(self, infile, outfile, keep=None): '''Writes a new file with small contigs removed. Returns lists of all names and names of removed contigs''' removed = set() all_names = set() if keep is None: keep = set() file_reader = pyfastaq....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _containing_contigs(self, hits): '''Given a list of hits, all with same query, returns a set of the contigs containing that query''' return {hit.ref_name for hit in hits if self._contains(hit)}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _expand_containing_using_transitivity(self, containing_contigs): '''This uses a contined in b, and b contained in c to force a contained in c. Just in case a contained in c wasn't already found by nucmer''' for name in containing_contigs: containing_contigs[name] = self._get_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 _collapse_list_of_sets(self, sets): '''Input is a list of sets. Merges any intersecting sets in the list''' found = True while found: found = False to_intersect = None for i in range(len(sets)): for j in range(len(sets)): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _longest_contig(self, contig_set, contig_lengths): '''Returns the name of the longest contig, from the set of names contig_set. contig_lengths is expected to be a dictionary of contig name => length.''' longest_name = None max_length = -1 for name in contig_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 check_files_exist(filenames): '''Dies if any files in the list of filenames does not exist''' files_not_found = [x for x in filenames if not os.path.exists(x)] if len(files_not_found): for filename in files_not_found: print('File not found: "', filename, '"', sep='', file=sys.stderr)...
<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_contigs(self): '''Returns a dictionary of contig_name -> pyfastaq.Sequences.Fasta object''' contigs = {} pyfastaq.tasks.file_to_dict(self.contigs_fasta, contigs) return contigs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def circular_contigs(self): '''Returns a set of the contig names that are circular''' if self.assembler == 'spades': if self.contigs_fastg is not None: return self._circular_contigs_from_spades_before_3_6_1(self.contigs_fastg) elif None not in [self.contigs_paths,...
<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_nucmer(self, ref, qry, outfile): '''Run nucmer of new assembly vs original assembly''' n = pymummer.nucmer.Runner( ref, qry, outfile, min_id=self.nucmer_min_id, min_length=self.nucmer_min_length, diagdiff=self.nucmer_diagdi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _load_nucmer_hits(self, infile): '''Returns dict ref name => list of nucmer hits from infile''' hits = {} file_reader = pymummer.coords_file.reader(infile) for al in file_reader: if al.ref_name not in hits: hits[al.ref_name] = [] hits[al.ref_na...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _is_at_ref_start(self, nucmer_hit): '''Returns True iff the hit is "close enough" to the start of the reference sequence''' hit_coords = nucmer_hit.ref_coords() return hit_coords.start < self.ref_end_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 _is_at_ref_end(self, nucmer_hit): '''Returns True iff the hit is "close enough" to the end of the reference sequence''' hit_coords = nucmer_hit.ref_coords() return hit_coords.end >= nucmer_hit.ref_length - self.ref_end_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 _is_at_qry_start(self, nucmer_hit): '''Returns True iff the hit is "close enough" to the start of the query sequence''' hit_coords = nucmer_hit.qry_coords() return hit_coords.start < self.qry_end_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 _is_at_qry_end(self, nucmer_hit): '''Returns True iff the hit is "close enough" to the end of the query sequence''' hit_coords = nucmer_hit.qry_coords() return hit_coords.end >= nucmer_hit.qry_length - self.qry_end_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 _get_hit_nearest_ref_start(self, hits): '''Returns the hit nearest to the start of the ref sequence from the input list of hits''' nearest_to_start = hits[0] for hit in hits[1:]: if hit.ref_coords().start < nearest_to_start.ref_coords().start: nearest_to_start = h...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _get_hit_nearest_ref_end(self, hits): '''Returns the hit nearest to the end of the ref sequence from the input list of hits''' nearest_to_end = hits[0] for hit in hits[1:]: if hit.ref_coords().end > nearest_to_end.ref_coords().end: nearest_to_end = hit ret...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _has_qry_hit_longer_than(self, nucmer_hits, min_length, hits_to_exclude=None): '''Returns True iff list of nucmer_hits has a hit longer than min_length, not counting the hits in hits_to_exclude''' if hits_to_exclude is None: to_exclude = set() else: to_exclude = hits_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _can_circularise(self, start_hit, end_hit): '''Returns true iff the two hits can be used to circularise the reference sequence of the hits''' if not(self._is_at_ref_start(start_hit) or self._is_at_ref_end(end_hit)): return False if self._is_at_qry_end(start_hit) \ and ...
<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_keys_from_dict_with_nonunique_values(self, d, log_fh=None, log_outprefix=None): '''Returns a new dictionary, with keys from input dict removed if their value was not unique''' value_counts = collections.Counter(d.values()) new_d = {} writing_log_file = None not in [log_fh, 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 _make_circularised_contig(self, ref_start_hit, ref_end_hit): '''Given a nucmer ref_start_hit and ref_end_hit, returns a new contig. Assumes that these hits can be used to circularise the reference contig of the hits using the query contig''' assert ref_start_hit.ref_name == ref_end_hit.ref_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 _orientation_ok_to_bridge_contigs(self, start_hit, end_hit): '''Returns True iff the orientation of the hits means that the query contig of both hits can bridge the reference contigs of the hits''' assert start_hit.qry_name == end_hit.qry_name if start_hit.ref_name == end_hit.ref_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 _merge_all_bridged_contigs(self, nucmer_hits, ref_contigs, qry_contigs, log_fh=None, log_outprefix=None): '''Input is dict of nucmer_hits. Makes any possible contig merges. Returns True iff any merges were made''' writing_log_file = None not in [log_fh, log_outprefix] if len(nucm...
<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_act_files(self, ref_fasta, qry_fasta, coords_file, outprefix): '''Writes crunch file and shell script to start up ACT, showing comparison of ref and qry''' if self.verbose: print('Making ACT files from', ref_fasta, qry_fasta, coords_file) ref_fasta = os.path.relpath(ref_fa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _contigs_dict_to_file(self, contigs, fname): '''Writes dictionary of contigs to file''' f = pyfastaq.utils.open_file_write(fname) for contig in sorted(contigs, key=lambda x:len(contigs[x]), reverse=True): print(contigs[contig], file=f) pyfastaq.utils.close(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 _get_spades_circular_nodes(self, fastg): '''Returns set of names of nodes in SPAdes fastg file that are circular. Names will match those in spades fasta file''' seq_reader = pyfastaq.sequences.file_reader(fastg) names = set([x.id.rstrip(';') for x in seq_reader if ':' in x.id]) found...
<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_new_contig_from_nucmer_and_spades(self, original_contig, hits, circular_spades, log_fh=None, log_outprefix=None): '''Tries to make new circularised contig from contig called original_contig. hits = list of nucmer hits, all with ref=original contg. circular_spades=set of query contig names that spades ...
<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_hunk(self, header, diff, encoding): """Parse hunk details."""
header_info = RE_HUNK_HEADER.match(header) hunk_info = header_info.groups() hunk = Hunk(*hunk_info) source_line_no = hunk.source_start target_line_no = hunk.target_start expected_source_end = source_line_no + hunk.source_length expected_target_end = target_line_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def path(self): """Return the file path abstracted from VCS."""
if (self.source_file.startswith('a/') and self.target_file.startswith('b/')): filepath = self.source_file[2:] elif (self.source_file.startswith('a/') and self.target_file == '/dev/null'): filepath = self.source_file[2:] elif (self.target_fil...
<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_tag_value(string, pre, post, tagtype=float, greedy=True): """ Extracts the value of a tag from a string. Parameters pre : str regular expression to match...
greedy = '?' if greedy else '' # For greedy search if isinstance(post, (list, tuple)): post = '(?=' + '|'.join(post) + ')' tag_list = re.findall(r'{pre}(.+{greedy}){post}'.format(pre=pre, post=post, greedy=greedy), string) if len(tag_list) > 1: raise ValueE...
<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_files(dirname=None, pattern='*.*', recursive=True): """ Get all file names within a given directory those names match a given pattern. Parameters dirname...
# get dirname from user if not given if dirname is None: from FlowCytometryTools.gui import dialogs dirname = dialogs.select_directory_dialog('Select a directory') # find all files in dirname that match pattern if recursive: # search subdirs matches = [] for root, dirn...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(path): """ Load pickled object from the specified file path. Parameters path : string File path Returns ------- unpickled : type of object stored in fil...
f = open(path, 'rb') try: return pickle.load(f) finally: f.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_iter(obj): """Convert an object to a list if it is not already an iterable. Nones are returned unaltered. This is an awful function that proliferates an e...
if isinstance(obj, type(None)): return None elif isinstance(obj, six.string_types): return [obj] else: # Nesting here since symmetry is broken in isinstance checks. # Strings are iterables in python 3, so the relative order of if statements is important. if isinstanc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_list(obj): """ Converts an object into a list if it not an iterable, forcing tuples into lists. Nones are returned unchanged. """
obj = to_iter(obj) if isinstance(obj, type(None)): return None else: return list(obj)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy(self, deep=True): """ Make a copy of this object Parameters deep : boolean, default True Make a deep copy, i.e. also copy data Returns ------- copy : ty...
from copy import copy, deepcopy if deep: return deepcopy(self) else: return copy(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 tlog(x, th=1, r=_display_max, d=_l_mmax): """ Truncated log10 transform. Parameters x : num | num iterable values to be transformed. th : num values below th...
if th <= 0: raise ValueError('Threshold value must be positive. %s given.' % th) return where(x <= th, log10(th) * 1. * r / d, log10(x) * 1. * r / 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 tlog_inv(y, th=1, r=_display_max, d=_l_mmax): """ Inverse truncated log10 transform. Values Parameters y : num | num iterable values to be transformed. th : ...
if th <= 0: raise ValueError('Threshold value must be positive. %s given.' % th) x = 10 ** (y * 1. * d / r) try: x[x < th] = th except TypeError: if x < th: x = th return 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 hlog_inv(y, b=500, r=_display_max, d=_l_mmax): """ Inverse of base 10 hyperlog transform. """
aux = 1. * d / r * y s = sign(y) if s.shape: # to catch case where input is a single number s[s == 0] = 1 elif s == 0: s = 1 return s * 10 ** (s * aux) + b * aux - 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 _x_for_spln(x, nx, log_spacing): """ Create vector of values to be used in constructing a spline. Parameters x : num | num iterable Resulted values will span...
x = asarray(x) xmin = min(x) xmax = max(x) if xmin == xmax: return asarray([xmin] * nx) if xmax <= 0: # all values<=0 return -_x_for_spln(-x, nx, log_spacing)[::-1] if not log_spacing: return linspace(xmin, xmax, nx) # All code below is to handle-log-spacing when ...
<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_hlog_numeric(b, r, d): """ Return a function that numerically computes the hlog transformation for given parameter values. """
hlog_obj = lambda y, x, b, r, d: hlog_inv(y, b, r, d) - x find_inv = vectorize(lambda x: brentq(hlog_obj, -2 * r, 2 * r, args=(x, b, r, d))) return find_inv
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hlog(x, b=500, r=_display_max, d=_l_mmax): """ Base 10 hyperlog transform. Parameters x : num | num iterable values to be transformed. b : num Parameter cont...
hlog_fun = _make_hlog_numeric(b, r, d) if not hasattr(x, '__len__'): # if transforming a single number y = hlog_fun(x) else: n = len(x) if not n: # if transforming empty container return x else: y = hlog_fun(x) return y
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transform_frame(frame, transform, columns=None, direction='forward', return_all=True, args=(), **kwargs): """ Apply transform to specified columns. direction...
tfun, tname = parse_transform(transform, direction) columns = to_list(columns) if columns is None: columns = frame.columns if return_all: transformed = frame.copy() for c in columns: transformed[c] = tfun(frame[c], *args, **kwargs) else: transformed = fra...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transform(self, x, use_spln=False, **kwargs): """ Apply transform to x Parameters x : float-array-convertible Data to be transformed. Should support conversi...
x = asarray(x, dtype=float) if use_spln: if self.spln is None: self.set_spline(x.min(), x.max(), **kwargs) return apply_along_axis(self.spln, 0, x) else: return self.tfun(x, *self.args, **self.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 pypi_register(server='pypitest'): """Register and prep user for PyPi upload. .. note:: May need to weak ~/.pypirc file per issue: http://stackoverflow.com/qu...
base_command = 'python setup.py register' if server == 'pypitest': command = base_command + ' -r https://testpypi.python.org/pypi' else: command = base_command _execute_setup_command(command)
<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_format(var, format_str): """Format all non-iterables inside of the iterable var using the format_str Example: will return ['2.0', ['1.0', '4.0'], '4.0'...
if isinstance(var, (list, tuple)): new_var = map(lambda x: apply_format(x, format_str), var) if isinstance(var, tuple): new_var = '(' + ', '.join(new_var) + ')' elif isinstance(var, list): new_var = '[' + ', '.join(new_var) + ']' return '{}'.format(new_var) ...
<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_spawnable(source_channels, target_channels): """Check whether gate is spawnable on the target channels."""
if len(target_channels) != len(set(target_channels)): raise Exception('Spawn channels must be unique') return source_channels.issubset( set(target_channels))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def key_press_handler(event, canvas, toolbar=None): """ Handles keyboard shortcuts for the FCToolbar. """
if event.key is None: return key = event.key.encode('ascii', 'ignore') if key in ['1']: toolbar.create_gate_widget(kind='poly') elif key in ['2', '3', '4']: kind = {'2': 'quad', '3': 'horizontal threshold', '4': 'vertical threshold'}[key] toolbar.create_gate_widget(kind=kind) ...
<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_callback(self, func): """ Registers a call back function """
if func is None: return func_list = to_list(func) if not hasattr(self, 'callback_list'): self.callback_list = func_list else: self.callback_list.extend(func_list)
<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_artist(self): """ decides whether the artist should be visible or not in the current axis current_axis : names of x, y axis """
verts = self.coordinates if not self.tracky: trans = self.ax.get_xaxis_transform(which='grid') elif not self.trackx: trans = self.ax.get_yaxis_transform(which='grid') else: trans = self.ax.transData self.artist = pl.Line2D([verts[0]], [verts...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ignore(self, event): """ Ignores events. """
if hasattr(event, 'inaxes'): if event.inaxes != self.ax: return True else: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spawn(self, channels, ax): """ Spawns a graphical gate that can be used to update the coordinates of the current gate. """
if _check_spawnable(self.source_channels, channels): sgate = self.gate_type(self.verts, ax, channels) self.spawn_list.append(sgate) return sgate else: return 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 remove_spawned_gates(self, spawn_gate=None): """ Removes all spawned gates. """
if spawn_gate is None: for sg in list(self.spawn_list): self.spawn_list.remove(sg) sg.remove() else: spawn_gate.remove() self.spawn_list.remove(spawn_gate)
<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_generation_code(self, **gencode): """ Generates python code that can create the gate. """
channels, verts = self.coordinates channels = ', '.join(["'{}'".format(ch) for ch in channels]) verts = list(verts) ## Formatting the vertexes # List level (must be first), used for gates that may have multiple vertexes like a polygon if len(verts) == 1: ve...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _gencode_gate_class(self): """ Returns the class name that generates this gate. """
channels, verts = self.coordinates num_channels = len(channels) gate_type_name = self.gate_type.__name__ if gate_type_name == 'ThresholdGate' and num_channels == 2: gate_type_name = 'QuadGate' return gate_type_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 source_channels(self): """ Returns a set describing the source channels on which the gate is defined. """
source_channels = [v.coordinates.keys() for v in self.verts] return set(itertools.chain(*source_channels))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pick_event_handler(self, event): """ Handles pick events """
info = {'options': self.get_available_channels(), 'guiEvent': event.mouseevent.guiEvent, } if hasattr(self, 'xlabel_artist') and (event.artist == self.xlabel_artist): info['axis_num'] = 0 self.callback(Event('axis_click', info)) if hasat...
<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_data(self): """Plots the loaded data"""
# Clear the plot before plotting onto it self.ax.cla() if self.sample is None: return if self.current_channels is None: self.current_channels = self.sample.channel_names[:2] channels = self.current_channels channels_to_plot = channels[0] if len...
<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_generation_code(self): """Return python code that generates all drawn gates."""
if len(self.gates) < 1: code = '' else: import_list = set([gate._gencode_gate_class for gate in self.gates]) import_list = 'from FlowCytometryTools import ' + ', '.join(import_list) code_list = [gate.get_generation_code() for gate in self.gates] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replace(self): """Reformat values inside the self.doc_dict using self.doc_dict TODO: Make support for partial_formatting """
doc_dict = self.doc_dict.copy() for k, v in doc_dict.items(): if '{' and '}' in v: self.doc_dict[k] = v.format(**doc_dict)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _format(self, doc): """ Formats the docstring using self.doc_dict """
if self.allow_partial_formatting: mapping = FormatDict(self.doc_dict) else: mapping = self.doc_dict formatter = string.Formatter() return formatter.vformat(doc, (), 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 get_package_version(path): '''Extracts the version''' with open(VERSION_FILE, "rt") as f: verstrline = f.read() VERSION = r"^version = ['\"]([^'\"]*)['\"]" results = re.search(VERSION, verstrline, re.M) if results: version = results.group(1) else: raise RuntimeError...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _assign_IDS_to_datafiles(datafiles, parser, measurement_class=None, **kwargs): """ Assign measurement IDS to datafiles using specified parser. Parameters dat...
if isinstance(parser, collections.Mapping): fparse = lambda x: parser[x] elif hasattr(parser, '__call__'): fparse = lambda x: parser(x, **kwargs) elif parser == 'name': kwargs.setdefault('pre', 'Well_') kwargs.setdefault('post', ['_', '\.', '$']) kwargs.setdefault('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 set_data(self, data=None, **kwargs): ''' Read data into memory, applying all actions in queue. Additionally, update queue and history. ''' if data is None: data = self.get_data(**kwargs) setattr(self, '_data', data) self.history += self.queue ...
<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_meta(self, meta=None, **kwargs): ''' Assign values to self.meta. Meta is not returned ''' if meta is None: meta = self.get_meta(**kwargs) setattr(self, '_meta', meta)
<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_data(self, **kwargs): ''' Get the measurement data. If data is not set, read from 'self.datafile' using 'self.read_data'. ''' if self.queue: new = self.apply_queued() return new.get_data() else: return self._get_attr_from_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 apply(self, func, applyto='measurement', noneval=nan, setdata=False): """ Apply func either to self or to associated data. If data is not already parsed, try...
applyto = applyto.lower() if applyto == 'data': if self.data is not None: data = self.data elif self.datafile is None: return noneval else: data = self.read_data() if setdata: self.da...
<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_files(cls, ID, datafiles, parser, readdata_kwargs={}, readmeta_kwargs={}, **ID_kwargs): """ Create a Collection of measurements from a set of data files...
d = _assign_IDS_to_datafiles(datafiles, parser, cls._measurement_class, **ID_kwargs) measurements = [] for sID, dfile in d.items(): try: measurements.append(cls._measurement_class(sID, datafile=dfile, readdat...
<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(self, criteria, applyto='measurement', ID=None): """ Filter measurements according to given criteria. Retain only Measurements for which criteria retu...
fil = criteria new = self.copy() if isinstance(applyto, collections.Mapping): remove = (k for k, v in self.items() if not fil(applyto[k])) elif applyto == 'measurement': remove = (k for k, v in self.items() if not fil(v)) elif applyto == 'keys': ...
<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_by_key(self, keys, ID=None): """ Keep only Measurements with given keys. """
keys = to_list(keys) fil = lambda x: x in keys if ID is None: ID = self.ID return self.filter(fil, applyto='keys', ID=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 filter_by_IDs(self, ids, ID=None): """ Keep only Measurements with given IDs. """
fil = lambda x: x in ids return self.filter_by_attr('ID', fil, 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 filter_by_rows(self, rows, ID=None): """ Keep only Measurements in corresponding rows. """
rows = to_list(rows) fil = lambda x: x in rows applyto = {k: self._positions[k][0] for k in self.keys()} if ID is None: ID = self.ID return self.filter(fil, applyto=applyto, ID=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 filter_by_cols(self, cols, ID=None): """ Keep only Measurements in corresponding columns. """
rows = to_list(cols) fil = lambda x: x in rows applyto = {k: self._positions[k][1] for k in self.keys()} if ID is None: ID = self.ID + '.filtered_by_cols' return self.filter(fil, applyto=applyto, ID=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_files(cls, ID, datafiles, parser='name', position_mapper=None, readdata_kwargs={}, readmeta_kwargs={}, ID_kwargs={}, **kwargs): """ Create an OrderedCol...
if position_mapper is None: if isinstance(parser, six.string_types): position_mapper = parser else: msg = "When using a custom parser, you must specify the position_mapper keyword." raise ValueError(msg) d = _assign_IDS_to_datafile...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _is_valid_position(self, position): ''' check if given position is valid for this collection ''' row, col = position valid_r = row in self.row_labels valid_c = col in self.col_labels return valid_r and valid_c
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _get_ID2position_mapper(self, position_mapper): ''' Defines a position parser that is used to map between sample IDs and positions. Parameters -------------- {_bases_position_mapper} TODO: Fix the name to work with more than 26 letters of the alphabe...
<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_positions(self, positions=None, position_mapper='name', ids=None): ''' checks for position validity & collisions, but not that all measurements are assigned. Parameters ----------- positions : is dict-like of measurement_key:(row,col) parser : ...
<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_positions(self, copy=True): ''' Get a dictionary of measurement positions. ''' if copy: return self._positions.copy() else: return self._positions
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dropna(self): ''' Remove rows and cols that have no assigned measurements. Return new instance. ''' new = self.copy() tmp = self._dict2DF(self, nan, True) new.row_labels = list(tmp.index) new.col_labels = list(tmp.columns) return new
<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_input(self): """Raise appropriate exception if gate was defined incorrectly."""
if self.vert[1] <= self.vert[0]: raise ValueError(u'{} must be larger than {}'.format(self.vert[1], self.vert[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 _identify(self, dataframe): """Return bool series which is True for indexes that 'pass' the gate"""
idx = ((dataframe[self.channels[0]] <= self.vert[1]) & (dataframe[self.channels[0]] >= self.vert[0])) if self.region == 'out': idx = ~idx return idx
<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_paths(): """Generate paths to test data. Done in a function to protect namespace a bit."""
import os base_path = os.path.dirname(os.path.abspath(__file__)) test_data_dir = os.path.join(base_path, 'tests', 'data', 'Plate01') test_data_file = os.path.join(test_data_dir, 'RFP_Well_A3.fcs') return test_data_dir, test_data_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 upload_prev(ver, doc_root='./'): 'push a copy of older release to appropriate version directory' local_dir = doc_root + 'build/html' remote_dir = '/usr/share/nginx/pandas/pandas-docs/version/%s/' % ver cmd = 'cd %s; rsync -avz . pandas@pandas.pydata.org:%s -essh' cmd = cmd % (local_dir, remote_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 plotFCM(data, channel_names, kind='histogram', ax=None, autolabel=True, xlabel_kwargs={}, ylabel_kwargs={}, colorbar=False, grid=False, **kwargs): """ Plots ...
if ax == None: ax = pl.gca() xlabel_kwargs.setdefault('size', 16) ylabel_kwargs.setdefault('size', 16) channel_names = to_list(channel_names) if len(channel_names) == 1: # 1D so histogram plot kwargs.setdefault('color', 'gray') kwargs.setdefault('histtype', 'stepfilled')...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def autoscale_subplots(subplots=None, axis='both'): """ Sets the x and y axis limits for each subplot to match the x and y axis limits of the most extreme data p...
axis_options = ('x', 'y', 'both', 'none', '', 'xy', 'yx') if axis.lower() not in axis_options: raise ValueError('axis must be in {0}'.format(axis_options)) if subplots is None: subplots = plt.gcf().axes data_limits = [(ax.xaxis.get_data_interval(), ax.yaxis.get_data_interval()) for 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 scale_subplots(subplots=None, xlim='auto', ylim='auto'): """Set the x and y axis limits for a collection of subplots. Parameters subplots : ndarray or list o...
auto_axis = '' if xlim == 'auto': auto_axis += 'x' if ylim == 'auto': auto_axis += 'y' autoscale_subplots(subplots, auto_axis) for loc, ax in numpy.ndenumerate(subplots): if 'x' not in auto_axis: ax.set_xlim(xlim) if 'y' not in auto_axis: ax...
<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_table(matrix, text_format='{:.2f}', cmap=None, **kwargs): """ Plot a numpy matrix as a table. Uses the current axis bounding box to decide on limits. t...
shape = matrix.shape xtick_pos = numpy.arange(shape[1]) ytick_pos = numpy.arange(shape[0]) xtick_grid, ytick_grid = numpy.meshgrid(xtick_pos, ytick_pos) vmax = numpy.nanmax(matrix) vmin = numpy.nanmin(matrix) if not kwargs.get('color', None) and cmap is not None: use_cmap = True...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _set_tick_lines_visibility(ax, visible=True): """Set the visibility of the tick lines of the requested axis."""
for i, thisAxis in enumerate((ax.get_xaxis(), ax.get_yaxis())): for thisItem in thisAxis.get_ticklines(): if isinstance(visible, list): thisItem.set_visible(visible[i]) else: thisItem.set_visible(visible)
<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_tick_labels_visibility(ax, visible=True): """Set the visibility of the tick labels of the requested axis."""
for i, thisAxis in enumerate((ax.get_xaxis(), ax.get_yaxis())): for thisItem in thisAxis.get_ticklabels(): if isinstance(visible, list): thisItem.set_visible(visible[i]) else: thisItem.set_visible(visible)