INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
skip column if either is a gap
def remove_gaps(A, B): """ skip column if either is a gap """ a_seq, b_seq = [], [] for a, b in zip(list(A), list(B)): if a == '-' or a == '.' or b == '-' or b == '.': continue a_seq.append(a) b_seq.append(b) return ''.join(a_seq), ''.join(b_seq)
compare pairs of sequences
def compare_seqs(seqs): """ compare pairs of sequences """ A, B, ignore_gaps = seqs a, b = A[1], B[1] # actual sequences if len(a) != len(b): print('# reads are not the same length', file=sys.stderr) exit() if ignore_gaps is True: pident = calc_pident_ignore_gaps(a, b...
calculate Levenshtein ratio of sequences
def compare_seqs_leven(seqs): """ calculate Levenshtein ratio of sequences """ A, B, ignore_gaps = seqs a, b = remove_gaps(A[1], B[1]) # actual sequences if len(a) != len(b): print('# reads are not the same length', file=sys.stderr) exit() pident = lr(a, b) * 100 return A...
make pairwise sequence comparisons between aligned sequences
def pairwise_compare(afa, leven, threads, print_list, ignore_gaps): """ make pairwise sequence comparisons between aligned sequences """ # load sequences into dictionary seqs = {seq[0]: seq for seq in nr_fasta([afa], append_index = True)} num_seqs = len(seqs) # define all pairs pairs = (...
- convert list of comparisons to dictionary - print list of pidents ( if requested ) to stderr
def to_dictionary(pw, print_list): """ - convert list of comparisons to dictionary - print list of pidents (if requested) to stderr """ pairs = {} for p in pw: a, b, pident = p if a not in pairs: pairs[a] = {a: '-'} if b not in pairs: pairs[b] = {b...
print matrix of pidents to stdout
def print_pairwise(pw, median = False): """ print matrix of pidents to stdout """ names = sorted(set([i for i in pw])) if len(names) != 0: if '>' in names[0]: yield ['#'] + [i.split('>')[1] for i in names if '>' in i] else: yield ['#'] + names for a in...
print stats for comparisons
def print_comps(comps): """ print stats for comparisons """ if comps == []: print('n/a') else: print('# min: %s, max: %s, mean: %s' % \ (min(comps), max(comps), np.mean(comps)))
print min. pident within each clade and then matrix of between - clade max.
def compare_clades(pw): """ print min. pident within each clade and then matrix of between-clade max. """ names = sorted(set([i for i in pw])) for i in range(0, 4): wi, bt = {}, {} for a in names: for b in pw[a]: if ';' not in a or ';' not in b: ...
convert matrix to dictionary of comparisons
def matrix2dictionary(matrix): """ convert matrix to dictionary of comparisons """ pw = {} for line in matrix: line = line.strip().split('\t') if line[0].startswith('#'): names = line[1:] continue a = line[0] for i, pident in enumerate(line[1:]...
Set argument parser option.
def setoption(parser, metadata=None): """Set argument parser option.""" parser.add_argument('-v', action='version', version=__version__) subparsers = parser.add_subparsers(help='sub commands help') create_cmd = subparsers.add_parser('create') create_cmd.add_argument('name', ...
Validate url.
def valid_url(url): """Validate url. :rtype: str :return: url :param str url: package homepage url. """ regex = re.compile( r'^(?:http)s?://' r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+' r'(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?))' r'(?:/?|[/?]\S+)$', re.IGNORECA...
Parse argument options.
def parse_options(metadata): """Parse argument options.""" parser = argparse.ArgumentParser(description='%(prog)s usage:', prog=__prog__) setoption(parser, metadata=metadata) return parser
Execute main processes.
def main(): """Execute main processes.""" try: pkg_version = Update() if pkg_version.updatable(): pkg_version.show_message() metadata = control.retreive_metadata() parser = parse_options(metadata) argvs = sys.argv if len(argvs) <= 1: parser...
Set name: value property to Package object.
def _set_param(self, name, value): """Set name:value property to Package object.""" if name == 'status': setattr(self, name, self.metadata.status().get(value)) elif name == 'license': setattr(self, name, self.metadata.licenses().get(value)) elif name == 'name': ...
Check key and set default vaule when it does not exists.
def _check_or_set_default_params(self): """Check key and set default vaule when it does not exists.""" if not hasattr(self, 'date'): self._set_param('date', datetime.utcnow().strftime('%Y-%m-%d')) if not hasattr(self, 'version'): self._set_param('version', self.default_ve...
Move directory from working directory to output directory.
def move(self): """Move directory from working directory to output directory.""" if not os.path.isdir(self.outdir): os.makedirs(self.outdir) shutil.move(self.tmpdir, os.path.join(self.outdir, self.name))
Initialize VCS repository.
def vcs_init(self): """Initialize VCS repository.""" VCS(os.path.join(self.outdir, self.name), self.pkg_data)
example_capture
def example_capture(): """example_capture An example capture script Change the network interface by ``export CAP_DEVICE=eth0`` """ dev = ev( "CAP_DEVICE", "lo") """ Ignore ports for forwarding to consolidators: Redis Internal VM: 6379, 16379 RabbitMQ Internal VM...
capture_udp_packets
def capture_udp_packets(): """capture_udp_packets Capture ``UDP`` packets and call the ``handle_packets`` method Change the network interface by ``export CAP_DEVICE=eth0`` """ dev = ev( "CAP_DEVICE", "lo") """ Ignore ports for forwarding to consolidators: Redis VM: 6...
Finds the location of the current Steam installation on Windows machines. Returns None for any non - Windows machines or for Windows machines where Steam is not installed.
def find_steam_location(): """ Finds the location of the current Steam installation on Windows machines. Returns None for any non-Windows machines, or for Windows machines where Steam is not installed. """ if registry is None: return None key = registry.CreateKey(registry.HKEY_CURRENT_USER,"Software\...
convert_pkt_to_json Inspired by: https:// gist. githubusercontent. com/ cr0hn/ 1b0c2e672cd0721d3a07/ raw/ 9144676ceb12dbd545e6dce366822bbedde8de2c/ pkg_to_json. py This function convert a Scapy packet to JSON
def convert_pkt_to_json(pkg): """ convert_pkt_to_json Inspired by: https://gist.githubusercontent.com/cr0hn/1b0c2e672cd0721d3a07/raw/9144676ceb12dbd545e6dce366822bbedde8de2c/pkg_to_json.py This function convert a Scapy packet to JSON :param pkg: A kamene package :type pkg: objects :return:...
Plot PCoA principal coordinates scaled by the relative abundances of otu_name.
def plot_PCoA(cat_data, otu_name, unifrac, names, colors, xr, yr, outDir, save_as, plot_style): """ Plot PCoA principal coordinates scaled by the relative abundances of otu_name. """ fig = plt.figure(figsize=(14, 8)) ax = fig.add_subplot(111) for i, cat in enumerate(cat_data):...
Split up the column data in a biom table by mapping category value.
def split_by_category(biom_cols, mapping, category_id): """ Split up the column data in a biom table by mapping category value. """ columns = defaultdict(list) for i, col in enumerate(biom_cols): columns[mapping[col['id']][category_id]].append((i, col)) return columns
print line if starts with...
def print_line(l): """ print line if starts with ... """ print_lines = ['# STOCKHOLM', '#=GF', '#=GS', ' '] if len(l.split()) == 0: return True for start in print_lines: if l.startswith(start): return True return False
convert stockholm to single line format
def stock2one(stock): """ convert stockholm to single line format """ lines = {} for line in stock: line = line.strip() if print_line(line) is True: yield line continue if line.startswith('//'): continue ID, seq = line.rsplit(' ', 1...
Statics the methods. wut.
def math_func(f): """ Statics the methods. wut. """ @wraps(f) def wrapper(*args, **kwargs): if len(args) > 0: return_type = type(args[0]) if kwargs.has_key('return_type'): return_type = kwargs['return_type'] kwargs.pop('return_type') re...
Show stats when pings are done
def dump_stats(myStats): """ Show stats when pings are done """ print("\n----%s PYTHON PING Statistics----" % (myStats.thisIP)) if myStats.pktsSent > 0: myStats.fracLoss = (myStats.pktsSent - myStats.pktsRcvd) \ / myStats.pktsSent print(("%d packets transmitted, %d pack...
Send > count< ping to > destIP< with the given > timeout< and display the result.
def verbose_ping(hostname, timeout=WAIT_TIMEOUT, count=NUM_PACKETS, packet_size=PACKET_SIZE, path_finder=False): """ Send >count< ping to >destIP< with the given >timeout< and display the result. """ signal.signal(signal.SIGINT, signal_handler) # Handle Ctrl-C if hasattr(signa...
bootstrap - py package updatable?.
def updatable(self): """bootstrap-py package updatable?.""" if self.latest_version > self.current_version: updatable_version = self.latest_version else: updatable_version = False return updatable_version
Show message updatable.
def show_message(self): """Show message updatable.""" print( 'current version: {current_version}\n' 'latest version : {latest_version}'.format( current_version=self.current_version, latest_version=self.latest_version))
Traverse the input otu - sequence file collect the non - unique OTU IDs and file the sequences associated with then under the unique OTU ID as defined by the input matrix.
def condense_otus(otuF, nuniqueF): """ Traverse the input otu-sequence file, collect the non-unique OTU IDs and file the sequences associated with then under the unique OTU ID as defined by the input matrix. :@type otuF: file :@param otuF: The output file from QIIME's pick_otus.py :@type nu...
determine if read overlaps with rna if so count bases
def rna_bases(rna_cov, scaffold, bases, line): """ determine if read overlaps with rna, if so count bases """ start = int(line[3]) stop = start + bases - 1 if scaffold not in rna_cov: return rna_cov for pos in rna_cov[scaffold][2]: ol = get_overlap([start, stop], pos) ...
parse ggKbase scaffold - to - bin mapping - scaffolds - to - bins and bins - to - scaffolds
def parse_s2bins(s2bins): """ parse ggKbase scaffold-to-bin mapping - scaffolds-to-bins and bins-to-scaffolds """ s2b = {} b2s = {} for line in s2bins: line = line.strip().split() s, b = line[0], line[1] if 'UNK' in b: continue if len(line) > 2...
parse [ 16 23 ] SfromHMM. py output - rna_cov [ scaffold ] = [ 0 0 [] ] # [ bases length ranges ]
def parse_rna(rna, s2bins, min_rna): """ parse [16,23]SfromHMM.py output - rna_cov[scaffold] = [0, 0, []] # [bases, length, ranges] """ rna_cov = {} for seq in parse_fasta(rna): # check that length passes threshold length = len(seq[1]) if length < min_rna: con...
remove any bins that don t have 16S
def filter_missing_rna(s2bins, bins2s, rna_cov): """ remove any bins that don't have 16S """ for bin, scaffolds in list(bins2s.items()): c = 0 for s in scaffolds: if s in rna_cov: c += 1 if c == 0: del bins2s[bin] for scaffold, bin in l...
calculate bin coverage
def calc_bin_cov(scaffolds, cov): """ calculate bin coverage """ bases = sum([cov[i][0] for i in scaffolds if i in cov]) length = sum([cov[i][1] for i in scaffolds if i in cov]) if length == 0: return 0 return float(float(bases)/float(length))
1. determine bin coverage 2. determine rRNA gene coverage 3. compare
def copies(mapping, s2bins, rna, min_rna = 800, mismatches = 0): """ 1. determine bin coverage 2. determine rRNA gene coverage 3. compare """ cov = {} # cov[scaffold] = [bases, length] s2bins, bins2s = parse_s2bins(s2bins) rna_cov = parse_rna(rna, s2bins, min_rna) s2bins, bins2s = fi...
Make sure there is at least a translation has been filled in. If a default language has been specified make sure that it exists amongst translations.
def clean(self): """ Make sure there is at least a translation has been filled in. If a default language has been specified, make sure that it exists amongst translations. """ # First make sure the super's clean method is called upon. super(TranslationFormSet, se...
If a default language has been set and is still available in self. available_languages return it and remove it from the list.
def _get_default_language(self): """ If a default language has been set, and is still available in `self.available_languages`, return it and remove it from the list. If not, simply pop the first available language. """ assert hasattr(self, 'available_languages'), \ ...
Construct the form overriding the initial value for language_code.
def _construct_form(self, i, **kwargs): """ Construct the form, overriding the initial value for `language_code`. """ if not settings.HIDE_LANGUAGE: self._construct_available_languages() form = super(TranslationFormSet, self)._construct_form(i, **kwargs) if ...
Split the list of OTUs ( and associated sequence ids ) into two lists: those occurring in more than some percentage of samples and those less than the cutoff.
def filter_by_sample_pct(otus, nsamples, pct, phyl_level): """ Split the list of OTUs (and associated sequence ids) into two lists: those occurring in more than some percentage of samples and those less than the cutoff. :type otus: dict :param otus: {otuid: [taxonomy, [sequence IDs]]} :type...
Split the list of OTUs ( and associated sequence ids ) into two lists: those occurring associated with more than some percentage of total sequences and those less than the cutoff.
def filter_by_sequence_pct(otus, nseqs, pct, phyl_level): """ Split the list of OTUs (and associated sequence ids) into two lists: those occurring associated with more than some percentage of total sequences and those less than the cutoff. :type otus: dict :param otus: {otuid: [taxonomy, [seque...
merge separate fastq files
def fq_merge(R1, R2): """ merge separate fastq files """ c = itertools.cycle([1, 2, 3, 4]) for r1, r2 in zip(R1, R2): n = next(c) if n == 1: pair = [[], []] pair[0].append(r1.strip()) pair[1].append(r2.strip()) if n == 4: yield pair
Creates hash ring.
def _build_circle(self): """ Creates hash ring. """ total_weight = 0 for node in self._nodes: total_weight += self._weights.get(node, 1) for node in self._nodes: weight = self._weights.get(node, 1) ks = math.floor((40 * len(self._...
Return node position ( integer ) for a given key. Else return None
def _get_node_pos(self, key): """ Return node position(integer) for a given key. Else return None """ if not self._hashring: return None key = self._gen_key(key) nodes = self._sorted_keys pos = bisect(nodes, key) if pos == len(nodes): ...
Return long integer for a given key that represent it place on the hash ring.
def _gen_key(self, key): """ Return long integer for a given key, that represent it place on the hash ring. """ b_key = self._md5_digest(key) return self._hashi(b_key, lambda x: x)
Removes node from circle and rebuild it.
def remove_node(self, node): """ Removes node from circle and rebuild it. """ try: self._nodes.remove(node) del self._weights[node] except (KeyError, ValueError): pass self._hashring = dict() self._sorted_keys = [] ...
Adds node to circle and rebuild it.
def add_node(self, node, weight=1): """ Adds node to circle and rebuild it. """ self._nodes.add(node) self._weights[node] = weight self._hashring = dict() self._sorted_keys = [] self._build_circle()
process_ether_frame
def process_ether_frame(self, id=None, msg=None): """process_ether_frame Convert a complex nested json dictionary to a flattened dictionary and capture all unique keys for table construction :param id: key for this msg ...
process_ip_frame
def process_ip_frame(self, id=None, msg=None): """process_ip_frame Convert a complex nested json dictionary to a flattened dictionary and capture all unique keys for table construction :param id: key for this msg :param ...
process_ipvsix_frame
def process_ipvsix_frame(self, id=None, msg=None): """process_ipvsix_frame Convert a complex nested json dictionary to a flattened dictionary and capture all unique keys for table construction :param id: key for this msg...
process_tcp_frame
def process_tcp_frame(self, id=None, msg=None): """process_tcp_frame Convert a complex nested json dictionary to a flattened dictionary and capture all unique keys for table construction :param id: key for this msg :pa...
process_udp_frame
def process_udp_frame(self, id=None, msg=None): """process_udp_frame Convert a complex nested json dictionary to a flattened dictionary and capture all unique keys for table construction :param id: key for this msg :pa...
process_dns_frame
def process_dns_frame(self, id=None, msg=None): """process_dns_frame Convert a complex nested json dictionary to a flattened dictionary and capture all unique keys for table construction :param id: key for this msg :pa...
process_icmp_frame
def process_icmp_frame(self, id=None, msg=None): """process_icmp_frame Convert a complex nested json dictionary to a flattened dictionary and capture all unique keys for table construction :param id: key for this msg ...
process_arp_frame
def process_arp_frame(self, id=None, msg=None): """process_arp_frame Convert a complex nested json dictionary to a flattened dictionary and capture all unique keys for table construction :param id: key for this msg :pa...
process_raw_frame
def process_raw_frame(self, id=None, msg=None): """process_raw_frame Convert a complex nested json dictionary to a flattened dictionary and capture all unique keys for table construction :param id: key for this msg :pa...
process_pad_frame
def process_pad_frame(self, id=None, msg=None): """process_pad_frame Convert a complex nested json dictionary to a flattened dictionary and capture all unique keys for table construction :param id: key for this msg :pa...
build_flat_msg
def build_flat_msg(self, id=None, msg=None): """build_flat_msg :param id: unique id for this message :param msg: message dictionary to flatten """ flat_msg = {} if not id: log.error("Please pass in an id") ...
build_all_keys_dict
def build_all_keys_dict(self): """build_all_keys_dict""" log.info("finding keys") for k in self.eth_keys: ak = "{}".format(k) if ak not in self.all_keys: self.all_keys[ak] = k # end of building all eths for k in self.ip_keys: a...
flatten_all
def flatten_all(self): """flatten_all""" log.info("flattening - START") self.all_rows = [] for idx, r in enumerate(self.all_flat): new_row = {"idx": idx} for k in self.all_keys_list: if k in r: new_row[k] = r[k] ...
create_json_archive
def create_json_archive(self): """create_json_archive""" archive_data = {"packets": self.recv_msgs, "dataset": self.dataset_name, "num_packets": len(self.recv_msgs), "created": rnow()} self.write_to_file(archive_data, ...
convert_to_df
def convert_to_df(self): """convert_to_df""" log.info(("converting={}") .format(len(self.all_rows))) if len(self.all_rows) == 0: return self.df = pd.DataFrame(self.all_rows).set_index("idx") if len(self.df) != len(self.all_rows): log.e...
write_to_file
def write_to_file(self, data_dict, output_file_path): """write_to_file :param data_dict: :param output_file_path: """ log.info("saving={}".format(output_file_path)) with open(output_file_path, "w") as output_file: ...
save_df_as_csv
def save_df_as_csv(self): """save_df_as_csv""" if len(self.all_rows) == 0: log.info(("no df={} to save") .format(self.df)) return else: log.info(("saving " "packets={} file={} rows={}") .format(...
save_data
def save_data(self): """save_data""" state = "" try: state = "create_json_archive" log.info("creating json archive") self.create_json_archive() state = "building_unique_keys" log.info("processing all unique keys") self.bu...
handle_msg
def handle_msg(self, body, org_message): """handle_msg :param body: dictionary contents from the message body :param org_message: message object can ack, requeue or reject """ if os.path.exists(self.stop_for_file): log.info(("De...
publish_predictions_to_core
def publish_predictions_to_core(self): """publish_predictions_to_core""" status = FAILED msg = "not started" try: msg = "generating request" log.info(msg) # noqa https://stackoverflow.com/questions/29815129/pandas-dataframe-to-list-of-dictionaries ...
OVERRIDDEN: Initialize required FGDC data map with XPATHS and specialized functions
def _init_data_map(self): """ OVERRIDDEN: Initialize required FGDC data map with XPATHS and specialized functions """ if self._data_map is not None: return # Initiation happens once # Parse and validate the FGDC metadata root if self._xml_tree is None: fgdc_ro...
Ensures complete removal of raster_info given the two roots: <spdoinfo > and <spref >
def _update_raster_info(self, **update_props): """ Ensures complete removal of raster_info given the two roots: <spdoinfo> and <spref> """ xpath_map = self._data_structures[update_props['prop']] return [ update_complex(xpath_root=self._data_map.get('_raster_info_root'), xpath_map=x...
Returns True if there exists a custom image for app_id.
def has_custom_image(user_context, app_id): """Returns True if there exists a custom image for app_id.""" possible_paths = _valid_custom_image_paths(user_context, app_id) return any(map(os.path.exists, possible_paths))
Returns the custom image associated with a given app. If there are multiple candidate images on disk one is chosen arbitrarily.
def get_custom_image(user_context, app_id): """Returns the custom image associated with a given app. If there are multiple candidate images on disk, one is chosen arbitrarily.""" possible_paths = _valid_custom_image_paths(user_context, app_id) existing_images = filter(os.path.exists, possible_paths) if len(ex...
Sets the custom image for app_id to be the image located at image_path. If there already exists a custom image for app_id it will be deleted. Returns True is setting the image was successful.
def set_custom_image(user_context, app_id, image_path): """Sets the custom image for `app_id` to be the image located at `image_path`. If there already exists a custom image for `app_id` it will be deleted. Returns True is setting the image was successful.""" if image_path is None: return False if not os...
Read an orthography profile from a metadata file or a default tab - separated profile file.
def from_file(cls, fname, form=None): """ Read an orthography profile from a metadata file or a default tab-separated profile file. """ try: tg = TableGroup.from_file(fname) opfname = None except JSONDecodeError: tg = TableGroup.fromvalue(cls.M...
Create a Profile instance from the Unicode graphemes found in text.
def from_text(cls, text, mapping='mapping'): """ Create a Profile instance from the Unicode graphemes found in `text`. Parameters ---------- text mapping Returns ------- A Profile instance. """ graphemes = Counter(grapheme_patter...
split fasta file into separate fasta files based on list of scaffolds that belong to each separate file
def split_fasta(f, id2f): """ split fasta file into separate fasta files based on list of scaffolds that belong to each separate file """ opened = {} for seq in parse_fasta(f): id = seq[0].split('>')[1].split()[0] if id not in id2f: continue fasta = id2f[id] ...
Check whether pathname is a valid user data directory
def _is_user_directory(self, pathname): """Check whether `pathname` is a valid user data directory This method is meant to be called on the contents of the userdata dir. As such, it will return True when `pathname` refers to a directory name that can be interpreted as a users' userID. """...
Returns an array of user ids for users on the filesystem
def local_users(self): """Returns an array of user ids for users on the filesystem""" # Any users on the machine will have an entry inside of the userdata # folder. As such, the easiest way to find a list of all users on the # machine is to just list the folders inside userdata u...
Calculates the temperature equivalent from a series of average daily temperatures according to the formula: 0. 6 * tempDay0 + 0. 3 * tempDay - 1 + 0. 1 * tempDay - 2
def calculate_temperature_equivalent(temperatures): """ Calculates the temperature equivalent from a series of average daily temperatures according to the formula: 0.6 * tempDay0 + 0.3 * tempDay-1 + 0.1 * tempDay-2 Parameters ---------- series : Pandas Series Returns ------- Pandas...
Calculates degree days starting with a series of temperature equivalent values
def _calculate_degree_days(temperature_equivalent, base_temperature, cooling=False): """ Calculates degree days, starting with a series of temperature equivalent values Parameters ---------- temperature_equivalent : Pandas Series base_temperature : float cooling : bool Set True if y...
Compute degree - days for heating and/ or cooling
def compute_degree_days(ts, heating_base_temperatures, cooling_base_temperatures): """ Compute degree-days for heating and/or cooling Parameters ---------- ts : pandas.Series Contains ambient (outside) temperature. Series name (ts.name) does not matter. heating_base_temperatures: list ...
Development status.
def status(self): """Development status.""" return {self._acronym_status(l): l for l in self.resp_text.split('\n') if l.startswith(self.prefix_status)}
OSI Approved license.
def licenses(self): """OSI Approved license.""" return {self._acronym_lic(l): l for l in self.resp_text.split('\n') if l.startswith(self.prefix_lic)}
Remove prefix.
def licenses_desc(self): """Remove prefix.""" return {self._acronym_lic(l): l.split(self.prefix_lic)[1] for l in self.resp_text.split('\n') if l.startswith(self.prefix_lic)}
Convert license acronym.
def _acronym_lic(self, license_statement): """Convert license acronym.""" pat = re.compile(r'\(([\w+\W?\s?]+)\)') if pat.search(license_statement): lic = pat.search(license_statement).group(1) if lic.startswith('CNRI'): acronym_licence = lic[:4] ...
calc MD5 based on path
def calcMD5(path): """ calc MD5 based on path """ # check that file exists if os.path.exists(path) is False: yield False else: command = ['md5sum', path] p = Popen(command, stdout = PIPE) for line in p.communicate()[0].splitlines(): yield line.decode('...
* comfirm that downloaded files match md5 checksum on server * if md5 is False only check path for the download
def md5check(f, ftp, md5, exclude): """ * comfirm that downloaded files match md5 checksum on server * if md5 is False, only check path for the download """ files = glob(f) # if no md5 file is specified: download files if path does not exist if md5 is False: if len(files) == 0: ...
download files with wget
def wget(ftp, f = False, exclude = False, name = False, md5 = False, tries = 10): """ download files with wget """ # file name if f is False: f = ftp.rsplit('/', 1)[-1] # downloaded file if it does not already exist # check md5s on server (optional) t = 0 while md5check(f, ft...
check that at least one of queries is in list l
def check(line, queries): """ check that at least one of queries is in list, l """ line = line.strip() spLine = line.replace('.', ' ').split() matches = set(spLine).intersection(queries) if len(matches) > 0: return matches, line.split('\t') return matches, False
search entrez using specified database and accession
def entrez(db, acc): """ search entrez using specified database and accession """ c1 = ['esearch', '-db', db, '-query', acc] c2 = ['efetch', '-db', 'BioSample', '-format', 'docsum'] p1 = Popen(c1, stdout = PIPE, stderr = PIPE) p2 = Popen(c2, stdin = p1.stdout, stdout = PIPE, stderr = PIP...
attempt to use NCBI Entrez to get BioSample ID
def searchAccession(acc): """ attempt to use NCBI Entrez to get BioSample ID """ # try genbank file # genome database out, error = entrez('genome', acc) for line in out.splitlines(): line = line.decode('ascii').strip() if 'Assembly_Accession' in line or 'BioSample' in lin...
download genome info from NCBI
def getFTPs(accessions, ftp, search, exclude, convert = False, threads = 1, attempt = 1, max_attempts = 2): """ download genome info from NCBI """ info = wget(ftp)[0] allMatches = [] for genome in open(info, encoding = 'utf8'): genome = str(genome) matches, genomeInfo...
download genomes from NCBI
def download(args): """ download genomes from NCBI """ accessions, infoFTP = set(args['g']), args['i'] search, exclude = args['s'], args['e'] FTPs = getFTPs(accessions, infoFTP, search, exclude, threads = args['t'], convert = args['convert']) if args['test'] is True: for ...
remove pesky characters from fasta file header
def fix_fasta(fasta): """ remove pesky characters from fasta file header """ for seq in parse_fasta(fasta): seq[0] = remove_char(seq[0]) if len(seq[1]) > 0: yield seq
Plot transformed LDA data.
def plot_LDA(X_lda, y_lda, class_colors, exp_var, style, fig_size, label_pad, font_size, sids, dim=2, zangles=None, pt_size=250, out_fp=""): """ Plot transformed LDA data. """ cats = class_colors.keys() fig = plt.figure(figsize=fig_size) if dim == 3: try: assert ...
Run LinearDiscriminantAnalysis on input dataframe ( df ) and return transformed data scalings and explained variance by discriminants.
def run_LDA(df): """ Run LinearDiscriminantAnalysis on input dataframe (df) and return transformed data, scalings and explained variance by discriminants. """ # Prep variables for sklearn LDA X = df.iloc[:, 1:df.shape[1]].values # input data matrix y = df["Condition"].values ...
Compute a DataFrame summary of a Stats object.
def _calc_frames(stats): """ Compute a DataFrame summary of a Stats object. """ timings = [] callers = [] for key, values in iteritems(stats.stats): timings.append( pd.Series( key + values[:-1], index=timing_colnames, ) ) ...
get unmapped reads
def unmapped(sam, mates): """ get unmapped reads """ for read in sam: if read.startswith('@') is True: continue read = read.strip().split() if read[2] == '*' and read[6] == '*': yield read elif mates is True: if read[2] == '*' or re...
Preprocess text for SugarTeX Pandoc filter. Replaces ˎ with $ ( except \ ˎ ) replaces \ ˎ with ˎ
def sugartex_preprocess(source: str) -> str: """ Preprocess text for SugarTeX Pandoc filter. Replaces 'ˎ' with `$` (except `\ˎ`), replaces `\ˎ` with `ˎ` """ rep = {r'\ˎ': 'ˎ', 'ˎ': '$'} return re.sub(r'\\ˎ|ˎ', lambda m: rep[m.group(0)], source)
Replace all with SugarTeX. Runs sugartex_preprocess then iterates via regex and replaces each math between $... $.
def sugartex_replace_all(string): """ Replace all with SugarTeX. Runs ``sugartex_preprocess`` then iterates via regex and replaces each math between '$...$'. """ string = sugartex_preprocess(string).replace(r'\$', SESSION_ID) return re.sub( r'(?<=\$)[^$]*(?=\$)', lambda m: su...