INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
filter sequences that are shown to be mapped in the sam file reads not in sam file are in *.filtered.fastq reads that are in the sam file are in *.matched.fastq
def filter(fastq, sam, paired = False): """ filter sequences that are shown to be mapped in the sam file reads not in sam file are in *.filtered.fastq reads that are in the sam file are in *.matched.fastq """ if paired is False: list = sam_list(sam) else: list = sam_list_paired(sam) if paired is False: f...
handle_processing_packets Replacement packet processing engine. This is not done.
def handle_processing_packets(): """handle_processing_packets Replacement packet processing engine. This is not done. """ host = os.getenv( "LISTEN_ON_HOST", "127.0.0.1").strip().lstrip() port = int(os.getenv( "LISTEN_ON_PORT", "80").strip().lstrip()) backlog =...
listen_on_udp_port Run a simple server for processing messages over ``UDP``. ``UDP_LISTEN_ON_HOST`` - listen on this host ip address ``UDP_LISTEN_ON_PORT`` - listen on this ``UDP`` port ``UDP_LISTEN_SIZE`` - listen on to packets of this size ``UDP_LISTEN_SLEEP`` - sleep this number of seconds p...
def listen_on_udp_port(): """listen_on_udp_port Run a simple server for processing messages over ``UDP``. ``UDP_LISTEN_ON_HOST`` - listen on this host ip address ``UDP_LISTEN_ON_PORT`` - listen on this ``UDP`` port ``UDP_LISTEN_SIZE`` - listen on to packets of this size ``UDP_LISTEN_SLEEP``...
send_udp_message Send a ``UDP`` message to port 80 by default. Environment variables: ``UDP_SEND_TO_HOST`` - host ip address ``UDP_SEND_TO_PORT`` - send to this UDP port
def send_udp_message(): """send_udp_message Send a ``UDP`` message to port 80 by default. Environment variables: ``UDP_SEND_TO_HOST`` - host ip address ``UDP_SEND_TO_PORT`` - send to this UDP port """ host = os.getenv( "UDP_SEND_TO_HOST", "0.0.0.0").strip().lstrip() p...
print fastq from sam
def sam2fastq(line): """ print fastq from sam """ fastq = [] fastq.append('@%s' % line[0]) fastq.append(line[9]) fastq.append('+%s' % line[0]) fastq.append(line[10]) return fastq
look for NM:i:<N> flag to determine number of mismatches
def count_mismatches(read): """ look for NM:i:<N> flag to determine number of mismatches """ if read is False: return False mm = [int(i.split(':')[2]) for i in read[11:] if i.startswith('NM:i:')] if len(mm) > 0: return sum(mm) else: return False
- check to see if the read maps with <= threshold number of mismatches - mm_option = 'one' or 'both' depending on whether or not one or both reads in a pair need to pass the mismatch threshold - pair can be False if read does not have a pair - make sure alignment score is not 0, which would indicate ...
def check_mismatches(read, pair, mismatches, mm_option, req_map): """ - check to see if the read maps with <= threshold number of mismatches - mm_option = 'one' or 'both' depending on whether or not one or both reads in a pair need to pass the mismatch threshold - pair can be False if read does n...
determine whether or not reads map to specific region of scaffold
def check_region(read, pair, region): """ determine whether or not reads map to specific region of scaffold """ if region is False: return True for mapping in read, pair: if mapping is False: continue start, length = int(mapping[3]), len(mapping[9]) r = [s...
get mapped reads (and their pairs) from an unsorted sam file
def get_reads(sam, \ contigs = False, mismatches = False, mm_option = False, \ sort_sam = True, req_map = False, region = False, sbuffer = False): """ get mapped reads (and their pairs) from an unsorted sam file """ tempdir = '%s/' % (os.path.abspath(sam).rsplit('/', 1)[0]) if sort_s...
Returns a Steam object representing the current Steam installation on the users computer. If the user doesn't have Steam installed, returns None.
def get_steam(): """ Returns a Steam object representing the current Steam installation on the users computer. If the user doesn't have Steam installed, returns None. """ # Helper function which checks if the potential userdata directory exists # and returns a new Steam instance with that userdata directory...
Determine a simple Genus-species identifier for an OTU, if possible. If OTU is not identified to the species level, name it as Unclassified (familly/genus/etc...). :type tax: list :param tax: QIIME-style taxonomy identifiers, e.g. ["k__Bacteria", u"p__Firmicutes", u"c__Bacilli", ... ...
def otu_name(tax): """ Determine a simple Genus-species identifier for an OTU, if possible. If OTU is not identified to the species level, name it as Unclassified (familly/genus/etc...). :type tax: list :param tax: QIIME-style taxonomy identifiers, e.g. ["k__Bacteria", u"p__Fir...
For core OTU data file, returns Genus-species identifier for each data entry. :type core_fp: str :param core_fp: A file containing core OTU data. :rtype: str :return: Returns genus-species identifier based on identified taxonomical level.
def load_core_file(core_fp): """ For core OTU data file, returns Genus-species identifier for each data entry. :type core_fp: str :param core_fp: A file containing core OTU data. :rtype: str :return: Returns genus-species identifier based on identified taxonomical level. """...
Determines the OTUIDs present in each sample. :type biomfile: biom.table.Table :param biomfile: BIOM table object from the biom-format library. :rtype: dict :return: Returns a dictionary keyed on Sample ID with sets containing the IDs of OTUIDs found in each sample.
def assign_otu_membership(biomfile): """ Determines the OTUIDs present in each sample. :type biomfile: biom.table.Table :param biomfile: BIOM table object from the biom-format library. :rtype: dict :return: Returns a dictionary keyed on Sample ID with sets containing the IDs of OTUIDs found ...
normalize from zero to one for row or table
def zero_to_one(table, option): """ normalize from zero to one for row or table """ if option == 'table': m = min(min(table)) ma = max(max(table)) t = [] for row in table: t_row = [] if option != 'table': m, ma = min(row), max(row) for i in row...
calculate percent of total
def pertotal(table, option): """ calculate percent of total """ if option == 'table': total = sum([i for line in table for i in line]) t = [] for row in table: t_row = [] if option != 'table': total = sum(row) for i in row: if total == 0: ...
standardize Z = (X - mean) / (standard deviation)
def standardize(table, option): """ standardize Z = (X - mean) / (standard deviation) """ if option == 'table': mean = np.mean(table) std = np.std(table) t = [] for row in table: t_row = [] if option != 'table': mean = np.mean(row) std ...
scale table based on the column with the largest sum
def scale(table): """ scale table based on the column with the largest sum """ t = [] columns = [[] for i in table[0]] for row in table: for i, v in enumerate(row): columns[i].append(v) sums = [float(sum(i)) for i in columns] scale_to = float(max(sums)) scale_fact...
fit to normal distribution
def norm(table): """ fit to normal distribution """ print('# norm dist is broken', file=sys.stderr) exit() from matplotlib.pyplot import hist as hist t = [] for i in table: t.append(np.ndarray.tolist(hist(i, bins = len(i), normed = True)[0])) return t
log transform each value in table
def log_trans(table): """ log transform each value in table """ t = [] all = [item for sublist in table for item in sublist] if min(all) == 0: scale = min([i for i in all if i != 0]) * 10e-10 else: scale = 0 for i in table: t.append(np.ndarray.tolist(np.log10([j +...
box-cox transform table
def box_cox(table): """ box-cox transform table """ from scipy.stats import boxcox as bc t = [] for i in table: if min(i) == 0: scale = min([j for j in i if j != 0]) * 10e-10 else: scale = 0 t.append(np.ndarray.tolist(bc(np.array([j + scale for j i...
inverse hyperbolic sine transformation
def inh(table): """ inverse hyperbolic sine transformation """ t = [] for i in table: t.append(np.ndarray.tolist(np.arcsinh(i))) return t
from SparCC - "randomly draw from the corresponding posterior Dirichlet distribution with a uniform prior"
def diri(table): """ from SparCC - "randomly draw from the corresponding posterior Dirichlet distribution with a uniform prior" """ t = [] for i in table: a = [j + 1 for j in i] t.append(np.ndarray.tolist(np.random.mtrand.dirichlet(a))) return t
transpose matrix
def transpose(table): """ transpose matrix """ t = [] for i in range(0, len(table[0])): t.append([row[i] for row in table]) return t
transform data table: option: rows columns table mode: 0: 0-1 pertotal: percent of total stand: standardize scale: scale based on largest column
def transform(table, option, mode): """ transform data table: option: rows columns table mode: 0: 0-1 pertotal: percent of total stand: standardize scale: scale based on largest column """ if option != 'rows' and option != 'columns' and opt...
send_tcp_large_message Send a large ``TCP`` message to port 80 by default.
def send_tcp_large_message(): """send_tcp_large_message Send a large ``TCP`` message to port 80 by default. """ need_response = os.getenv("NEED_RESPONSE", "0") == "1" msg = os.getenv( "MSG", "testing msg time={} - {}".format( datetime.datetime.now().strfti...
Open a file for reading with either the standard built-in open() or the open in the codecs module for reading UTF-16 encoded files. :param fn: Name of the file to open :param utf16: Boolean flag to specify a UTF-16 file
def open_enc(fn, utf16): """ Open a file for reading with either the standard built-in open() or the open in the codecs module for reading UTF-16 encoded files. :param fn: Name of the file to open :param utf16: Boolean flag to specify a UTF-16 file """ if utf16: return codecs.open(f...
Given a list of sample IDs generate unique n-base barcodes for each. Note that only 4^n unique barcodes are possible.
def generate_barcodes(nIds, codeLen=12): """ Given a list of sample IDs generate unique n-base barcodes for each. Note that only 4^n unique barcodes are possible. """ def next_code(b, c, i): return c[:i] + b + (c[i+1:] if i < -1 else '') def rand_base(): return random.choice(['A...
Given a mapping from sample IDs to barcodes/primers/other info, write out a QIIME-compatible mapping file. File format described at: http://qiime.org/documentation/file_formats.html Note that primer column can be left blank.
def write_mapping_file(mapF, sampleIDs, barcodes, treatment=None): """ Given a mapping from sample IDs to barcodes/primers/other info, write out a QIIME-compatible mapping file. File format described at: http://qiime.org/documentation/file_formats.html Note that primer column can be left blank. ...
Given a sample ID and a mapping, modify a Sanger FASTA file to include the barcode and 'primer' in the sequence data and change the description line as needed.
def scrobble_data_dir(dataDir, sampleMap, outF, qualF=None, idopt=None, utf16=False): """ Given a sample ID and a mapping, modify a Sanger FASTA file to include the barcode and 'primer' in the sequence data and change the description line as needed. """ seqcount = 0 out...
Uses the built-in argparse module to handle command-line options for the program. :return: The gathered command-line options specified by the user :rtype: argparse.ArgumentParser
def handle_program_options(): """ Uses the built-in argparse module to handle command-line options for the program. :return: The gathered command-line options specified by the user :rtype: argparse.ArgumentParser """ parser = argparse.ArgumentParser(description="Convert Sanger-sequencing \ ...
find_all_headers :param pipeline_files: files to process :param label_rules: labeling rules
def find_all_headers( pipeline_files=[], label_rules=None): """find_all_headers :param pipeline_files: files to process :param label_rules: labeling rules """ log.info("find_all_headers - START") headers = ["src_file"] headers_dict = {"src_file": None} if label_rules:...
handle_packets :param pk: data packet that kamene sends in
def handle_packets(pk): """handle_packets :param pk: data packet that kamene sends in """ log.info(("processing with pub={}") .format(pub)) # get the lowest layer eth = pk.getlayer(kamene.Ether) should_forward = False send_msg = {"data": {}, "created": rn...
build_csv :param pipeline_files: files to process :param fulldata_file: output all columns to this csv file :param clean_file: output all numeric-ready columns to this csv file :param post_proc_rules: rules after building the DataFrame :param label_rules: labeling rules :param metadata_filename...
def build_csv( pipeline_files=[], fulldata_file=None, clean_file=None, post_proc_rules=None, label_rules=None, metadata_filename="metadata.json"): """build_csv :param pipeline_files: files to process :param fulldata_file: output all columns to this csv file ...
find_all_pipeline_csvs :param csv_glob_path: path to csvs
def find_all_pipeline_csvs( csv_glob_path="/opt/antinex/datasets/**/*.csv"): """find_all_pipeline_csvs :param csv_glob_path: path to csvs """ log.info("finding pipeline csvs in dir={}".format(csv_glob_path)) pipeline_files = [] for csv_file in glob.iglob(csv_glob_path, ...
prepare_new_dataset
def prepare_new_dataset(): """prepare_new_dataset""" clean_dir = ev( "OUTPUT_DIR", "/tmp") clean_file = ev( "CLEANED_FILE", "{}/cleaned_attack_scans.csv".format( clean_dir)) fulldata_file = ev( "FULLDATA_FILE", "{}/fulldata_attack_scans.csv".fo...
Write the BIOM table to a file. :type biom_tbl: biom.table.Table :param biom_tbl: A BIOM table containing the per-sample OTU counts and metadata to be written out to file. :type output_fp str :param output_fp: Path to the BIOM-format file that will be written. :type fmt: str :p...
def write_biom(biom_tbl, output_fp, fmt="hdf5", gzip=False): """ Write the BIOM table to a file. :type biom_tbl: biom.table.Table :param biom_tbl: A BIOM table containing the per-sample OTU counts and metadata to be written out to file. :type output_fp str :param output_fp: Pat...
Applies the arcsine square root transform to the given BIOM-format table
def arcsin_sqrt(biom_tbl): """ Applies the arcsine square root transform to the given BIOM-format table """ arcsint = lambda data, id_, md: np.arcsin(np.sqrt(data)) tbl_relabd = relative_abd(biom_tbl) tbl_asin = tbl_relabd.transform(arcsint, inplace=False) return tbl_asin
parse sam file and check mapping quality
def parse_sam(sam, qual): """ parse sam file and check mapping quality """ for line in sam: if line.startswith('@'): continue line = line.strip().split() if int(line[4]) == 0 or int(line[4]) < qual: continue yield line
genomes = {} # genomes[genome][contig][sample] = {'bp_stats':[]}
def save_refs(sam, fastas, genomes, s2b): """ genomes = {} # genomes[genome][contig][sample] = {'bp_stats':[]} """ if s2b is False: s2b = {} for fasta in fastas: # if no reference sequence supplied, get length from sam file if fasta is False: for line in sam: ...
parse cigar string into list of operations e.g.: 28M1I29M2I6M1I46M -> [['28', 'M'], ['1', 'I'], ['29', 'M'], ['2', 'I'], ['6', 'M'], ['1', 'I'], ['46', 'M']]
def parse_cigar(cigar): """ parse cigar string into list of operations e.g.: 28M1I29M2I6M1I46M -> [['28', 'M'], ['1', 'I'], ['29', 'M'], ['2', 'I'], ['6', 'M'], ['1', 'I'], ['46', 'M']] """ cigar = cigar.replace('M', 'M ').replace('I', 'I ').replace('D', 'D ').split() cigar = [c.replac...
save base pair frequency statistics for each base from sam file genomes = {} # genomes[genome][contig][sample] = {'bp_stats':{}}
def get_bp_stats(sam, genomes, s2b, qual): """ save base pair frequency statistics for each base from sam file genomes = {} # genomes[genome][contig][sample] = {'bp_stats':{}} """ for read in parse_sam(sam, qual): ref = read[2] # scaffold that read mapped to if ref not in s2b: ...
reverse completement stats
def rc_stats(stats): """ reverse completement stats """ rc_nucs = {'A':'T', 'T':'A', 'G':'C', 'C':'G', 'N':'N'} rcs = [] for pos in reversed(stats): rc = {} rc['reference frequencey'] = pos['reference frequency'] rc['consensus frequencey'] = pos['consensus frequency'] ...
parse codon nucleotide positions in range start -> end, wrt strand
def parse_codons(ref, start, end, strand): """ parse codon nucleotide positions in range start -> end, wrt strand """ codon = [] c = cycle([1, 2, 3]) ref = ref[start - 1:end] if strand == -1: ref = rc_stats(ref) for pos in ref: n = next(c) codon.append(pos) ...
calculate coverage for positions in range start -> end
def calc_coverage(ref, start, end, length, nucs): """ calculate coverage for positions in range start -> end """ ref = ref[start - 1:end] bases = 0 for pos in ref: for base, count in list(pos.items()): if base in nucs: bases += count return float(bases)/fl...
parse gbk file
def parse_gbk(gbks): """ parse gbk file """ for gbk in gbks: for record in SeqIO.parse(open(gbk), 'genbank'): for feature in record.features: if feature.type == 'gene': try: locus = feature.qualifiers['locus_tag'][0] ...
parse gene call information from Prodigal fasta output
def parse_fasta_annotations(fastas, annot_tables, trans_table): """ parse gene call information from Prodigal fasta output """ if annot_tables is not False: annots = {} for table in annot_tables: for cds in open(table): ID, start, end, strand = cds.strip().spl...
parse annotations in either gbk or Prodigal fasta format
def parse_annotations(annots, fmt, annot_tables, trans_table): """ parse annotations in either gbk or Prodigal fasta format """ annotations = {} # annotations[contig] = [features] # gbk format if fmt is False: for contig, feature in parse_gbk(annots): if contig not in annotat...
count types of mutations in codon counts = {'obs syn':#, 'pos syn':#, 'obs non-syn':#, 'pos non-syn':#}
def count_mutations(codon, AA, alleles, counts, nucs, trans_table): """ count types of mutations in codon counts = {'obs syn':#, 'pos syn':#, 'obs non-syn':#, 'pos non-syn':#} """ # find alternative codons based on SNPs obs_codons = [] # codons observed from SNPs for pos, pos_mutations in en...
convert codon to amino acid
def codon2aa(codon, trans_table): """ convert codon to amino acid """ return Seq(''.join(codon), IUPAC.ambiguous_dna).translate(table = trans_table)[0]
counts = {'obs syn':#, 'pos syn':#, 'obs non-syn':#, 'pos non-syn':#}
def calc_PnPs(counts): """ counts = {'obs syn':#, 'pos syn':#, 'obs non-syn':#, 'pos non-syn':#} """ if counts['pos non-syn'] == 0 or counts['pos syn'] == 0: return 'n/a' NonSyn = float(counts['obs non-syn'])/float(counts['pos non-syn']) Syn = float(counts['obs syn']) /float(counts...
calculate syn and non-syn sub. rates for each locus/gene
def sub_rates(stats, annots): """ calculate syn and non-syn sub. rates for each locus/gene """ nucs = ['A', 'T', 'G', 'C'] subs = {} # subs[locus]{pn/ps reference, pn/ps consensus, snp density} for cds in annots: locus, location, info = cds subs[locus] = {} start, end, st...
find consensus base based on nucleotide frequencies
def find_consensus(bases): """ find consensus base based on nucleotide frequencies """ nucs = ['A', 'T', 'G', 'C', 'N'] total = sum([bases[nuc] for nuc in nucs if nuc in bases]) # save most common base as consensus (random nuc if there is a tie) try: top = max([bases[nuc] for nuc...
print bp frequencies to table genomes = {} # genomes[genome][contig][sample] = {'bp_stats':{}}
def calc_frequencies(genomes, bp_table, min_cov, min_per): """ print bp frequencies to table genomes = {} # genomes[genome][contig][sample] = {'bp_stats':{}} """ nucs = ['A', 'T', 'G', 'C', 'N'] if bp_table is not False: bp_table = open(bp_table, 'w') header = ['#genome', 'contig...
print consensensus sequences for each genome and sample
def print_consensus(genomes): """ print consensensus sequences for each genome and sample """ # generate consensus sequences cons = {} # cons[genome][sample][contig] = consensus for genome, contigs in list(genomes.items()): cons[genome] = {} for contig, samples in list(contigs.it...
print substitution rate data to table genomes[genome][contig][sample] = \ {'bp_stats':{}, 'sub_rates'[locus] = {ref PnPs, consensus PnPs}}
def print_stats(genomes): """ print substitution rate data to table genomes[genome][contig][sample] = \ {'bp_stats':{}, 'sub_rates'[locus] = {ref PnPs, consensus PnPs}} """ header = ['#genome', 'contig', 'locus', 'position', 'strand', 'length', \ 'sample', 'coverage', \ ...
quantify genomic variation from mapping genomes[genome][contig][sample] = \ {'bp_stats':[], 'sub_rates'[locus] = {ref PnPs, consensus PnPs, ...}}
def variation(fastas, sams, s2b, annots, qual, min_cov, min_per, no_sub, bp_table, print_con): """ quantify genomic variation from mapping genomes[genome][contig][sample] = \ {'bp_stats':[], 'sub_rates'[locus] = {ref PnPs, consensus PnPs, ...}} """ genomes = {} # save base-pair data...
custom = {(reads mapped to scaffold)/(total reads for sample)}/(length of scaffold)
def calc_custom(custom, genome, scaffold, sequence, scaffold_coverage, total_bases): """ custom = {(reads mapped to scaffold)/(total reads for sample)}/(length of scaffold) """ index = 0 if scaffold in scaffold_coverage: # what if the scaffold does not have bases mapped back to it? (this *should* not happen) if ...
absolute abundance = (number of bases mapped to genome / total number of bases in sample) * 100
def absolute_abundance(coverage, total_bases): """ absolute abundance = (number of bases mapped to genome / total number of bases in sample) * 100 """ absolute = {} for genome in coverage: absolute[genome] = [] index = 0 for calc in coverage[genome]: bases = calc[0] total = total_bases[index] absolu...
cov = number of bases / length of genome relative abundance = [(cov) / sum(cov for all genomes)] * 100
def relative_abundance(coverage): """ cov = number of bases / length of genome relative abundance = [(cov) / sum(cov for all genomes)] * 100 """ relative = {} sums = [] for genome in coverage: for cov in coverage[genome]: sums.append(0) break for genome in coverage: index = 0 for cov in coverage[geno...
coverage = (number of bases / length of genome) * 100
def genome_coverage(genomes, scaffold_coverage, total_bases): """ coverage = (number of bases / length of genome) * 100 """ coverage = {} custom = {} std = {} for genome in genomes: for sequence in parse_fasta(genome): scaffold = sequence[0].split('>')[1].split()[0] coverage, std = sum_coverage(coverage,...
calculate genome coverage from scaffold coverage table
def parse_cov(cov_table, scaffold2genome): """ calculate genome coverage from scaffold coverage table """ size = {} # size[genome] = genome size mapped = {} # mapped[genome][sample] = mapped bases # parse coverage files for line in open(cov_table): line = line.strip().split('\t') ...
calculate genome coverage from scaffold coverage
def genome_coverage(covs, s2b): """ calculate genome coverage from scaffold coverage """ COV = [] for cov in covs: COV.append(parse_cov(cov, s2b)) return pd.concat(COV)
convert s2b files to dictionary
def parse_s2bs(s2bs): """ convert s2b files to dictionary """ s2b = {} for s in s2bs: for line in open(s): line = line.strip().split('\t') s, b = line[0], line[1] s2b[s] = b return s2b
convert fastas to s2b dictionary
def fa2s2b(fastas): """ convert fastas to s2b dictionary """ s2b = {} for fa in fastas: for seq in parse_fasta(fa): s = seq[0].split('>', 1)[1].split()[0] s2b[s] = fa.rsplit('/', 1)[-1].rsplit('.', 1)[0] return s2b
eth_addr :param f: eth frame
def eth_addr(f): """eth_addr :param f: eth frame """ data = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (f[0], f[1], f[2], f[3], ...
build_node :param data_packet: raw recvfrom data :param filter_keys: list of strings to filter and remove baby-birding packets to yourself :param record_tcp: want to record TCP frames? :param record_udp: want to record UDP frames? :param record_arp: w...
def parse_network_data(data_packet=None, include_filter_key=None, filter_keys=[], record_tcp=True, record_udp=True, record_arp=True, record_icmp=True): """build_node :param ...
Filters out sequences with too much ambiguity as defined by the method parameters. :type records: list :param records: A list of sequences :type repeats: int :param repeats: Defines the number of repeated N that trigger truncating a sequence. :type percent: float :param ...
def filter_ambiguity(records, percent=0.5): # , repeats=6) """ Filters out sequences with too much ambiguity as defined by the method parameters. :type records: list :param records: A list of sequences :type repeats: int :param repeats: Defines the number of repeated N that trigger truncat...
:param root: Tree node. :param line: String to parse. :param idx: Global counter of characters parsed. :return: (list of parsed graphemes, incremented character count)
def _parse(self, root, line, idx): """ :param root: Tree node. :param line: String to parse. :param idx: Global counter of characters parsed. :return: (list of parsed graphemes, incremented character count) """ # Base (or degenerate..) case. if len(line) =...
Search package. * :class:`bootstrap_py.exceptions.Conflict` exception occurs when user specified name has already existed. * :class:`bootstrap_py.exceptions.BackendFailure` exception occurs when PyPI service is down. :param str name: package name
def package_existent(name): """Search package. * :class:`bootstrap_py.exceptions.Conflict` exception occurs when user specified name has already existed. * :class:`bootstrap_py.exceptions.BackendFailure` exception occurs when PyPI service is down. :param str name: package name """ ...
Given a BIOM table, calculate per-sample relative abundance for each OTU and write out to a tab-separated file listing OTUs as rows and Samples as columns. :type biom: biom object :param biom: BIOM-formatted OTU/Sample abundance data :type out_fn: str :param out_fn: The full path to the desired ...
def write_relative_abundance(rel_abd, biomf, out_fn, sort_by=None): """ Given a BIOM table, calculate per-sample relative abundance for each OTU and write out to a tab-separated file listing OTUs as rows and Samples as columns. :type biom: biom object :param biom: BIOM-formatted OTU/Sample abund...
add index to id to make it unique wrt ids
def append_index_id(id, ids): """ add index to id to make it unique wrt ids """ index = 1 mod = '%s_%s' % (id, index) while mod in ids: index += 1 mod = '%s_%s' % (id, index) ids.append(mod) return mod, ids
de-replicate fastas based on sequence names
def de_rep(fastas, append_index, return_original = False): """ de-replicate fastas based on sequence names """ ids = [] for fasta in fastas: for seq in parse_fasta(fasta): header = seq[0].split('>')[1].split() id = header[0] if id not in ids: ...
Request data associated with `postcode`. :param postcode: the postcode to search for. The postcode may contain spaces (they will be removed). :returns: a dict of the nearest postcode's data or None if no postcode data is found.
def get(postcode): """ Request data associated with `postcode`. :param postcode: the postcode to search for. The postcode may contain spaces (they will be removed). :returns: a dict of the nearest postcode's data or None if no postcode data is found. """ po...
Request all postcode data within `distance` miles of `postcode`. :param postcode: the postcode to search for. The postcode may contain spaces (they will be removed). :param distance: distance in miles to `postcode`. :returns: a list of dicts containing postcode data within the ...
def get_from_postcode(postcode, distance): """ Request all postcode data within `distance` miles of `postcode`. :param postcode: the postcode to search for. The postcode may contain spaces (they will be removed). :param distance: distance in miles to `postcode`. :returns: a ...
Checks if latitude and longitude correct
def _check_point(self, lat, lng): """ Checks if latitude and longitude correct """ if abs(lat) > 90 or abs(lng) > 180: msg = "Illegal lat and/or lng, (%s, %s) provided." % (lat, lng) raise IllegalPointException(msg)
Checks for cached responses, before requesting from web-service
def _lookup(self, skip_cache, fun, *args, **kwargs): """ Checks for cached responses, before requesting from web-service """ if args not in self.cache or skip_cache: self.cache[args] = fun(*args, **kwargs) return self.cache[args]
Calls `postcodes.get` and by default utilises a local cache. :param skip_cache: optional argument specifying whether to skip the cache and make an explicit request. Given postcode data doesn't really change, it's unlike...
def get(self, postcode, skip_cache=False): """ Calls `postcodes.get` and by default utilises a local cache. :param skip_cache: optional argument specifying whether to skip the cache and make an explicit request. Given postcode data...
Calls `postcodes.get_nearest` but checks correctness of `lat` and `long`, and by default utilises a local cache. :param skip_cache: optional argument specifying whether to skip the cache and make an explicit request. :raises IllegalPointException: if the latitude o...
def get_nearest(self, lat, lng, skip_cache=False): """ Calls `postcodes.get_nearest` but checks correctness of `lat` and `long`, and by default utilises a local cache. :param skip_cache: optional argument specifying whether to skip the cache and make an exp...
Calls `postcodes.get_from_postcode` but checks correctness of `distance`, and by default utilises a local cache. :param skip_cache: optional argument specifying whether to skip the cache and make an explicit request. :raises IllegalPointException: if the latitude o...
def get_from_postcode(self, postcode, distance, skip_cache=False): """ Calls `postcodes.get_from_postcode` but checks correctness of `distance`, and by default utilises a local cache. :param skip_cache: optional argument specifying whether to skip the cache ...
Calls `postcodes.get_from_geo` but checks the correctness of all arguments, and by default utilises a local cache. :param skip_cache: optional argument specifying whether to skip the cache and make an explicit request. :raises IllegalPointException: if the latitude...
def get_from_geo(self, lat, lng, distance, skip_cache=False): """ Calls `postcodes.get_from_geo` but checks the correctness of all arguments, and by default utilises a local cache. :param skip_cache: optional argument specifying whether to skip the cache and...
get coordinates of insertions from insertion-masked sequence
def insertions_from_masked(seq): """ get coordinates of insertions from insertion-masked sequence """ insertions = [] prev = True for i, base in enumerate(seq): if base.isupper() and prev is True: insertions.append([]) prev = False elif base.islower(): ...
analyze fa (names, insertions) and convert fasta to prodigal/cmscan safe file - find insertions (masked sequence) - make upper case - assign names to id number
def analyze_fa(fa): """ analyze fa (names, insertions) and convert fasta to prodigal/cmscan safe file - find insertions (masked sequence) - make upper case - assign names to id number """ if fa.name == '<stdin>': safe = 'temp.id' else: safe = '%s.id' % (fa.name) safe ...
get insertion information from header
def seq_info(names, id2names, insertions, sequences): """ get insertion information from header """ seqs = {} # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns]], ...]] for name in names: id = id2names[name] gene = name.split('fromHMM::', 1)[0].rs...
make sure thresh % feature is contained within insertion
def check_overlap(pos, ins, thresh): """ make sure thresh % feature is contained within insertion """ ins_pos = ins[0] ins_len = ins[2] ol = overlap(ins_pos, pos) feat_len = pos[1] - pos[0] + 1 # print float(ol) / float(feat_len) if float(ol) / float(feat_len) >= thresh: retur...
find orfs and see if they overlap with insertions # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns]], ...]]
def find_orfs(fa, seqs): """ find orfs and see if they overlap with insertions # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns]], ...]] """ faa = '%s.prodigal.faa' % (fa) fna = '%s.prodigal.fna' % (fa) gbk = '%s.prodigal.gbk' % (fa) if os.path.exist...
find introns by searching Rfam intron databse using cmscan # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns]], ...]]
def find_introns(fa, seqs, sequences, threads): """ find introns by searching Rfam intron databse using cmscan # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns]], ...]] """ db = '%s/rfam/Rfam.cm.1_1.introns' % (os.environ['databases']) out = '%s.rfam-introns...
search orfs against pfam # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns], orfs?, introns?, {orf: annotations}], ...]]
def annotate_orfs(fa, seqs, threads, threshold = 1e-6): """ search orfs against pfam # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns], orfs?, introns?, {orf: annotations}], ...]] """ db = '%s/pfam/Pfam-A.hmm' % os.environ['databases'] base = fa.rsplit('.', ...
- find ORFs using Prodigal - find introns using cmscan (vs Rfam intron database) - check that ORFs and intron overlap with insertion region - plot insertion length versus model position for each insertion (based on insertion type)
def analyze_insertions(fa, threads = 6): """ - find ORFs using Prodigal - find introns using cmscan (vs Rfam intron database) - check that ORFs and intron overlap with insertion region - plot insertion length versus model position for each insertion (based on insertion type) """ safe, sequen...
convert orf and intron information to boolean # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns]], ...]] # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns], orfs?, introns?], ...]]
def seqs2bool(seqs): """ convert orf and intron information to boolean # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns]], ...]] # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns], orfs?, introns?], ...]] """ for seq in s...
print table of results # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns], orfs?, introns?], ...]]
def print_table(seqs, id2name, name): """ print table of results # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns], orfs?, introns?], ...]] """ itable = open('%s.itable' % (name.rsplit('.', 1)[0]), 'w') print('\t'.join(['#sequence', 'gene', 'model', 'inserti...
print fasta of introns and ORFs # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns], orfs?, introns?, [orf annotations]], ...]]
def print_seqs(seqs, id2name, name): """ print fasta of introns and ORFs # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns], orfs?, introns?, [orf annotations]], ...]] """ orfs = open('%s.orfs.faa' % (name.rsplit('.', 1)[0]), 'w') introns = open('%s.introns.f...
length of largest insertion
def max_insertion(seqs, gene, domain): """ length of largest insertion """ seqs = [i[2] for i in list(seqs.values()) if i[2] != [] and i[0] == gene and i[1] == domain] lengths = [] for seq in seqs: for ins in seq: lengths.append(int(ins[2])) if lengths == []: retu...
get length of model
def model_length(gene, domain): """ get length of model """ if gene == '16S': domain2max = {'E_coli_K12': int(1538), 'bacteria': int(1689), 'archaea': int(1563), 'eukarya': int(2652)} return domain2max[domain] elif gene == '23S': domain2max = {'E_coli_K12': int(2903), 'bacter...
setup unique marker for every orf annotation - change size if necessary
def setup_markers(seqs): """ setup unique marker for every orf annotation - change size if necessary """ family2marker = {} # family2marker[family] = [marker, size] markers = cycle(['^', 'p', '*', '+', 'x', 'd', '|', 'v', '>', '<', '8']) size = 60 families = [] for seq in list(seqs.v...
plot insertions wrt model positions 2 panels: 1. insertions with ORF - triangle if has intron - circle if no intron 2. insertion does not have ORF - triangle if has intron - circle if no intron *3. conservation of sequence in model *4. ...
def plot_insertions(fname, seqs, gene, domain, tax, id2name): """ plot insertions wrt model positions 2 panels: 1. insertions with ORF - triangle if has intron - circle if no intron 2. insertion does not have ORF - triangle if has intron - circ...
plot insertions for each gene and domain
def plot_by_gene_and_domain(name, seqs, tax, id2name): """ plot insertions for each gene and domain """ for gene in set([seq[0] for seq in list(seqs.values())]): for domain in set([seq[1] for seq in list(seqs.values())]): plot_insertions(name, seqs, gene, domain, tax, id2name)
normalize the bit score: normalization factor = average max bit score for the two ORFs normalized = bit score / normalization factor
def normalize_bit(A, B, bit, id2desc): """ normalize the bit score: normalization factor = average max bit score for the two ORFs normalized = bit score / normalization factor """ Amax, Bmax = id2desc[A][-1], id2desc[B][-1] norm_factor = float(numpy.average([Amax, Bmax])) normalized = bi...
get the description for each ORF
def get_descriptions(fastas): """ get the description for each ORF """ id2desc = {} for fasta in fastas: for seq in parse_fasta(fasta): header = seq[0].split('>')[1].split(' ') id = header[0] if len(header) > 1: desc = ' '.join(header[1:])...
optimize later? slow ... should combine with calculate_threshold module
def print_genome_matrix(hits, fastas, id2desc, file_name): """ optimize later? slow ... should combine with calculate_threshold module """ out = open(file_name, 'w') fastas = sorted(fastas) print('## percent identity between genomes', file=out) print('# - \t %s' % ('\t'.join(fastas)), fi...
compare genome to self to get the best possible bit score for each ORF
def self_compare(fastas, id2desc, algorithm): """ compare genome to self to get the best possible bit score for each ORF """ for fasta in fastas: blast = open(search(fasta, fasta, method = algorithm, alignment = 'local')) for hit in best_blast(blast, 1): id, bit = hit[0].spli...