idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
11,900 | def image_to_string ( image , lang = None , boxes = False ) : input_file_name = '%s.bmp' % tempnam ( ) output_file_name_base = tempnam ( ) if not boxes : output_file_name = '%s.txt' % output_file_name_base else : output_file_name = '%s.box' % output_file_name_base try : image . save ( input_file_name ) status , error_string = run_tesseract ( input_file_name , output_file_name_base , lang = lang , boxes = boxes ) if status : errors = get_errors ( error_string ) raise TesseractError ( status , errors ) f = file ( output_file_name ) try : return f . read ( ) . strip ( ) finally : f . close ( ) finally : cleanup ( input_file_name ) cleanup ( output_file_name ) | Runs tesseract on the specified image . First the image is written to disk and then the tesseract command is run on the image . Resseract s result is read and the temporary files are erased . |
11,901 | def mitosomatic ( args ) : import pandas as pd p = OptionParser ( mitosomatic . __doc__ ) p . add_option ( "--minaf" , default = .005 , type = "float" , help = "Minimum allele fraction" ) p . add_option ( "--maxaf" , default = .1 , type = "float" , help = "Maximum allele fraction" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) df , = args af_file = df . rsplit ( "." , 1 ) [ 0 ] + ".af" fw = open ( af_file , "w" ) df = pd . read_csv ( df , sep = "\t" ) for i , row in df . iterrows ( ) : na = row [ "num_A" ] nt = row [ "num_T" ] nc = row [ "num_C" ] ng = row [ "num_G" ] nd = row [ "num_D" ] ni = row [ "num_I" ] depth = row [ "depth" ] af = ( nd + ni ) * 1. / depth if not ( opts . minaf <= af <= opts . maxaf ) : continue print ( "{}\t{}\t{:.6f}" . format ( row [ "chrom" ] , row [ "start" ] , af ) , file = fw ) fw . close ( ) logging . debug ( "Allele freq written to `{}`" . format ( af_file ) ) | %prog mitosomatic t . piledriver |
11,902 | def bed ( args ) : p = OptionParser ( bed . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) delt , = args dt = Delly ( delt ) dt . write_bed ( "del.bed" ) | %prog bed del . txt |
11,903 | def mito ( args ) : p = OptionParser ( mito . __doc__ ) p . set_aws_opts ( store = "hli-mv-data-science/htang/mito-deletions" ) p . add_option ( "--realignonly" , default = False , action = "store_true" , help = "Realign only" ) p . add_option ( "--svonly" , default = False , action = "store_true" , help = "Run Realign => SV calls only" ) p . add_option ( "--support" , default = 1 , type = "int" , help = "Minimum number of supporting reads" ) p . set_home ( "speedseq" , default = "/mnt/software/speedseq/bin" ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) chrMfa , bamfile = args store = opts . output_path cleanup = not opts . nocleanup if not op . exists ( chrMfa ) : logging . debug ( "File `{}` missing. Exiting." . format ( chrMfa ) ) return chrMfai = chrMfa + ".fai" if not op . exists ( chrMfai ) : cmd = "samtools index {}" . format ( chrMfa ) sh ( cmd ) if not bamfile . endswith ( ".bam" ) : bamfiles = [ x . strip ( ) for x in open ( bamfile ) ] else : bamfiles = [ bamfile ] if store : computed = ls_s3 ( store ) computed = [ op . basename ( x ) . split ( '.' ) [ 0 ] for x in computed if x . endswith ( ".depth" ) ] remaining_samples = [ x for x in bamfiles if op . basename ( x ) . split ( "." ) [ 0 ] not in computed ] logging . debug ( "Already computed on `{}`: {}" . format ( store , len ( bamfiles ) - len ( remaining_samples ) ) ) bamfiles = remaining_samples logging . debug ( "Total samples: {}" . format ( len ( bamfiles ) ) ) for bamfile in bamfiles : run_mito ( chrMfa , bamfile , opts , realignonly = opts . realignonly , svonly = opts . svonly , store = store , cleanup = cleanup ) | %prog mito chrM . fa input . bam |
11,904 | def fcs ( args ) : p = OptionParser ( fcs . __doc__ ) p . add_option ( "--cutoff" , default = 200 , help = "Skip small components less than [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) fcsfile , = args cutoff = opts . cutoff fp = open ( fcsfile ) for row in fp : if row [ 0 ] == "#" : continue sep = "\t" if "\t" in row else None atoms = row . rstrip ( ) . split ( sep , 3 ) contig , length = atoms [ : 2 ] length = int ( length ) label = atoms [ - 1 ] label = label . replace ( " " , "_" ) if len ( atoms ) == 3 : ranges = "{0}..{1}" . format ( 1 , length ) else : assert len ( atoms ) == 4 ranges = atoms [ 2 ] for ab in ranges . split ( "," ) : a , b = ab . split ( ".." ) a , b = int ( a ) , int ( b ) assert a <= b ahang = a - 1 bhang = length - b if ahang < cutoff : a = 1 if bhang < cutoff : b = length print ( "\t" . join ( str ( x ) for x in ( contig , a - 1 , b , label ) ) ) | %prog fcs fcsfile |
11,905 | def asn ( args ) : from jcvi . formats . base import must_open p = OptionParser ( asn . __doc__ ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) < 1 : sys . exit ( not p . print_help ( ) ) fw = must_open ( opts . outfile , "w" ) for asnfile in args : fp = open ( asnfile ) ingeneralblock = False ingenbankblock = False gb , name = None , None for row in fp : if row . strip ( ) == "" : continue tag = row . split ( ) [ 0 ] if tag == "general" : ingeneralblock = True if ingeneralblock and tag == "str" : if name is None : name = row . split ( "\"" ) [ 1 ] ingeneralblock = False if tag == "genbank" : ingenbankblock = True if ingenbankblock and tag == "accession" : if gb is None : gb = row . split ( "\"" ) [ 1 ] ingenbankblock = False assert gb and name print ( "{0}\t{1}" . format ( gb , name ) , file = fw ) | %prog asn asnfiles |
11,906 | def htgnew ( args ) : from jcvi . formats . fasta import sequin p = OptionParser ( htgnew . __doc__ ) p . add_option ( "--comment" , default = "" , help = "Comments for this submission [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) fastafile , phasefile , sbtfile = args comment = opts . comment fastadir = "fasta" sqndir = "sqn" mkdir ( fastadir ) mkdir ( sqndir ) cmd = "faSplit byname {0} {1}/" . format ( fastafile , fastadir ) sh ( cmd , outfile = "/dev/null" , errfile = "/dev/null" ) acmd = 'tbl2asn -a z -p fasta -r {sqndir}' acmd += ' -i {splitfile} -t {sbtfile} -C tigr' acmd += ' -j "[tech=htgs {phase}] [organism=Medicago truncatula] [strain=A17]"' acmd += ' -o {sqndir}/{accession_nv}.sqn -V Vbr' acmd += ' -y "{comment}" -W T -T T' nupdated = 0 for row in open ( phasefile ) : name , phase = row . split ( ) [ : 2 ] fafile = op . join ( fastadir , name + ".fa" ) cloneopt = "--clone={0}" . format ( name ) splitfile , gaps = sequin ( [ fafile , cloneopt ] ) splitfile = op . basename ( splitfile ) accession = accession_nv = name phase = int ( phase ) assert phase in ( 1 , 2 , 3 ) cmd = acmd . format ( accession_nv = accession_nv , sqndir = sqndir , sbtfile = sbtfile , splitfile = splitfile , phase = phase , comment = comment ) sh ( cmd ) verify_sqn ( sqndir , accession ) nupdated += 1 print ( "A total of {0} records updated." . format ( nupdated ) , file = sys . stderr ) | %prog htgnew fastafile phasefile template . sbt |
11,907 | def convert_96_to_384 ( c96 , quad , nrows = Nrows , ncols = Ncols ) : rows , cols = get_rows_cols ( ) plate , splate = get_plate ( ) n96 = rows . index ( c96 [ 0 ] ) * ncols / 2 + int ( c96 [ 1 : ] ) q = "{0:02d}{1}" . format ( n96 , "ABCD" [ quad - 1 ] ) return splate [ q ] | Convert the 96 - well number and quad number to 384 - well number |
11,908 | def parse_description ( s ) : s = "" . join ( s . split ( ) [ 1 : ] ) . replace ( "/" , ";" ) a = parse_qs ( s ) return a | Returns a dictionary based on the FASTA header assuming JCVI data |
11,909 | def scaffold ( args ) : from jcvi . formats . base import FileMerger from jcvi . formats . bed import mates from jcvi . formats . contig import frombed from jcvi . formats . fasta import join from jcvi . utils . iter import grouper p = OptionParser ( scaffold . __doc__ ) p . set_rclip ( rclip = 1 ) p . add_option ( "--conf" , help = "BAMBUS configuration file [default: %default]" ) p . add_option ( "--prefix" , default = False , action = "store_true" , help = "Only keep links between IDs with same prefix [default: %default]" ) opts , args = p . parse_args ( args ) nargs = len ( args ) if nargs < 3 or nargs % 2 != 1 : sys . exit ( not p . print_help ( ) ) rclip = opts . rclip ctgfasta = args [ 0 ] duos = list ( grouper ( args [ 1 : ] , 2 ) ) trios = [ ] for fastafile , bedfile in duos : prefix = bedfile . rsplit ( "." , 1 ) [ 0 ] matefile = prefix + ".mates" matebedfile = matefile + ".bed" if need_update ( bedfile , [ matefile , matebedfile ] ) : matesopt = [ bedfile , "--lib" , "--nointra" , "--rclip={0}" . format ( rclip ) , "--cutoff={0}" . format ( opts . cutoff ) ] if opts . prefix : matesopt += [ "--prefix" ] matefile , matebedfile = mates ( matesopt ) trios . append ( ( fastafile , matebedfile , matefile ) ) bbfasta , bbbed , bbmate = "bambus.reads.fasta" , "bambus.bed" , "bambus.mates" for files , outfile in zip ( zip ( * trios ) , ( bbfasta , bbbed , bbmate ) ) : FileMerger ( files , outfile = outfile ) . merge ( checkexists = True ) ctgfile = "bambus.contig" idsfile = "bambus.ids" frombedInputs = [ bbbed , ctgfasta , bbfasta ] if need_update ( frombedInputs , ctgfile ) : frombed ( frombedInputs ) inputfasta = "bambus.contigs.fasta" singletonfasta = "bambus.singletons.fasta" cmd = "faSomeRecords {0} {1} " . format ( ctgfasta , idsfile ) sh ( cmd + inputfasta ) sh ( cmd + singletonfasta + " -exclude" ) prefix = "bambus" cmd = "goBambus -c {0} -m {1} -o {2}" . format ( ctgfile , bbmate , prefix ) if opts . conf : cmd += " -C {0}" . format ( opts . conf ) sh ( cmd ) cmd = "untangle -e {0}.evidence.xml -s {0}.out.xml -o {0}.untangle.xml" . format ( prefix ) sh ( cmd ) final = "final" cmd = "printScaff -e {0}.evidence.xml -s {0}.untangle.xml -l {0}.lib " "-merge -detail -oo -sum -o {1}" . format ( prefix , final ) sh ( cmd ) oofile = final + ".oo" join ( [ inputfasta , "--oo={0}" . format ( oofile ) ] ) | %prog scaffold ctgfasta reads1 . fasta mapping1 . bed reads2 . fasta mapping2 . bed ... |
11,910 | def diginorm ( args ) : from jcvi . formats . fastq import shuffle , pairinplace , split from jcvi . apps . base import getfilesize p = OptionParser ( diginorm . __doc__ ) p . add_option ( "--single" , default = False , action = "store_true" , help = "Single end reads" ) p . add_option ( "--tablesize" , help = "Memory size" ) p . add_option ( "--npass" , default = "1" , choices = ( "1" , "2" ) , help = "How many passes of normalization" ) p . set_depth ( depth = 50 ) p . set_home ( "khmer" , default = "/usr/local/bin/" ) opts , args = p . parse_args ( args ) if len ( args ) not in ( 1 , 2 ) : sys . exit ( not p . print_help ( ) ) if len ( args ) == 2 : fastq = shuffle ( args + [ "--tag" ] ) else : fastq , = args kh = opts . khmer_home depth = opts . depth PE = not opts . single sys . path . insert ( 0 , op . join ( kh , "python" ) ) pf = fastq . rsplit ( "." , 1 ) [ 0 ] keepfile = fastq + ".keep" hashfile = pf + ".kh" mints = 10000000 ts = opts . tablesize or ( ( getfilesize ( fastq ) / 16 / mints + 1 ) * mints ) norm_cmd = op . join ( kh , "normalize-by-median.py" ) filt_cmd = op . join ( kh , "filter-abund.py" ) if need_update ( fastq , ( hashfile , keepfile ) ) : cmd = norm_cmd cmd += " -C {0} -k 20 -N 4 -x {1}" . format ( depth , ts ) if PE : cmd += " -p" cmd += " -s {0} {1}" . format ( hashfile , fastq ) sh ( cmd ) abundfiltfile = keepfile + ".abundfilt" if need_update ( ( hashfile , keepfile ) , abundfiltfile ) : cmd = filt_cmd cmd += " {0} {1}" . format ( hashfile , keepfile ) sh ( cmd ) if opts . npass == "1" : seckeepfile = abundfiltfile else : seckeepfile = abundfiltfile + ".keep" if need_update ( abundfiltfile , seckeepfile ) : cmd = norm_cmd cmd += " -C {0} -k 20 -N 4 -x {1}" . format ( depth - 10 , ts / 2 ) cmd += " {0}" . format ( abundfiltfile ) sh ( cmd ) if PE : pairsfile = pairinplace ( [ seckeepfile , "--base={0}" . format ( pf + "_norm" ) , "--rclip=2" ] ) split ( [ pairsfile ] ) | %prog diginorm fastqfile |
11,911 | def contamination ( args ) : from jcvi . apps . bowtie import BowtieLogFile , align p = OptionParser ( contamination . __doc__ ) p . set_firstN ( ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) ecoli , genome , fq = args firstN_opt = "--firstN={0}" . format ( opts . firstN ) samfile , logfile = align ( [ ecoli , fq , firstN_opt ] ) bl = BowtieLogFile ( logfile ) lowerbound = bl . rate samfile , logfile = align ( [ genome , fq , firstN_opt ] ) bl = BowtieLogFile ( logfile ) upperbound = 100 - bl . rate median = ( lowerbound + upperbound ) / 2 clogfile = fq + ".Ecoli" fw = open ( clogfile , "w" ) lowerbound = "{0:.1f}" . format ( lowerbound ) upperbound = "{0:.1f}" . format ( upperbound ) median = "{0:.1f}" . format ( median ) print ( "\t" . join ( ( fq , lowerbound , median , upperbound ) ) , file = fw ) print ( "{0}: Ecoli contamination rate {1}-{2}" . format ( fq , lowerbound , upperbound ) , file = sys . stderr ) fw . close ( ) | %prog contamination Ecoli . fasta genome . fasta read . fastq |
11,912 | def alignextend ( args ) : choices = "prepare,align,filter,rmdup,genreads" . split ( "," ) p = OptionParser ( alignextend . __doc__ ) p . add_option ( "--nosuffix" , default = False , action = "store_true" , help = "Do not add /1/2 suffix to the read [default: %default]" ) p . add_option ( "--rc" , default = False , action = "store_true" , help = "Reverse complement the reads before alignment" ) p . add_option ( "--len" , default = 100 , type = "int" , help = "Extend to this length" ) p . add_option ( "--stage" , default = "prepare" , choices = choices , help = "Start from certain stage" ) p . add_option ( "--dup" , default = 10 , type = "int" , help = "Filter duplicates with coordinates within this distance" ) p . add_option ( "--maxdiff" , default = 1 , type = "int" , help = "Maximum number of differences" ) p . set_home ( "amos" ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) ref , r1 , r2 = args pf = op . basename ( r1 ) . split ( "." ) [ 0 ] cmd = op . join ( opts . amos_home , "src/Experimental/alignextend.pl" ) if not opts . nosuffix : cmd += " -suffix" bwa_idx = "{0}.ref.fa.sa" . format ( pf ) if not need_update ( ref , bwa_idx ) : cmd += " -noindex" cmd += " -threads {0}" . format ( opts . cpus ) offset = guessoffset ( [ r1 ] ) if offset == 64 : cmd += " -I" if opts . rc : cmd += " -rc" cmd += " -allow -len {0} -dup {1}" . format ( opts . len , opts . dup ) cmd += " -min {0} -max {1}" . format ( 2 * opts . len , 20 * opts . len ) cmd += " -maxdiff {0}" . format ( opts . maxdiff ) cmd += " -stage {0}" . format ( opts . stage ) cmd += " " . join ( ( "" , pf , ref , r1 , r2 ) ) sh ( cmd ) | %prog alignextend ref . fasta read . 1 . fastq read . 2 . fastq |
11,913 | def hetsmooth ( args ) : p = OptionParser ( hetsmooth . __doc__ ) p . add_option ( "-K" , default = 23 , type = "int" , help = "K-mer size [default: %default]" ) p . add_option ( "-L" , type = "int" , help = "Bottom threshold, first min [default: %default]" ) p . add_option ( "-U" , type = "int" , help = "Top threshold, second min [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) reads1fq , reads2fq , jfdb = args K = opts . K L = opts . L U = opts . U assert L is not None and U is not None , "Please specify -L and -U" cmd = "het-smooth --kmer-len={0}" . format ( K ) cmd += " --bottom-threshold={0} --top-threshold={1}" . format ( L , U ) cmd += " --no-multibase-replacements --jellyfish-hash-file={0}" . format ( jfdb ) cmd += " --no-reads-log" cmd += " " + " " . join ( ( reads1fq , reads2fq ) ) sh ( cmd ) | %prog hetsmooth reads_1 . fq reads_2 . fq jf - 23_0 |
11,914 | def range_intersect ( a , b , extend = 0 ) : a_min , a_max = a if a_min > a_max : a_min , a_max = a_max , a_min b_min , b_max = b if b_min > b_max : b_min , b_max = b_max , b_min if a_max + extend < b_min or b_max + extend < a_min : return None i_min = max ( a_min , b_min ) i_max = min ( a_max , b_max ) if i_min > i_max + extend : return None return [ i_min , i_max ] | Returns the intersection between two reanges . |
11,915 | def range_overlap ( a , b , ratio = False ) : a_chr , a_min , a_max = a b_chr , b_min , b_max = b a_min , a_max = sorted ( ( a_min , a_max ) ) b_min , b_max = sorted ( ( b_min , b_max ) ) shorter = min ( ( a_max - a_min ) , ( b_max - b_min ) ) + 1 if a_chr != b_chr : ov = 0 else : ov = min ( shorter , ( a_max - b_min + 1 ) , ( b_max - a_min + 1 ) ) ov = max ( ov , 0 ) if ratio : ov /= float ( shorter ) return ov | Returns whether two ranges overlap . Set percentage = True returns overlap ratio over the shorter range of the two . |
11,916 | def range_distance ( a , b , distmode = 'ss' ) : assert distmode in ( 'ss' , 'ee' ) a_chr , a_min , a_max , a_strand = a b_chr , b_min , b_max , b_strand = b if a_chr != b_chr : dist = - 1 else : if a_min > b_min : a_min , b_min = b_min , a_min a_max , b_max = b_max , a_max a_strand , b_strand = b_strand , a_strand if distmode == "ss" : dist = b_max - a_min + 1 elif distmode == "ee" : dist = b_min - a_max - 1 orientation = a_strand + b_strand return dist , orientation | Returns the distance between two ranges . |
11,917 | def range_minmax ( ranges ) : rmin = min ( ranges ) [ 0 ] rmax = max ( ranges , key = lambda x : x [ 1 ] ) [ 1 ] return rmin , rmax | Returns the span of a collection of ranges where start is the smallest of all starts and end is the largest of all ends . |
11,918 | def range_interleave ( ranges , sizes = { } , empty = False ) : from jcvi . utils . iter import pairwise ranges = range_merge ( ranges ) interleaved_ranges = [ ] for ch , cranges in groupby ( ranges , key = lambda x : x [ 0 ] ) : cranges = list ( cranges ) size = sizes . get ( ch , None ) if size : ch , astart , aend = cranges [ 0 ] if astart > 1 : interleaved_ranges . append ( ( ch , 1 , astart - 1 ) ) elif empty : interleaved_ranges . append ( None ) for a , b in pairwise ( cranges ) : ch , astart , aend = a ch , bstart , bend = b istart , iend = aend + 1 , bstart - 1 if istart <= iend : interleaved_ranges . append ( ( ch , istart , iend ) ) elif empty : interleaved_ranges . append ( None ) if size : ch , astart , aend = cranges [ - 1 ] if aend < size : interleaved_ranges . append ( ( ch , aend + 1 , size ) ) elif empty : interleaved_ranges . append ( None ) return interleaved_ranges | Returns the ranges in between the given ranges . |
11,919 | def range_merge ( ranges , dist = 0 ) : if not ranges : return [ ] ranges . sort ( ) cur_range = list ( ranges [ 0 ] ) merged_ranges = [ ] for r in ranges [ 1 : ] : if r [ 1 ] - cur_range [ 2 ] > dist or r [ 0 ] != cur_range [ 0 ] : merged_ranges . append ( tuple ( cur_range ) ) cur_range = list ( r ) else : cur_range [ 2 ] = max ( cur_range [ 2 ] , r [ 2 ] ) merged_ranges . append ( tuple ( cur_range ) ) return merged_ranges | Returns merged range . Similar to range_union except this returns new ranges . |
11,920 | def range_span ( ranges ) : if not ranges : return 0 ranges . sort ( ) ans = 0 for seq , lt in groupby ( ranges , key = lambda x : x [ 0 ] ) : lt = list ( lt ) ans += max ( max ( lt ) [ 1 : ] ) - min ( min ( lt ) [ 1 : ] ) + 1 return ans | Returns the total span between the left most range to the right most range . |
11,921 | def range_piles ( ranges ) : endpoints = _make_endpoints ( ranges ) for seqid , ends in groupby ( endpoints , lambda x : x [ 0 ] ) : active = [ ] depth = 0 for seqid , pos , leftright , i , score in ends : if leftright == LEFT : active . append ( i ) depth += 1 else : depth -= 1 if depth == 0 and active : yield active active = [ ] | Return piles of intervals that overlap . The piles are only interrupted by regions of zero coverage . |
11,922 | def range_conflict ( ranges , depth = 1 ) : overlap = set ( ) active = set ( ) endpoints = _make_endpoints ( ranges ) for seqid , ends in groupby ( endpoints , lambda x : x [ 0 ] ) : active . clear ( ) for seqid , pos , leftright , i , score in ends : if leftright == LEFT : active . add ( i ) else : active . remove ( i ) if len ( active ) > depth : overlap . add ( tuple ( sorted ( active ) ) ) for ov in overlap : yield ov | Find intervals that are overlapping in 1 - dimension . Return groups of block IDs that are in conflict . |
11,923 | def loadtable ( header , rows , major = '=' , minor = '-' , thousands = True ) : formatted = load_csv ( header , rows , sep = " " , thousands = thousands ) header , rows = formatted [ 0 ] , formatted [ 1 : ] return banner ( header , rows ) | Print a tabular output with horizontal separators |
11,924 | def write_csv ( header , contents , sep = "," , filename = "stdout" , thousands = False , tee = False , align = True , comment = False ) : from jcvi . formats . base import must_open formatted = load_csv ( header , contents , sep = sep , thousands = thousands , align = align ) if comment : formatted [ 0 ] = '#' + formatted [ 0 ] [ 1 : ] formatted = "\n" . join ( formatted ) fw = must_open ( filename , "w" ) print ( formatted , file = fw ) if tee and filename != "stdout" : print ( formatted ) | Write csv that are aligned with the column headers . |
11,925 | def blat ( args ) : from jcvi . formats . base import is_number from jcvi . formats . blast import best as blast_best , bed as blast_bed from jcvi . apps . align import blat as blat_align p = OptionParser ( blat . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) maptxt , ref = args pf = maptxt . rsplit ( "." , 1 ) [ 0 ] register = { } fastafile = pf + ".fasta" fp = open ( maptxt ) fw = open ( fastafile , "w" ) for row in fp : name , lg , pos , seq = row . split ( ) if not is_number ( pos ) : continue register [ name ] = ( pf + '-' + lg , pos ) print ( ">{0}\n{1}\n" . format ( name , seq ) , file = fw ) fw . close ( ) blatfile = blat_align ( [ ref , fastafile ] ) bestfile = blast_best ( [ blatfile ] ) bedfile = blast_bed ( [ bestfile ] ) b = Bed ( bedfile ) . order pf = "." . join ( ( op . basename ( maptxt ) . split ( "." ) [ 0 ] , op . basename ( ref ) . split ( "." ) [ 0 ] ) ) csvfile = pf + ".csv" fp = open ( maptxt ) fw = open ( csvfile , "w" ) for row in fp : name , lg , pos , seq = row . split ( ) if name not in b : continue bbi , bb = b [ name ] scaffold , scaffold_pos = bb . seqid , bb . start print ( "," . join ( str ( x ) for x in ( scaffold , scaffold_pos , lg , pos ) ) , file = fw ) fw . close ( ) | %prog blat map1 . txt ref . fasta |
11,926 | def header ( args ) : from jcvi . formats . base import DictFile p = OptionParser ( header . __doc__ ) p . add_option ( "--prefix" , default = "" , help = "Prepend text to line number [default: %default]" ) p . add_option ( "--ids" , help = "Write ids to file [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) mstmap , conversion_table = args data = MSTMap ( mstmap ) hd = data . header conversion = DictFile ( conversion_table ) newhd = [ opts . prefix + conversion . get ( x , x ) for x in hd ] print ( "\t" . join ( hd ) ) print ( "- ) print ( "\t" . join ( newhd ) ) ids = opts . ids if ids : fw = open ( ids , "w" ) print ( "\n" . join ( newhd ) , file = fw ) fw . close ( ) | %prog header map conversion_table |
11,927 | def rename ( args ) : p = OptionParser ( rename . __doc__ ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) mstmap , bedfile = args markersbed = Bed ( bedfile ) markers = markersbed . order data = MSTMap ( mstmap ) header = data . header header = [ header [ 0 ] ] + [ "seqid" , "start" ] + header [ 1 : ] renamed = [ ] for b in data : m , geno = b . id , b . genotype om = m if m not in markers : m = m . rsplit ( "." , 1 ) [ 0 ] if m not in markers : continue i , mb = markers [ m ] renamed . append ( [ om , mb . seqid , mb . start , "\t" . join ( list ( geno ) ) ] ) renamed . sort ( key = lambda x : ( x [ 1 ] , x [ 2 ] ) ) fw = must_open ( opts . outfile , "w" ) print ( "\t" . join ( header ) , file = fw ) for d in renamed : print ( "\t" . join ( str ( x ) for x in d ) , file = fw ) | %prog rename map markers . bed > renamed . map |
11,928 | def anchor ( args ) : from jcvi . formats . blast import bed p = OptionParser ( anchor . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) mapbed , blastfile = args bedfile = bed ( [ blastfile ] ) markersbed = Bed ( bedfile ) markers = markersbed . order mapbed = Bed ( mapbed , sorted = False ) for b in mapbed : m = b . accn if m not in markers : continue i , mb = markers [ m ] new_accn = "{0}:{1}-{2}" . format ( mb . seqid , mb . start , mb . end ) b . accn = new_accn print ( b ) | %prog anchor map . bed markers . blast > anchored . bed |
11,929 | def bed ( args ) : p = OptionParser ( bed . __doc__ ) p . add_option ( "--switch" , default = False , action = "store_true" , help = "Switch reference and aligned map elements [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) mapout , = args pf = mapout . split ( "." ) [ 0 ] mapbed = pf + ".bed" bm = BinMap ( mapout ) bm . print_to_bed ( mapbed , switch = opts . switch ) return mapbed | %prog fasta map . out |
11,930 | def fasta ( args ) : from jcvi . formats . sizes import Sizes p = OptionParser ( fasta . __doc__ ) p . add_option ( "--extend" , default = 1000 , type = "int" , help = "Extend seq flanking the gaps [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) mapout , sfasta = args Flank = opts . extend pf = mapout . split ( "." ) [ 0 ] mapbed = pf + ".bed" bm = BinMap ( mapout ) bm . print_to_bed ( mapbed ) bed = Bed ( mapbed , sorted = False ) markersbed = pf + ".markers.bed" fw = open ( markersbed , "w" ) sizes = Sizes ( sfasta ) . mapping for b in bed : accn = b . accn scf , pos = accn . split ( "." ) pos = int ( pos ) start = max ( 0 , pos - Flank ) end = min ( pos + Flank , sizes [ scf ] ) print ( "\t" . join ( str ( x ) for x in ( scf , start , end , accn ) ) , file = fw ) fw . close ( ) fastaFromBed ( markersbed , sfasta , name = True ) | %prog fasta map . out scaffolds . fasta |
11,931 | def breakpoint ( args ) : from jcvi . utils . iter import pairwise p = OptionParser ( breakpoint . __doc__ ) p . add_option ( "--diff" , default = .1 , type = "float" , help = "Maximum ratio of differences allowed [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) mstmap , = args diff = opts . diff data = MSTMap ( mstmap ) good = [ ] nsingletons = 0 for i in xrange ( 1 , len ( data ) - 1 ) : a = data [ i ] left_label , left_rr = check_markers ( data [ i - 1 ] , a , diff ) right_label , right_rr = check_markers ( a , data [ i + 1 ] , diff ) if left_label == BREAK and right_label == BREAK : nsingletons += 1 continue good . append ( a ) logging . debug ( "A total of {0} singleton markers removed." . format ( nsingletons ) ) for a , b in pairwise ( good ) : label , rr = check_markers ( a , b , diff ) if label == BREAK : print ( "\t" . join ( str ( x ) for x in rr ) ) | %prog breakpoint mstmap . input > breakpoints . bed |
11,932 | def trimNs ( seq , line , newagp ) : start , end = line . component_beg , line . component_end size = end - start + 1 leftNs , rightNs = 0 , 0 lid , lo = line . component_id , line . orientation for s in seq : if s in 'nN' : leftNs += 1 else : break for s in seq [ : : - 1 ] : if s in 'nN' : rightNs += 1 else : break if lo == '-' : trimstart = start + rightNs trimend = end - leftNs else : trimstart = start + leftNs trimend = end - rightNs trimrange = ( trimstart , trimend ) oldrange = ( start , end ) if trimrange != oldrange : logging . debug ( "{0} trimmed of N's: {1} => {2}" . format ( lid , oldrange , trimrange ) ) if leftNs : print ( "\t" . join ( str ( x ) for x in ( line . object , 0 , 0 , 0 , 'N' , leftNs , "fragment" , "yes" , "" ) ) , file = newagp ) if trimend > trimstart : print ( "\t" . join ( str ( x ) for x in ( line . object , 0 , 0 , 0 , line . component_type , lid , trimstart , trimend , lo ) ) , file = newagp ) if rightNs and rightNs != size : print ( "\t" . join ( str ( x ) for x in ( line . object , 0 , 0 , 0 , 'N' , rightNs , "fragment" , "yes" , "" ) ) , file = newagp ) else : print ( line , file = newagp ) | Test if the sequences contain dangling N s on both sides . This component needs to be adjusted to the actual sequence range . |
11,933 | def fromcsv ( args ) : import csv from jcvi . formats . sizes import Sizes p = OptionParser ( fromcsv . __doc__ ) p . add_option ( "--evidence" , default = "map" , help = "Linkage evidence to add in AGP" ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) contigsfasta , mapcsv , mapagp = args reader = csv . reader ( open ( mapcsv ) ) sizes = Sizes ( contigsfasta ) . mapping next ( reader ) fwagp = must_open ( mapagp , "w" ) o = OO ( ) for row in reader : if len ( row ) == 2 : object , ctg = row strand = '?' elif len ( row ) == 3 : object , ctg , strand = row size = sizes [ ctg ] o . add ( object , ctg , size , strand ) o . write_AGP ( fwagp , gapsize = 100 , gaptype = "scaffold" , phases = { } , evidence = opts . evidence ) | %prog fromcsv contigs . fasta map . csv map . agp |
11,934 | def compress ( args ) : p = OptionParser ( compress . __doc__ ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) aagpfile , bagpfile = args store = { } agp = AGP ( aagpfile ) for a in agp : if a . is_gap : continue if a . sign == 0 : a . sign = 1 store [ ( a . object , a . object_beg , a . object_end ) ] = ( a . component_id , a . component_beg , a . component_end , a . sign ) agp = AGP ( bagpfile ) fw = must_open ( opts . outfile , "w" ) print ( "\n" . join ( agp . header ) , file = fw ) for a in agp : if a . is_gap : print ( a , file = fw ) continue component_id , component_beg , component_end , sign = store [ ( a . component_id , a . component_beg , a . component_end ) ] orientation = { 1 : '+' , - 1 : '-' , 0 : '?' } . get ( sign * a . sign ) atoms = ( a . object , a . object_beg , a . object_end , a . part_number , a . component_type , component_id , component_beg , component_end , orientation ) a = AGPLine ( "\t" . join ( str ( x ) for x in atoms ) ) print ( a , file = fw ) | %prog compress a . agp b . agp |
11,935 | def infer ( args ) : from jcvi . apps . grid import WriteJobs from jcvi . formats . bed import sort p = OptionParser ( infer . __doc__ ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) scaffoldsf , genomef = args inferbed = "infer-components.bed" if need_update ( ( scaffoldsf , genomef ) , inferbed ) : scaffolds = Fasta ( scaffoldsf , lazy = True ) genome = Fasta ( genomef ) genome = genome . tostring ( ) args = [ ( scaffold_name , scaffold , genome ) for scaffold_name , scaffold in scaffolds . iteritems_ordered ( ) ] pool = WriteJobs ( map_one_scaffold , args , inferbed , cpus = opts . cpus ) pool . run ( ) sort ( [ inferbed , "-i" ] ) bed = Bed ( inferbed ) inferagpbed = "infer.bed" fw = open ( inferagpbed , "w" ) seen = [ ] for b in bed : r = ( b . seqid , b . start , b . end ) if check_seen ( r , seen ) : continue print ( "\t" . join ( str ( x ) for x in ( b . accn , 0 , b . span , b . seqid , b . score , b . strand ) ) , file = fw ) seen . append ( r ) fw . close ( ) frombed ( [ inferagpbed ] ) | %prog infer scaffolds . fasta genome . fasta |
11,936 | def format ( args ) : from jcvi . formats . base import DictFile p = OptionParser ( format . __doc__ ) p . add_option ( "--switchcomponent" , help = "Switch component id based on" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) oldagpfile , newagpfile = args switchcomponent = opts . switchcomponent if switchcomponent : switchcomponent = DictFile ( switchcomponent ) agp = AGP ( oldagpfile ) fw = open ( newagpfile , "w" ) nconverts = 0 for i , a in enumerate ( agp ) : if not a . is_gap and a . component_id in switchcomponent : oldid = a . component_id newid = switchcomponent [ a . component_id ] a . component_id = newid logging . debug ( "Covert {0} to {1} on line {2}" . format ( oldid , newid , i + 1 ) ) nconverts += 1 print ( a , file = fw ) logging . debug ( "Total converted records: {0}" . format ( nconverts ) ) | %prog format oldagpfile newagpfile |
11,937 | def frombed ( args ) : p = OptionParser ( frombed . __doc__ ) p . add_option ( "--gapsize" , default = 100 , type = "int" , help = "Insert gaps of size [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) bedfile , = args gapsize = opts . gapsize agpfile = bedfile . replace ( ".bed" , ".agp" ) fw = open ( agpfile , "w" ) bed = Bed ( bedfile , sorted = False ) for object , beds in groupby ( bed , key = lambda x : x . accn ) : beds = list ( beds ) for i , b in enumerate ( beds ) : if gapsize and i != 0 : print ( "\t" . join ( str ( x ) for x in ( object , 0 , 0 , 0 , "U" , gapsize , "scaffold" , "yes" , "map" ) ) , file = fw ) print ( "\t" . join ( str ( x ) for x in ( object , 0 , 0 , 0 , "W" , b . seqid , b . start , b . end , b . strand ) ) , file = fw ) fw . close ( ) return reindex ( [ agpfile , "--inplace" ] ) | %prog frombed bedfile |
11,938 | def swap ( args ) : from jcvi . utils . range import range_interleave p = OptionParser ( swap . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) agpfile , = args agp = AGP ( agpfile , nogaps = True , validate = False ) agp . sort ( key = lambda x : ( x . component_id , x . component_beg ) ) newagpfile = agpfile . rsplit ( "." , 1 ) [ 0 ] + ".swapped.agp" fw = open ( newagpfile , "w" ) agp . transfer_header ( fw ) for cid , aa in groupby ( agp , key = ( lambda x : x . component_id ) ) : aa = list ( aa ) aranges = [ ( x . component_id , x . component_beg , x . component_end ) for x in aa ] gaps = range_interleave ( aranges ) for a , g in zip_longest ( aa , gaps ) : a . object , a . component_id = a . component_id , a . object a . component_beg = a . object_beg a . component_end = a . object_end print ( a , file = fw ) if not g : continue aline = [ cid , 0 , 0 , 0 ] gseq , ga , gb = g cspan = gb - ga + 1 aline += [ "N" , cspan , "fragment" , "yes" ] print ( "\t" . join ( str ( x ) for x in aline ) , file = fw ) fw . close ( ) idxagpfile = reindex ( [ newagpfile , "--inplace" ] ) return newagpfile | %prog swap agpfile |
11,939 | def stats ( args ) : from jcvi . utils . table import tabulate p = OptionParser ( stats . __doc__ ) p . add_option ( "--warn" , default = False , action = "store_true" , help = "Warnings on small component spans [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( p . print_help ( ) ) agpfile , = args agp = AGP ( agpfile ) gap_lengths = [ ] component_lengths = [ ] for a in agp : span = a . object_span if a . is_gap : label = a . gap_type gap_lengths . append ( ( span , label ) ) else : label = "{0}:{1}-{2}" . format ( a . component_id , a . component_beg , a . component_end ) component_lengths . append ( ( span , label ) ) if opts . warn and span < 50 : logging . error ( "component span too small ({0}):\n{1}" . format ( span , a ) ) table = dict ( ) for label , lengths in zip ( ( "Gaps" , "Components" ) , ( gap_lengths , component_lengths ) ) : if not lengths : table [ ( label , "Min" ) ] = table [ ( label , "Max" ) ] = table [ ( label , "Sum" ) ] = "n.a." continue table [ ( label , "Min" ) ] = "{0} ({1})" . format ( * min ( lengths ) ) table [ ( label , "Max" ) ] = "{0} ({1})" . format ( * max ( lengths ) ) table [ ( label , "Sum" ) ] = sum ( x [ 0 ] for x in lengths ) print ( tabulate ( table ) , file = sys . stderr ) | %prog stats agpfile |
11,940 | def cut ( args ) : p = OptionParser ( cut . __doc__ ) p . add_option ( "--sep" , default = "." , help = "Separator for splits" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) agpfile , bedfile = args sep = opts . sep agp = AGP ( agpfile ) bed = Bed ( bedfile ) simple_agp = agp . order newagpfile = agpfile . replace ( ".agp" , ".cut.agp" ) fw = open ( newagpfile , "w" ) agp_fixes = defaultdict ( list ) for component , intervals in bed . sub_beds ( ) : i , a = simple_agp [ component ] object = a . object component_span = a . component_span orientation = a . orientation assert a . component_beg , a . component_end cuts = set ( ) for i in intervals : start , end = i . start , i . end end -= 1 assert start <= end cuts . add ( start ) cuts . add ( end ) cuts . add ( 0 ) cuts . add ( component_span ) cuts = list ( sorted ( cuts ) ) sum_of_spans = 0 for i , ( a , b ) in enumerate ( pairwise ( cuts ) ) : oid = object + "{0}{1}" . format ( sep , i + 1 ) aline = [ oid , 0 , 0 , 0 ] cspan = b - a aline += [ 'D' , component , a + 1 , b , orientation ] sum_of_spans += cspan aline = "\t" . join ( str ( x ) for x in aline ) agp_fixes [ component ] . append ( aline ) assert component_span == sum_of_spans for a in agp : if not a . is_gap and a . component_id in agp_fixes : print ( "\n" . join ( agp_fixes [ a . component_id ] ) , file = fw ) else : print ( a , file = fw ) fw . close ( ) reindex ( [ newagpfile , "--inplace" ] ) return newagpfile | %prog cut agpfile bedfile |
11,941 | def summary ( args ) : from jcvi . utils . table import write_csv p = OptionParser ( summary . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( p . print_help ( ) ) agpfile , = args header = "Chromosome #_Distinct #_Components #_Scaffolds " "Scaff_N50 Scaff_L50 Length" . split ( ) agp = AGP ( agpfile ) data = list ( agp . summary_all ( ) ) write_csv ( header , data , sep = " " ) | %prog summary agpfile |
11,942 | def phase ( args ) : p = OptionParser ( phase . __doc__ ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) < 1 : sys . exit ( not p . print_help ( ) ) fw = must_open ( opts . outfile , "w" ) for gbfile in args : for rec in SeqIO . parse ( gbfile , "gb" ) : bac_phase , keywords = get_phase ( rec ) chr , clone = get_clone ( rec ) keyword_field = ";" . join ( keywords ) print ( "\t" . join ( ( rec . id , str ( bac_phase ) , keyword_field , chr , clone ) ) , file = fw ) | %prog phase genbankfiles |
11,943 | def tpf ( args ) : p = OptionParser ( tpf . __doc__ ) p . add_option ( "--noversion" , default = False , action = "store_true" , help = "Remove trailing accession versions [default: %default]" ) p . add_option ( "--gaps" , default = False , action = "store_true" , help = "Include gaps in the output [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) agpfile , = args agp = AGP ( agpfile ) for a in agp : object = a . object if a . is_gap : if opts . gaps and a . isCloneGap : print ( "\t" . join ( ( a . gap_type , object , "na" ) ) ) continue component_id = a . component_id orientation = a . orientation if opts . noversion : component_id = component_id . rsplit ( "." , 1 ) [ 0 ] print ( "\t" . join ( ( component_id , object , orientation ) ) ) | %prog tpf agpfile |
11,944 | def bed ( args ) : from jcvi . formats . obo import validate_term p = OptionParser ( bed . __doc__ ) p . add_option ( "--gaps" , default = False , action = "store_true" , help = "Only print bed lines for gaps [default: %default]" ) p . add_option ( "--nogaps" , default = False , action = "store_true" , help = "Do not print bed lines for gaps [default: %default]" ) p . add_option ( "--bed12" , default = False , action = "store_true" , help = "Produce bed12 formatted output [default: %default]" ) p . add_option ( "--component" , default = False , action = "store_true" , help = "Generate bed file for components [default: %default]" ) p . set_outfile ( ) g1 = OptionGroup ( p , "GFF specific parameters" , "Note: If not specified, output will be in `bed` format" ) g1 . add_option ( "--gff" , default = False , action = "store_true" , help = "Produce gff3 formatted output. By default, ignores " + "AGP gap lines. [default: %default]" ) g1 . add_option ( "--source" , default = "MGSC" , help = "Specify a gff3 source [default: `%default`]" ) g1 . add_option ( "--feature" , default = "golden_path_fragment" , help = "Specify a gff3 feature type [default: `%default`]" ) p . add_option_group ( g1 ) p . set_SO_opts ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) if opts . component : opts . nogaps = True if opts . gff and opts . verifySO : validate_term ( opts . feature , method = opts . verifySO ) agpfile , = args agp = AGP ( agpfile ) fw = must_open ( opts . outfile , "w" ) if opts . gff : print ( "##gff-version 3" , file = fw ) for a in agp : if opts . nogaps and a . is_gap : continue if opts . gaps and not a . is_gap : continue if opts . bed12 : print ( a . bed12line , file = fw ) elif opts . gff : print ( a . gffline ( gff_source = opts . source , gff_feat_type = opts . feature ) , file = fw ) elif opts . component : name = "{0}:{1}-{2}" . format ( a . component_id , a . component_beg , a . component_end ) print ( "\t" . join ( str ( x ) for x in ( a . component_id , a . component_beg - 1 , a . component_end , name , a . component_type , a . orientation ) ) , file = fw ) else : print ( a . bedline , file = fw ) fw . close ( ) return fw . name | %prog bed agpfile |
11,945 | def extendbed ( args ) : from jcvi . formats . sizes import Sizes p = OptionParser ( extendbed . __doc__ ) p . add_option ( "--nogaps" , default = False , action = "store_true" , help = "Do not print bed lines for gaps [default: %default]" ) p . add_option ( "--bed12" , default = False , action = "store_true" , help = "Produce bed12 formatted output [default: %default]" ) p . add_option ( "--gff" , default = False , action = "store_true" , help = "Produce gff3 formatted output. By default, ignores " + " AGP gap lines. [default: %default]" ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) if opts . gff : opts . nogaps = True agpfile , fastafile = args agp = AGP ( agpfile ) fw = must_open ( opts . outfile , "w" ) if opts . gff : print ( "##gff-version 3" , file = fw ) ranges = defaultdict ( list ) thickCoords = [ ] for a in agp : thickCoords . append ( ( a . object_beg , a . object_end ) ) if a . is_gap : continue ranges [ a . component_id ] . append ( a ) sizes = Sizes ( fastafile ) . mapping for accn , rr in ranges . items ( ) : alen = sizes [ accn ] a = rr [ 0 ] if a . orientation == "+" : hang = a . component_beg - 1 else : hang = alen - a . component_end a . object_beg -= hang a = rr [ - 1 ] if a . orientation == "+" : hang = alen - a . component_end else : hang = a . component_beg - 1 a . object_end += hang for a , ( ts , te ) in zip ( agp , thickCoords ) : if opts . nogaps and a . is_gap : continue if opts . bed12 : line = a . bedline a . object_beg , a . object_end = ts , te line += "\t" + a . bedextra print ( line , file = fw ) elif opts . gff : print ( a . gffline ( ) , file = fw ) else : print ( a . bedline , file = fw ) | %prog extend agpfile componentfasta |
11,946 | def gaps ( args ) : from jcvi . graphics . histogram import loghistogram p = OptionParser ( gaps . __doc__ ) p . add_option ( "--merge" , dest = "merge" , default = False , action = "store_true" , help = "Merge adjacent gaps (to conform to AGP specification)" ) p . add_option ( "--header" , default = False , action = "store_true" , help = "Produce an AGP header [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) merge = opts . merge agpfile , = args if merge : merged_agpfile = agpfile . replace ( ".agp" , ".merged.agp" ) fw = open ( merged_agpfile , "w" ) agp = AGP ( agpfile ) sizes = [ ] data = [ ] priorities = ( "centromere" , "telomere" , "scaffold" , "contig" , "clone" , "fragment" ) for is_gap , alines in groupby ( agp , key = lambda x : ( x . object , x . is_gap ) ) : alines = list ( alines ) is_gap = is_gap [ 1 ] if is_gap : gap_size = sum ( x . gap_length for x in alines ) gap_types = set ( x . gap_type for x in alines ) for gtype in ( "centromere" , "telomere" ) : if gtype in gap_types : gap_size = gtype sizes . append ( gap_size ) b = deepcopy ( alines [ 0 ] ) b . object_beg = min ( x . object_beg for x in alines ) b . object_end = max ( x . object_end for x in alines ) b . gap_length = sum ( x . gap_length for x in alines ) assert b . gap_length == b . object_end - b . object_beg + 1 b . component_type = 'U' if b . gap_length == 100 else 'N' gtypes = [ x . gap_type for x in alines ] for gtype in priorities : if gtype in gtypes : b . gap_type = gtype break linkages = [ x . linkage for x in alines ] for linkage in ( "no" , "yes" ) : if linkage in linkages : b . linkage = linkage break alines = [ b ] data . extend ( alines ) loghistogram ( sizes ) if opts . header : AGP . print_header ( fw , organism = "Medicago truncatula" , taxid = 3880 , source = "J. Craig Venter Institute" ) if merge : for ob , bb in groupby ( data , lambda x : x . object ) : for i , b in enumerate ( bb ) : b . part_number = i + 1 print ( b , file = fw ) return merged_agpfile | %prog gaps agpfile |
11,947 | def tidy ( args ) : p = OptionParser ( tidy . __doc__ ) p . add_option ( "--nogaps" , default = False , action = "store_true" , help = "Remove all gap lines [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( p . print_help ( ) ) agpfile , componentfasta = args originalagpfile = agpfile tmpfasta = "tmp.fasta" trimmed_agpfile = build ( [ agpfile , componentfasta , tmpfasta , "--newagp" , "--novalidate" ] ) os . remove ( tmpfasta ) agpfile = trimmed_agpfile agpfile = reindex ( [ agpfile , "--inplace" ] ) merged_agpfile = gaps ( [ agpfile , "--merge" ] ) os . remove ( agpfile ) agpfile = merged_agpfile agp = AGP ( agpfile ) newagpfile = agpfile . replace ( ".agp" , ".fixed.agp" ) fw = open ( newagpfile , "w" ) for object , a in groupby ( agp , key = lambda x : x . object ) : a = list ( a ) if a [ 0 ] . is_gap : g , a = a [ 0 ] , a [ 1 : ] logging . debug ( "Trim beginning Ns({0}) of {1}" . format ( g . gap_length , object ) ) if a and a [ - 1 ] . is_gap : a , g = a [ : - 1 ] , a [ - 1 ] logging . debug ( "Trim trailing Ns({0}) of {1}" . format ( g . gap_length , object ) ) print ( "\n" . join ( str ( x ) for x in a ) , file = fw ) fw . close ( ) os . remove ( agpfile ) agpfile = newagpfile reindex_opts = [ agpfile , "--inplace" ] if opts . nogaps : reindex_opts += [ "--nogaps" ] agpfile = reindex ( reindex_opts ) tidyagpfile = originalagpfile . replace ( ".agp" , ".tidy.agp" ) shutil . move ( agpfile , tidyagpfile ) logging . debug ( "File written to `{0}`." . format ( tidyagpfile ) ) return tidyagpfile | %prog tidy agpfile componentfasta |
11,948 | def build ( args ) : p = OptionParser ( build . __doc__ ) p . add_option ( "--newagp" , dest = "newagp" , default = False , action = "store_true" , help = "Check components to trim dangling N's [default: %default]" ) p . add_option ( "--novalidate" , dest = "novalidate" , default = False , action = "store_true" , help = "Don't validate the agpfile [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) agpfile , componentfasta , targetfasta = args validate = not opts . novalidate if opts . newagp : assert agpfile . endswith ( ".agp" ) newagpfile = agpfile . replace ( ".agp" , ".trimmed.agp" ) newagp = open ( newagpfile , "w" ) else : newagpfile = None newagp = None agp = AGP ( agpfile , validate = validate , sorted = True ) agp . build_all ( componentfasta = componentfasta , targetfasta = targetfasta , newagp = newagp ) logging . debug ( "Target fasta written to `{0}`." . format ( targetfasta ) ) return newagpfile | %prog build agpfile componentfasta targetfasta |
11,949 | def validate ( args ) : p = OptionParser ( validate . __doc__ ) opts , args = p . parse_args ( args ) try : agpfile , componentfasta , targetfasta = args except Exception as e : sys . exit ( p . print_help ( ) ) agp = AGP ( agpfile ) build = Fasta ( targetfasta ) bacs = Fasta ( componentfasta , index = False ) for aline in agp : try : build_seq = build . sequence ( dict ( chr = aline . object , start = aline . object_beg , stop = aline . object_end ) ) if aline . is_gap : assert build_seq . upper ( ) == aline . gap_length * 'N' , "gap mismatch: %s" % aline else : bac_seq = bacs . sequence ( dict ( chr = aline . component_id , start = aline . component_beg , stop = aline . component_end , strand = aline . orientation ) ) assert build_seq . upper ( ) == bac_seq . upper ( ) , "sequence mismatch: %s" % aline logging . debug ( "%s:%d-%d verified" % ( aline . object , aline . object_beg , aline . object_end ) ) except Exception as e : logging . error ( e ) | %prog validate agpfile componentfasta targetfasta |
11,950 | def getNorthSouthClone ( self , i ) : north = self . getAdjacentClone ( i , south = False ) south = self . getAdjacentClone ( i ) return north , south | Returns the adjacent clone name from both sides . |
11,951 | def build_one ( self , object , lines , fasta , fw , newagp = None ) : components = [ ] total_bp = 0 for line in lines : if line . is_gap : seq = 'N' * line . gap_length if newagp : print ( line , file = newagp ) else : seq = fasta . sequence ( dict ( chr = line . component_id , start = line . component_beg , stop = line . component_end , strand = line . orientation ) ) if newagp : trimNs ( seq , line , newagp ) components . append ( seq ) total_bp += len ( seq ) if self . validate : assert total_bp == line . object_end , "cumulative base pairs (%d) does not match (%d)" % ( total_bp , line . object_end ) if not newagp : rec = SeqRecord ( Seq ( '' . join ( components ) ) , id = object , description = "" ) SeqIO . write ( [ rec ] , fw , "fasta" ) if len ( rec ) > 1000000 : logging . debug ( "Write object %s to `%s`" % ( object , fw . name ) ) | Construct molecule using component fasta sequence |
11,952 | def getAdjacentClone ( self , i , south = True ) : rr = xrange ( i + 1 , len ( self ) ) if south else xrange ( i - 1 , - 1 , - 1 ) a = self [ i ] for ix in rr : x = self [ ix ] if x . object != a . object : break return x return None | Returns adjacent clone name either the line before or after the current line . |
11,953 | def genemark ( args ) : p = OptionParser ( genemark . __doc__ ) p . add_option ( "--junctions" , help = "Path to `junctions.bed` from Tophat2" ) p . set_home ( "gmes" ) p . set_cpus ( cpus = 32 ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) species , fastafile = args junctions = opts . junctions mhome = opts . gmes_home license = op . expanduser ( "~/.gm_key" ) assert op . exists ( license ) , "License key ({0}) not found!" . format ( license ) cmd = "{0}/gmes_petap.pl --sequence {1}" . format ( mhome , fastafile ) cmd += " --cores {0}" . format ( opts . cpus ) if junctions : intronsgff = "introns.gff" if need_update ( junctions , intronsgff ) : jcmd = "{0}/bet_to_gff.pl" . format ( mhome ) jcmd += " --bed {0} --gff {1} --label Tophat2" . format ( junctions , intronsgff ) sh ( jcmd ) cmd += " --ET {0} --et_score 10" . format ( intronsgff ) else : cmd += " --ES" sh ( cmd ) logging . debug ( "GENEMARK matrix written to `output/gmhmm.mod" ) | %prog genemark species fastafile |
11,954 | def snap ( args ) : p = OptionParser ( snap . __doc__ ) p . set_home ( "maker" ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) species , gffile , fastafile = args mhome = opts . maker_home snapdir = "snap" mkdir ( snapdir ) cwd = os . getcwd ( ) os . chdir ( snapdir ) newgffile = "training.gff3" logging . debug ( "Construct GFF file combined with sequence ..." ) sh ( "cat ../{0} > {1}" . format ( gffile , newgffile ) ) sh ( 'echo "##FASTA" >> {0}' . format ( newgffile ) ) sh ( "cat ../{0} >> {1}" . format ( fastafile , newgffile ) ) logging . debug ( "Make models ..." ) sh ( "{0}/src/bin/maker2zff training.gff3" . format ( mhome ) ) sh ( "{0}/exe/snap/fathom -categorize 1000 genome.ann genome.dna" . format ( mhome ) ) sh ( "{0}/exe/snap/fathom -export 1000 -plus uni.ann uni.dna" . format ( mhome ) ) sh ( "{0}/exe/snap/forge export.ann export.dna" . format ( mhome ) ) sh ( "{0}/exe/snap/hmm-assembler.pl {1} . > {1}.hmm" . format ( mhome , species ) ) os . chdir ( cwd ) logging . debug ( "SNAP matrix written to `{0}/{1}.hmm`" . format ( snapdir , species ) ) | %prog snap species gffile fastafile |
11,955 | def augustus ( args ) : p = OptionParser ( augustus . __doc__ ) p . add_option ( "--autotrain" , default = False , action = "store_true" , help = "Run autoAugTrain.pl to iteratively train AUGUSTUS" ) p . set_home ( "augustus" ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) species , gffile , fastafile = args mhome = opts . augustus_home augdir = "augustus" cwd = os . getcwd ( ) mkdir ( augdir ) os . chdir ( augdir ) target = "{0}/config/species/{1}" . format ( mhome , species ) if op . exists ( target ) : logging . debug ( "Removing existing target `{0}`" . format ( target ) ) sh ( "rm -rf {0}" . format ( target ) ) sh ( "{0}/scripts/new_species.pl --species={1}" . format ( mhome , species ) ) sh ( "{0}/scripts/gff2gbSmallDNA.pl ../{1} ../{2} 1000 raw.gb" . format ( mhome , gffile , fastafile ) ) sh ( "{0}/bin/etraining --species={1} raw.gb 2> train.err" . format ( mhome , species ) ) sh ( "cat train.err | perl -pe 's/.*in sequence (\S+): .*/$1/' > badgenes.lst" ) sh ( "{0}/scripts/filterGenes.pl badgenes.lst raw.gb > training.gb" . format ( mhome ) ) sh ( "grep -c LOCUS raw.gb training.gb" ) if opts . autotrain : sh ( "rm -rf {0}" . format ( target ) ) sh ( "{0}/scripts/autoAugTrain.pl --trainingset=training.gb --species={1}" . format ( mhome , species ) ) os . chdir ( cwd ) sh ( "cp -r {0} augustus/" . format ( target ) ) | %prog augustus species gffile fastafile |
11,956 | def merger ( args ) : p = OptionParser ( merger . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) layout , gkpstore , contigs = args fp = open ( layout ) pf = "0" iidfile = pf + ".iids" for i , row in enumerate ( fp ) : logging . debug ( "Read unitig {0}" . format ( i ) ) fw = open ( iidfile , "w" ) layout = row . split ( "|" ) print ( "\n" . join ( layout ) , file = fw ) fw . close ( ) cmd = "gatekeeper -iid {0}.iids -dumpfasta {0} {1}" . format ( pf , gkpstore ) sh ( cmd ) fastafile = "{0}.fasta" . format ( pf ) newfastafile = "{0}.new.fasta" . format ( pf ) format ( [ fastafile , newfastafile , "--sequential=replace" , "--sequentialoffset=1" , "--nodesc" ] ) fasta ( [ newfastafile ] ) sh ( "rm -rf {0}" . format ( pf ) ) cmd = "runCA {0}.frg -p {0} -d {0} consensus=pbutgcns" . format ( pf ) cmd += " unitigger=bogart doFragmentCorrection=0 doUnitigSplitting=0" sh ( cmd ) outdir = "{0}/9-terminator" . format ( pf ) cmd = "cat {0}/{1}.ctg.fasta {0}/{1}.deg.fasta {0}/{1}.singleton.fasta" . format ( outdir , pf ) sh ( cmd , outfile = contigs , append = True ) | %prog merger layout gkpStore contigs . fasta |
11,957 | def unitigs ( args ) : p = OptionParser ( unitigs . __doc__ ) p . add_option ( "--maxerr" , default = 2 , type = "int" , help = "Maximum error rate" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) bestedges , = args G = read_graph ( bestedges , maxerr = opts . maxerr , directed = True ) H = nx . Graph ( ) intconv = lambda x : int ( x . split ( "-" ) [ 0 ] ) for k , v in G . iteritems ( ) : if k == G . get ( v , None ) : H . add_edge ( intconv ( k ) , intconv ( v ) ) nunitigs = nreads = 0 for h in nx . connected_component_subgraphs ( H , copy = False ) : st = [ x for x in h if h . degree ( x ) == 1 ] if len ( st ) != 2 : continue src , target = st path = list ( nx . all_simple_paths ( h , src , target ) ) assert len ( path ) == 1 path , = path print ( "|" . join ( str ( x ) for x in path ) ) nunitigs += 1 nreads += len ( path ) logging . debug ( "A total of {0} unitigs built from {1} reads." . format ( nunitigs , nreads ) ) | %prog unitigs best . edges |
11,958 | def astat ( args ) : p = OptionParser ( astat . __doc__ ) p . add_option ( "--cutoff" , default = 1000 , type = "int" , help = "Length cutoff [default: %default]" ) p . add_option ( "--genome" , default = "" , help = "Genome name [default: %default]" ) p . add_option ( "--arrDist" , default = False , action = "store_true" , help = "Use arrDist instead [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) covfile , = args cutoff = opts . cutoff genome = opts . genome plot_arrDist = opts . arrDist suffix = ".{0}" . format ( cutoff ) small_covfile = covfile + suffix update_covfile = need_update ( covfile , small_covfile ) if update_covfile : fw = open ( small_covfile , "w" ) else : logging . debug ( "Found `{0}`, will use this one" . format ( small_covfile ) ) covfile = small_covfile fp = open ( covfile ) header = next ( fp ) if update_covfile : fw . write ( header ) data = [ ] msg = "{0} tigs scanned ..." for row in fp : tigID , rho , covStat , arrDist = row . split ( ) tigID = int ( tigID ) if tigID % 1000000 == 0 : sys . stderr . write ( msg . format ( tigID ) + "\r" ) rho , covStat , arrDist = [ float ( x ) for x in ( rho , covStat , arrDist ) ] if rho < cutoff : continue if update_covfile : fw . write ( row ) data . append ( ( tigID , rho , covStat , arrDist ) ) print ( msg . format ( tigID ) , file = sys . stderr ) from jcvi . graphics . base import plt , savefig logging . debug ( "Plotting {0} data points." . format ( len ( data ) ) ) tigID , rho , covStat , arrDist = zip ( * data ) y = arrDist if plot_arrDist else covStat ytag = "arrDist" if plot_arrDist else "covStat" fig = plt . figure ( 1 , ( 7 , 7 ) ) ax = fig . add_axes ( [ .12 , .1 , .8 , .8 ] ) ax . plot ( rho , y , "." , color = "lightslategrey" ) xtag = "rho" info = ( genome , xtag , ytag ) title = "{0} {1} vs. {2}" . format ( * info ) ax . set_title ( title ) ax . set_xlabel ( xtag ) ax . set_ylabel ( ytag ) if plot_arrDist : ax . set_yscale ( 'log' ) imagename = "{0}.png" . format ( "." . join ( info ) ) savefig ( imagename , dpi = 150 ) | %prog astat coverage . log |
11,959 | def emitFragment ( fw , fragID , libID , shredded_seq , clr = None , qvchar = 'l' , fasta = False ) : if fasta : s = SeqRecord ( shredded_seq , id = fragID , description = "" ) SeqIO . write ( [ s ] , fw , "fasta" ) return seq = str ( shredded_seq ) slen = len ( seq ) qvs = qvchar * slen if clr is None : clr_beg , clr_end = 0 , slen else : clr_beg , clr_end = clr print ( frgTemplate . format ( fragID = fragID , libID = libID , seq = seq , qvs = qvs , clr_beg = clr_beg , clr_end = clr_end ) , file = fw ) | Print out the shredded sequence . |
11,960 | def make_matepairs ( fastafile ) : assert op . exists ( fastafile ) matefile = fastafile . rsplit ( "." , 1 ) [ 0 ] + ".mates" if op . exists ( matefile ) : logging . debug ( "matepairs file `{0}` found" . format ( matefile ) ) else : logging . debug ( "parsing matepairs from `{0}`" . format ( fastafile ) ) matefw = open ( matefile , "w" ) it = SeqIO . parse ( fastafile , "fasta" ) for fwd , rev in zip ( it , it ) : print ( "{0}\t{1}" . format ( fwd . id , rev . id ) , file = matefw ) matefw . close ( ) return matefile | Assumes the mates are adjacent sequence records |
11,961 | def sff ( args ) : p = OptionParser ( sff . __doc__ ) p . add_option ( "--prefix" , dest = "prefix" , default = None , help = "Output frg filename prefix" ) p . add_option ( "--nodedup" , default = False , action = "store_true" , help = "Do not remove duplicates [default: %default]" ) p . set_size ( ) opts , args = p . parse_args ( args ) if len ( args ) < 1 : sys . exit ( p . print_help ( ) ) sffiles = args plates = [ x . split ( "." ) [ 0 ] . split ( "_" ) [ - 1 ] for x in sffiles ] mated = ( opts . size != 0 ) mean , sv = get_mean_sv ( opts . size ) if len ( plates ) > 1 : plate = plates [ 0 ] [ : - 1 ] + 'X' else : plate = "_" . join ( plates ) if mated : libname = "Titan{0}Kb-" . format ( opts . size / 1000 ) + plate else : libname = "TitanFrags-" + plate if opts . prefix : libname = opts . prefix cmd = "sffToCA" cmd += " -libraryname {0} -output {0} " . format ( libname ) cmd += " -clear 454 -trim chop " if mated : cmd += " -linker titanium -insertsize {0} {1} " . format ( mean , sv ) if opts . nodedup : cmd += " -nodedup " cmd += " " . join ( sffiles ) sh ( cmd ) | %prog sff sffiles |
11,962 | def fastq ( args ) : from jcvi . formats . fastq import guessoffset p = OptionParser ( fastq . __doc__ ) p . add_option ( "--outtie" , dest = "outtie" , default = False , action = "store_true" , help = "Are these outie reads? [default: %default]" ) p . set_phred ( ) p . set_size ( ) opts , args = p . parse_args ( args ) if len ( args ) < 1 : sys . exit ( p . print_help ( ) ) fastqfiles = [ get_abs_path ( x ) for x in args ] size = opts . size outtie = opts . outtie if size > 1000 and ( not outtie ) : logging . debug ( "[warn] long insert size {0} but not outtie" . format ( size ) ) mated = ( size != 0 ) libname = op . basename ( args [ 0 ] ) . split ( "." ) [ 0 ] libname = libname . replace ( "_1_sequence" , "" ) frgfile = libname + ".frg" mean , sv = get_mean_sv ( opts . size ) cmd = "fastqToCA" cmd += " -libraryname {0} " . format ( libname ) fastqs = " " . join ( "-reads {0}" . format ( x ) for x in fastqfiles ) if mated : assert len ( args ) in ( 1 , 2 ) , "you need one or two fastq files for mated library" fastqs = "-mates {0}" . format ( "," . join ( fastqfiles ) ) cmd += "-insertsize {0} {1} " . format ( mean , sv ) cmd += fastqs offset = int ( opts . phred ) if opts . phred else guessoffset ( [ fastqfiles [ 0 ] ] ) illumina = ( offset == 64 ) if illumina : cmd += " -type illumina" if outtie : cmd += " -outtie" sh ( cmd , outfile = frgfile ) | %prog fastq fastqfile |
11,963 | def clr ( args ) : p = OptionParser ( clr . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) < 2 : sys . exit ( not p . print_help ( ) ) blastfile = args [ 0 ] fastafiles = args [ 1 : ] sizes = { } for fa in fastafiles : f = Fasta ( fa ) sizes . update ( f . itersizes ( ) ) b = Blast ( blastfile ) for query , hits in b . iter_hits ( ) : qsize = sizes [ query ] vectors = list ( ( x . qstart , x . qstop ) for x in hits ) vmin , vmax = range_minmax ( vectors ) left_size = vmin - 1 right_size = qsize - vmax if left_size > right_size : clr_start , clr_end = 0 , vmin else : clr_start , clr_end = vmax , qsize print ( "\t" . join ( str ( x ) for x in ( query , clr_start , clr_end ) ) ) del sizes [ query ] for q , size in sorted ( sizes . items ( ) ) : print ( "\t" . join ( str ( x ) for x in ( q , 0 , size ) ) ) | %prog blastfile fastafiles |
11,964 | def truncate_name ( name , rule = None ) : import re if rule is None : return name k = re . search ( "(?<=^head)[0-9]{1,2}$" , rule ) if k : k = k . group ( 0 ) tname = name [ int ( k ) : ] else : k = re . search ( "(?<=^ohead)[0-9]{1,2}$" , rule ) if k : k = k . group ( 0 ) tname = name [ : int ( k ) ] else : k = re . search ( "(?<=^tail)[0-9]{1,2}$" , rule ) if k : k = k . group ( 0 ) tname = name [ : - int ( k ) ] else : k = re . search ( "(?<=^otail)[0-9]{1,2}$" , rule ) if k : k = k . group ( 0 ) tname = name [ - int ( k ) : ] else : print ( truncate_name . __doc__ , file = sys . stderr ) raise ValueError ( 'Wrong rule for truncation!' ) return tname | shorten taxa names for tree display |
11,965 | def run_treefix ( input , stree_file , smap_file , a_ext = ".fasta" , o_ext = ".dnd" , n_ext = ".treefix.dnd" , ** kwargs ) : cl = TreeFixCommandline ( input = input , stree_file = stree_file , smap_file = smap_file , a_ext = a_ext , o = o_ext , n = n_ext , ** kwargs ) outtreefile = input . rsplit ( o_ext , 1 ) [ 0 ] + n_ext print ( "TreeFix:" , cl , file = sys . stderr ) r , e = cl . run ( ) if e : print ( "***TreeFix could not run" , file = sys . stderr ) return None else : logging . debug ( "new tree written to {0}" . format ( outtreefile ) ) return outtreefile | get the ML tree closest to the species tree |
11,966 | def run_gblocks ( align_fasta_file , ** kwargs ) : cl = GblocksCommandline ( aln_file = align_fasta_file , ** kwargs ) r , e = cl . run ( ) print ( "Gblocks:" , cl , file = sys . stderr ) if e : print ( "***Gblocks could not run" , file = sys . stderr ) return None else : print ( r , file = sys . stderr ) alignp = re . sub ( r'.*Gblocks alignment:.*\(([0-9]{1,3}) %\).*' , r'\1' , r , flags = re . DOTALL ) alignp = int ( alignp ) if alignp <= 10 : print ( "** WARNING ** Only %s %% positions retained by Gblocks. " "Results aborted. Using original alignment instead.\n" % alignp , file = sys . stderr ) return None else : return align_fasta_file + "-gb" | remove poorly aligned positions and divergent regions with Gblocks |
11,967 | def run_ffitch ( distfile , outtreefile , intreefile = None , ** kwargs ) : cl = FfitchCommandline ( datafile = distfile , outtreefile = outtreefile , intreefile = intreefile , ** kwargs ) r , e = cl . run ( ) if e : print ( "***ffitch could not run" , file = sys . stderr ) return None else : print ( "ffitch:" , cl , file = sys . stderr ) return outtreefile | Infer tree branch lengths using ffitch in EMBOSS PHYLIP |
11,968 | def smart_reroot ( treefile , outgroupfile , outfile , format = 0 ) : tree = Tree ( treefile , format = format ) leaves = [ t . name for t in tree . get_leaves ( ) ] [ : : - 1 ] outgroup = [ ] for o in must_open ( outgroupfile ) : o = o . strip ( ) for leaf in leaves : if leaf [ : len ( o ) ] == o : outgroup . append ( leaf ) if outgroup : break if not outgroup : print ( "Outgroup not found. Tree {0} cannot be rerooted." . format ( treefile ) , file = sys . stderr ) return treefile try : tree . set_outgroup ( tree . get_common_ancestor ( * outgroup ) ) except ValueError : assert type ( outgroup ) == list outgroup = outgroup [ 0 ] tree . set_outgroup ( outgroup ) tree . write ( outfile = outfile , format = format ) logging . debug ( "Rerooted tree printed to {0}" . format ( outfile ) ) return outfile | simple function to reroot Newick format tree using ete2 |
11,969 | def build_ml_phyml ( alignment , outfile , work_dir = "." , ** kwargs ) : phy_file = op . join ( work_dir , "work" , "aln.phy" ) AlignIO . write ( alignment , file ( phy_file , "w" ) , "phylip-relaxed" ) phyml_cl = PhymlCommandline ( cmd = PHYML_BIN ( "phyml" ) , input = phy_file , ** kwargs ) logging . debug ( "Building ML tree using PhyML: %s" % phyml_cl ) stdout , stderr = phyml_cl ( ) tree_file = phy_file + "_phyml_tree.txt" if not op . exists ( tree_file ) : print ( "***PhyML failed." , file = sys . stderr ) return None sh ( "cp {0} {1}" . format ( tree_file , outfile ) , log = False ) logging . debug ( "ML tree printed to %s" % outfile ) return outfile , phy_file | build maximum likelihood tree of DNA seqs with PhyML |
11,970 | def build_ml_raxml ( alignment , outfile , work_dir = "." , ** kwargs ) : work_dir = op . join ( work_dir , "work" ) mkdir ( work_dir ) phy_file = op . join ( work_dir , "aln.phy" ) AlignIO . write ( alignment , file ( phy_file , "w" ) , "phylip-relaxed" ) raxml_work = op . abspath ( op . join ( op . dirname ( phy_file ) , "raxml_work" ) ) mkdir ( raxml_work ) raxml_cl = RaxmlCommandline ( cmd = RAXML_BIN ( "raxmlHPC" ) , sequences = phy_file , algorithm = "a" , model = "GTRGAMMA" , parsimony_seed = 12345 , rapid_bootstrap_seed = 12345 , num_replicates = 100 , name = "aln" , working_dir = raxml_work , ** kwargs ) logging . debug ( "Building ML tree using RAxML: %s" % raxml_cl ) stdout , stderr = raxml_cl ( ) tree_file = "{0}/RAxML_bipartitions.aln" . format ( raxml_work ) if not op . exists ( tree_file ) : print ( "***RAxML failed." , file = sys . stderr ) sh ( "rm -rf %s" % raxml_work , log = False ) return None sh ( "cp {0} {1}" . format ( tree_file , outfile ) , log = False ) logging . debug ( "ML tree printed to %s" % outfile ) sh ( "rm -rf %s" % raxml_work ) return outfile , phy_file | build maximum likelihood tree of DNA seqs with RAxML |
11,971 | def SH_raxml ( reftree , querytree , phy_file , shout = "SH_out.txt" ) : assert op . isfile ( reftree ) shout = must_open ( shout , "a" ) raxml_work = op . abspath ( op . join ( op . dirname ( phy_file ) , "raxml_work" ) ) mkdir ( raxml_work ) raxml_cl = RaxmlCommandline ( cmd = RAXML_BIN ( "raxmlHPC" ) , sequences = phy_file , algorithm = "h" , model = "GTRGAMMA" , name = "SH" , starting_tree = reftree , bipartition_filename = querytree , working_dir = raxml_work ) logging . debug ( "Running SH test in RAxML: %s" % raxml_cl ) o , stderr = raxml_cl ( ) try : pval = re . search ( '(Significantly.*:.*)' , o ) . group ( 0 ) except : print ( "SH test failed." , file = sys . stderr ) else : pval = pval . strip ( ) . replace ( "\t" , " " ) . replace ( "%" , "\%" ) print ( "{0}\t{1}" . format ( op . basename ( querytree ) , pval ) , file = shout ) logging . debug ( "SH p-value appended to %s" % shout . name ) shout . close ( ) return shout . name | SH test using RAxML |
11,972 | def subalignment ( alnfle , subtype , alntype = "fasta" ) : aln = AlignIO . read ( alnfle , alntype ) alnlen = aln . get_alignment_length ( ) nseq = len ( aln ) subaln = None subalnfile = alnfle . rsplit ( "." , 1 ) [ 0 ] + "_{0}.{1}" . format ( subtype , alntype ) if subtype == "synonymous" : for j in range ( 0 , alnlen , 3 ) : aa = None for i in range ( nseq ) : codon = str ( aln [ i , j : j + 3 ] . seq ) if codon not in CODON_TRANSLATION : break if aa and CODON_TRANSLATION [ codon ] != aa : break else : aa = CODON_TRANSLATION [ codon ] else : if subaln is None : subaln = aln [ : , j : j + 3 ] else : subaln += aln [ : , j : j + 3 ] if subtype == "fourfold" : for j in range ( 0 , alnlen , 3 ) : for i in range ( nseq ) : codon = str ( aln [ i , j : j + 3 ] . seq ) if codon not in FOURFOLD : break else : if subaln is None : subaln = aln [ : , j : j + 3 ] else : subaln += aln [ : , j : j + 3 ] if subaln : AlignIO . write ( subaln , subalnfile , alntype ) return subalnfile else : print ( "No sites {0} selected." . format ( subtype ) , file = sys . stderr ) return None | Subset synonymous or fourfold degenerate sites from an alignment |
11,973 | def merge_rows_local ( filename , ignore = "." , colsep = "\t" , local = 10 , fieldcheck = True , fsep = "," ) : fw = must_open ( filename + ".merged" , "w" ) rows = file ( filename ) . readlines ( ) rows = [ row . strip ( ) . split ( colsep ) for row in rows ] l = len ( rows [ 0 ] ) for rowi , row in enumerate ( rows ) : n = len ( rows ) i = rowi + 1 while i <= min ( rowi + local , n - 1 ) : merge = 1 row2 = rows [ i ] for j in range ( l ) : a = row [ j ] b = row2 [ j ] if fieldcheck : a = set ( a . split ( fsep ) ) a = fsep . join ( sorted ( list ( a ) ) ) b = set ( b . split ( fsep ) ) b = fsep . join ( sorted ( list ( b ) ) ) if all ( [ a != ignore , b != ignore , a not in b , b not in a ] ) : merge = 0 i += 1 break if merge : for x in range ( l ) : if row [ x ] == ignore : rows [ rowi ] [ x ] = row2 [ x ] elif row [ x ] in row2 [ x ] : rows [ rowi ] [ x ] = row2 [ x ] else : rows [ rowi ] [ x ] = row [ x ] row = rows [ rowi ] rows . remove ( row2 ) print ( colsep . join ( row ) , file = fw ) fw . close ( ) return fw . name | merge overlapping rows within given row count distance |
11,974 | def add_tandems ( mcscanfile , tandemfile ) : tandems = [ f . strip ( ) . split ( "," ) for f in file ( tandemfile ) ] fw = must_open ( mcscanfile + ".withtandems" , "w" ) fp = must_open ( mcscanfile ) seen = set ( ) for i , row in enumerate ( fp ) : if row [ 0 ] == '#' : continue anchorslist = row . strip ( ) . split ( "\t" ) anchors = set ( [ a . split ( "," ) [ 0 ] for a in anchorslist ] ) anchors . remove ( "." ) if anchors & seen == anchors : continue newanchors = [ ] for a in anchorslist : if a == "." : newanchors . append ( a ) continue for t in tandems : if a in t : newanchors . append ( "," . join ( t ) ) seen . update ( t ) break else : newanchors . append ( a ) seen . add ( a ) print ( "\t" . join ( newanchors ) , file = fw ) fw . close ( ) newmcscanfile = merge_rows_local ( fw . name ) logging . debug ( "Tandems added to `{0}`. Results in `{1}`" . format ( mcscanfile , newmcscanfile ) ) fp . seek ( 0 ) logging . debug ( "{0} rows merged to {1} rows" . format ( len ( fp . readlines ( ) ) , len ( file ( newmcscanfile ) . readlines ( ) ) ) ) sh ( "rm %s" % fw . name ) return newmcscanfile | add tandem genes to anchor genes in mcscan file |
11,975 | def _draw_trees ( trees , nrow = 1 , ncol = 1 , rmargin = .3 , iopts = None , outdir = "." , shfile = None , ** kwargs ) : from jcvi . graphics . tree import draw_tree if shfile : SHs = DictFile ( shfile , delimiter = "\t" ) ntrees = len ( trees ) n = nrow * ncol for x in xrange ( int ( ceil ( float ( ntrees ) / n ) ) ) : fig = plt . figure ( 1 , ( iopts . w , iopts . h ) ) if iopts else plt . figure ( 1 , ( 5 , 5 ) ) root = fig . add_axes ( [ 0 , 0 , 1 , 1 ] ) xiv = 1. / ncol yiv = 1. / nrow xstart = list ( np . arange ( 0 , 1 , xiv ) ) * nrow ystart = list ( chain ( * zip ( * [ list ( np . arange ( 0 , 1 , yiv ) ) [ : : - 1 ] ] * ncol ) ) ) for i in xrange ( n * x , n * ( x + 1 ) ) : if i == ntrees : break ax = fig . add_axes ( [ xstart [ i % n ] , ystart [ i % n ] , xiv , yiv ] ) f = trees . keys ( ) [ i ] tree = trees [ f ] try : SH = SHs [ f ] except : SH = None draw_tree ( ax , tree , rmargin = rmargin , reroot = False , supportcolor = "r" , SH = SH , ** kwargs ) root . set_xlim ( 0 , 1 ) root . set_ylim ( 0 , 1 ) root . set_axis_off ( ) format = iopts . format if iopts else "pdf" dpi = iopts . dpi if iopts else 300 if n == 1 : image_name = f . rsplit ( "." , 1 ) [ 0 ] + "." + format else : image_name = "trees{0}.{1}" . format ( x , format ) image_name = op . join ( outdir , image_name ) savefig ( image_name , dpi = dpi , iopts = iopts ) plt . clf ( ) | Draw one or multiple trees on one plot . |
11,976 | def sort_layout ( thread , listfile , column = 0 ) : from jcvi . formats . base import DictFile outfile = listfile . rsplit ( "." , 1 ) [ 0 ] + ".sorted.list" threadorder = thread . order fw = open ( outfile , "w" ) lt = DictFile ( listfile , keypos = column , valuepos = None ) threaded = [ ] imported = set ( ) for t in thread : accn = t . accn if accn not in lt : continue imported . add ( accn ) atoms = lt [ accn ] threaded . append ( atoms ) assert len ( threaded ) == len ( imported ) total = sum ( 1 for x in open ( listfile ) ) logging . debug ( "Total: {0}, currently threaded: {1}" . format ( total , len ( threaded ) ) ) fp = open ( listfile ) for row in fp : atoms = row . split ( ) accn = atoms [ 0 ] if accn in imported : continue insert_into_threaded ( atoms , threaded , threadorder ) for atoms in threaded : print ( "\t" . join ( atoms ) , file = fw ) fw . close ( ) logging . debug ( "File `{0}` sorted to `{1}`." . format ( outfile , thread . filename ) ) | Sort the syntelog table according to chromomomal positions . First orient the contents against threadbed then for contents not in threadbed insert to the nearest neighbor . |
11,977 | def layout ( args ) : p = OptionParser ( layout . __doc__ ) p . add_option ( "--sort" , help = "Sort layout file based on bedfile [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) omgfile , taxa = args listfile = omgfile . rsplit ( "." , 1 ) [ 0 ] + ".list" taxa = taxa . split ( "," ) ntaxa = len ( taxa ) fw = open ( listfile , "w" ) data = [ ] fp = open ( omgfile ) for row in fp : genes , idxs = row . split ( ) row = [ "." ] * ntaxa genes = genes . split ( "," ) ixs = [ int ( x ) for x in idxs . split ( "," ) ] for gene , idx in zip ( genes , ixs ) : row [ idx ] = gene txs = "," . join ( taxa [ x ] for x in ixs ) print ( "\t" . join ( ( "\t" . join ( row ) , txs ) ) , file = fw ) data . append ( row ) coldata = zip ( * data ) ngenes = [ ] for i , tx in enumerate ( taxa ) : genes = [ x for x in coldata [ i ] if x != '.' ] genes = set ( x . strip ( "|" ) for x in genes ) ngenes . append ( ( len ( genes ) , tx ) ) details = ", " . join ( "{0} {1}" . format ( a , b ) for a , b in ngenes ) total = sum ( a for a , b in ngenes ) s = "A list of {0} orthologous families that collectively" . format ( len ( data ) ) s += " contain a total of {0} genes ({1})" . format ( total , details ) print ( s , file = sys . stderr ) fw . close ( ) lastcolumn = ntaxa + 1 cmd = "sort -k{0},{0} {1} -o {1}" . format ( lastcolumn , listfile ) sh ( cmd ) logging . debug ( "List file written to `{0}`." . format ( listfile ) ) sort = opts . sort if sort : thread = Bed ( sort ) sort_layout ( thread , listfile ) | %prog layout omgfile taxa |
11,978 | def omgparse ( args ) : p = OptionParser ( omgparse . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) work , = args omgfiles = glob ( op . join ( work , "gf*.out" ) ) for omgfile in omgfiles : omg = OMGFile ( omgfile ) best = omg . best ( ) for bb in best : genes , taxa = zip ( * bb ) print ( "\t" . join ( ( "," . join ( genes ) , "," . join ( taxa ) ) ) ) | %prog omgparse work |
11,979 | def group ( args ) : p = OptionParser ( group . __doc__ ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) < 1 : sys . exit ( not p . print_help ( ) ) anchorfiles = args groups = Grouper ( ) for anchorfile in anchorfiles : ac = AnchorFile ( anchorfile ) for a , b , idx in ac . iter_pairs ( ) : groups . join ( a , b ) logging . debug ( "Created {0} groups with {1} members." . format ( len ( groups ) , groups . num_members ) ) outfile = opts . outfile fw = must_open ( outfile , "w" ) for g in groups : print ( "," . join ( sorted ( g ) ) , file = fw ) fw . close ( ) return outfile | %prog group anchorfiles |
11,980 | def omg ( args ) : p = OptionParser ( omg . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) < 1 : sys . exit ( not p . print_help ( ) ) weightsfiles = args groupfile = group ( weightsfiles + [ "--outfile=groups" ] ) weights = get_weights ( weightsfiles ) info = get_info ( ) fp = open ( groupfile ) work = "work" mkdir ( work ) for i , row in enumerate ( fp ) : gf = op . join ( work , "gf{0:05d}" . format ( i ) ) genes = row . rstrip ( ) . split ( "," ) fw = open ( gf , "w" ) contents = "" npairs = 0 for gene in genes : gene_pairs = weights [ gene ] for a , b , c in gene_pairs : if b not in genes : continue contents += "weight {0}" . format ( c ) + '\n' contents += info [ a ] + '\n' contents += info [ b ] + '\n\n' npairs += 1 header = "a group of genes :length ={0}" . format ( npairs ) print ( header , file = fw ) print ( contents , file = fw ) fw . close ( ) | %prog omg weightsfile |
11,981 | def omgprepare ( args ) : from jcvi . formats . blast import cscore from jcvi . formats . base import DictFile p = OptionParser ( omgprepare . __doc__ ) p . add_option ( "--norbh" , action = "store_true" , help = "Disable RBH hits [default: %default]" ) p . add_option ( "--pctid" , default = 0 , type = "int" , help = "Percent id cutoff for RBH hits [default: %default]" ) p . add_option ( "--cscore" , default = 90 , type = "int" , help = "C-score cutoff for RBH hits [default: %default]" ) p . set_stripnames ( ) p . set_beds ( ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) ploidy , anchorfile , blastfile = args norbh = opts . norbh pctid = opts . pctid cs = opts . cscore qbed , sbed , qorder , sorder , is_self = check_beds ( anchorfile , p , opts ) fp = open ( ploidy ) genomeidx = dict ( ( x . split ( ) [ 0 ] , i ) for i , x in enumerate ( fp ) ) fp . close ( ) ploidy = DictFile ( ploidy ) geneinfo ( qbed , qorder , genomeidx , ploidy ) geneinfo ( sbed , sorder , genomeidx , ploidy ) pf = blastfile . rsplit ( "." , 1 ) [ 0 ] cscorefile = pf + ".cscore" cscore ( [ blastfile , "-o" , cscorefile , "--cutoff=0" , "--pct" ] ) ac = AnchorFile ( anchorfile ) pairs = set ( ( a , b ) for a , b , i in ac . iter_pairs ( ) ) logging . debug ( "Imported {0} pairs from `{1}`." . format ( len ( pairs ) , anchorfile ) ) weightsfile = pf + ".weights" fp = open ( cscorefile ) fw = open ( weightsfile , "w" ) npairs = 0 for row in fp : a , b , c , pct = row . split ( ) c , pct = float ( c ) , float ( pct ) c = int ( c * 100 ) if ( a , b ) not in pairs : if norbh : continue if c < cs : continue if pct < pctid : continue c /= 10 print ( "\t" . join ( ( a , b , str ( c ) ) ) , file = fw ) npairs += 1 fw . close ( ) logging . debug ( "Write {0} pairs to `{1}`." . format ( npairs , weightsfile ) ) | %prog omgprepare ploidy anchorsfile blastfile |
11,982 | def parse_qs ( qs , keep_blank_values = 0 , strict_parsing = 0 , keep_attr_order = True ) : od = DefaultOrderedDict ( list ) if keep_attr_order else defaultdict ( list ) for name , value in parse_qsl ( qs , keep_blank_values , strict_parsing ) : od [ name ] . append ( value ) return od | Kind of like urlparse . parse_qs except returns an ordered dict . Also avoids replicating that function s bad habit of overriding the built - in dict type . |
11,983 | def index ( self , item ) : 'Find the position of an item. Raise ValueError if not found.' k = self . _key ( item ) i = bisect_left ( self . _keys , k ) j = bisect_right ( self . _keys , k ) return self . _items [ i : j ] . index ( item ) + i | Find the position of an item . Raise ValueError if not found . |
11,984 | def insert ( self , item ) : 'Insert a new item. If equal keys are found, add to the left' k = self . _key ( item ) i = bisect_left ( self . _keys , k ) self . _keys . insert ( i , k ) self . _items . insert ( i , item ) | Insert a new item . If equal keys are found add to the left |
11,985 | def insert_right ( self , item ) : 'Insert a new item. If equal keys are found, add to the right' k = self . _key ( item ) i = bisect_right ( self . _keys , k ) self . _keys . insert ( i , k ) self . _items . insert ( i , item ) | Insert a new item . If equal keys are found add to the right |
11,986 | def remove ( self , item ) : 'Remove first occurence of item. Raise ValueError if not found' i = self . index ( item ) del self . _keys [ i ] del self . _items [ i ] | Remove first occurence of item . Raise ValueError if not found |
11,987 | def find_ge ( self , item ) : 'Return first item with a key >= equal to item. Raise ValueError if not found' k = self . _key ( item ) i = bisect_left ( self . _keys , k ) if i != len ( self ) : return self . _items [ i ] raise ValueError ( 'No item found with key at or above: %r' % ( k , ) ) | Return first item with a key > = equal to item . Raise ValueError if not found |
11,988 | def find_gt ( self , item ) : 'Return first item with a key > item. Raise ValueError if not found' k = self . _key ( item ) i = bisect_right ( self . _keys , k ) if i != len ( self ) : return self . _items [ i ] raise ValueError ( 'No item found with key above: %r' % ( k , ) ) | Return first item with a key > item . Raise ValueError if not found |
11,989 | def multireport ( args ) : p = OptionParser ( multireport . __doc__ ) p . set_outfile ( outfile = "Ks_plot.pdf" ) add_plot_options ( p ) opts , args , iopts = p . set_image_options ( args , figsize = "5x5" ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) layoutfile , = args ks_min = opts . vmin ks_max = opts . vmax bins = opts . bins fill = opts . fill layout = Layout ( layoutfile ) print ( layout , file = sys . stderr ) fig = plt . figure ( 1 , ( iopts . w , iopts . h ) ) ax = fig . add_axes ( [ .12 , .1 , .8 , .8 ] ) kp = KsPlot ( ax , ks_max , bins , legendp = opts . legendp ) for lo in layout : data = KsFile ( lo . ksfile ) data = [ x . ng_ks for x in data ] data = [ x for x in data if ks_min <= x <= ks_max ] kp . add_data ( data , lo . components , label = lo . label , color = lo . color , marker = lo . marker , fill = fill , fitted = opts . fit ) kp . draw ( title = opts . title , filename = opts . outfile ) | %prog multireport layoutfile |
11,990 | def fromgroups ( args ) : from jcvi . formats . bed import Bed p = OptionParser ( fromgroups . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) < 2 : sys . exit ( not p . print_help ( ) ) groupsfile = args [ 0 ] bedfiles = args [ 1 : ] beds = [ Bed ( x ) for x in bedfiles ] fp = open ( groupsfile ) groups = [ row . strip ( ) . split ( "," ) for row in fp ] for b1 , b2 in product ( beds , repeat = 2 ) : extract_pairs ( b1 , b2 , groups ) | %prog fromgroups groupsfile a . bed b . bed ... |
11,991 | def find_synonymous ( input_file , work_dir ) : cwd = os . getcwd ( ) os . chdir ( work_dir ) ctl_file = "yn-input.ctl" output_file = "nuc-subs.yn" ctl_h = open ( ctl_file , "w" ) ctl_h . write ( "seqfile = %s\noutfile = %s\nverbose = 0\n" % ( op . basename ( input_file ) , output_file ) ) ctl_h . write ( "icode = 0\nweighting = 0\ncommonf3x4 = 0\n" ) ctl_h . close ( ) cl = YnCommandline ( ctl_file ) print ( "\tyn00:" , cl , file = sys . stderr ) r , e = cl . run ( ) ds_value_yn = None ds_value_ng = None dn_value_yn = None dn_value_ng = None output_h = open ( output_file ) row = output_h . readline ( ) while row : if row . find ( "Nei & Gojobori" ) >= 0 : for x in xrange ( 5 ) : row = next ( output_h ) dn_value_ng , ds_value_ng = row . split ( '(' ) [ 1 ] . split ( ')' ) [ 0 ] . split ( ) break row = output_h . readline ( ) output_h . close ( ) output_h = open ( output_file ) for line in output_h : if line . find ( "+-" ) >= 0 and line . find ( "dS" ) == - 1 : parts = line . split ( " +-" ) ds_value_yn = extract_subs_value ( parts [ 1 ] ) dn_value_yn = extract_subs_value ( parts [ 0 ] ) if ds_value_yn is None or ds_value_ng is None : h = open ( output_file ) print ( "yn00 didn't work: \n%s" % h . read ( ) , file = sys . stderr ) os . chdir ( cwd ) return ds_value_yn , dn_value_yn , ds_value_ng , dn_value_ng | Run yn00 to find the synonymous subsitution rate for the alignment . |
11,992 | def run_mrtrans ( align_fasta , recs , work_dir , outfmt = "paml" ) : align_file = op . join ( work_dir , "prot-align.fasta" ) nuc_file = op . join ( work_dir , "nuc.fasta" ) output_file = op . join ( work_dir , "nuc-align.mrtrans" ) align_h0 = open ( align_file + "0" , "w" ) align_h0 . write ( str ( align_fasta ) ) align_h0 . close ( ) prot_seqs = { } i = 0 for rec in SeqIO . parse ( align_h0 . name , "fasta" ) : prot_seqs [ i ] = rec . seq i += 1 align_h = open ( align_file , "w" ) for i , rec in enumerate ( recs ) : if len ( rec . id ) > 30 : rec . id = rec . id [ : 28 ] + "_" + str ( i ) rec . description = "" print ( ">{0}\n{1}" . format ( rec . id , prot_seqs [ i ] ) , file = align_h ) align_h . close ( ) SeqIO . write ( recs , file ( nuc_file , "w" ) , "fasta" ) cl = MrTransCommandline ( align_file , nuc_file , output_file , outfmt = outfmt ) r , e = cl . run ( ) if e is None : print ( "\tpal2nal:" , cl , file = sys . stderr ) return output_file elif e . read ( ) . find ( "could not translate" ) >= 0 : print ( "***pal2nal could not translate" , file = sys . stderr ) return None | Align nucleotide sequences with mrtrans and the protein alignment . |
11,993 | def clustal_align_protein ( recs , work_dir , outfmt = "fasta" ) : fasta_file = op . join ( work_dir , "prot-start.fasta" ) align_file = op . join ( work_dir , "prot.aln" ) SeqIO . write ( recs , file ( fasta_file , "w" ) , "fasta" ) clustal_cl = ClustalwCommandline ( cmd = CLUSTALW_BIN ( "clustalw2" ) , infile = fasta_file , outfile = align_file , outorder = "INPUT" , type = "PROTEIN" ) stdout , stderr = clustal_cl ( ) aln_file = file ( clustal_cl . outfile ) alignment = AlignIO . read ( aln_file , "clustal" ) print ( "\tDoing clustalw alignment: %s" % clustal_cl , file = sys . stderr ) if outfmt == "fasta" : return alignment . format ( "fasta" ) if outfmt == "clustal" : return alignment | Align given proteins with clustalw . recs are iterable of Biopython SeqIO objects |
11,994 | def muscle_align_protein ( recs , work_dir , outfmt = "fasta" , inputorder = True ) : fasta_file = op . join ( work_dir , "prot-start.fasta" ) align_file = op . join ( work_dir , "prot.aln" ) SeqIO . write ( recs , file ( fasta_file , "w" ) , "fasta" ) muscle_cl = MuscleCommandline ( cmd = MUSCLE_BIN ( "muscle" ) , input = fasta_file , out = align_file , seqtype = "protein" , clwstrict = True ) stdout , stderr = muscle_cl ( ) alignment = AlignIO . read ( muscle_cl . out , "clustal" ) if inputorder : try : muscle_inputorder ( muscle_cl . input , muscle_cl . out ) except ValueError : return "" alignment = AlignIO . read ( muscle_cl . out , "fasta" ) print ( "\tDoing muscle alignment: %s" % muscle_cl , file = sys . stderr ) if outfmt == "fasta" : return alignment . format ( "fasta" ) if outfmt == "clustal" : return alignment . format ( "clustal" ) | Align given proteins with muscle . recs are iterable of Biopython SeqIO objects |
11,995 | def subset ( args ) : p = OptionParser ( subset . __doc__ ) p . add_option ( "--noheader" , action = "store_true" , help = "don't write ksfile header line [default: %default]" ) p . add_option ( "--block" , action = "store_true" , help = "preserve block structure in input [default: %default]" ) p . set_stripnames ( ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) pairsfile , ksfiles = args [ 0 ] , args [ 1 : ] noheader = opts . noheader block = opts . block if block : noheader = True outfile = opts . outfile ksvals = { } for ksfile in ksfiles : ksvals . update ( dict ( ( line . name , line ) for line in KsFile ( ksfile , strip_names = opts . strip_names ) ) ) fp = open ( pairsfile ) fw = must_open ( outfile , "w" ) if not noheader : print ( fields , file = fw ) i = j = 0 for row in fp : if row [ 0 ] == '#' : if block : print ( row . strip ( ) , file = fw ) continue a , b = row . split ( ) [ : 2 ] name = ";" . join ( ( a , b ) ) if name not in ksvals : name = ";" . join ( ( b , a ) ) if name not in ksvals : j += 1 print ( "\t" . join ( ( a , b , "." , "." ) ) , file = fw ) continue ksline = ksvals [ name ] if block : print ( "\t" . join ( str ( x ) for x in ( a , b , ksline . ks ) ) , file = fw ) else : ksline . name = ";" . join ( ( a , b ) ) print ( ksline , file = fw ) i += 1 fw . close ( ) logging . debug ( "{0} pairs not found in ksfiles" . format ( j ) ) logging . debug ( "{0} ks records written to `{1}`" . format ( i , outfile ) ) return outfile | %prog subset pairsfile ksfile1 ksfile2 ... - o pairs . ks |
11,996 | def report ( args ) : from jcvi . utils . cbook import SummaryStats from jcvi . graphics . histogram import stem_leaf_plot p = OptionParser ( report . __doc__ ) p . add_option ( "--pdf" , default = False , action = "store_true" , help = "Generate graphic output for the histogram [default: %default]" ) p . add_option ( "--components" , default = 1 , type = "int" , help = "Number of components to decompose peaks [default: %default]" ) add_plot_options ( p ) opts , args , iopts = p . set_image_options ( args , figsize = "5x5" ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) ks_file , = args data = KsFile ( ks_file ) ks_min = opts . vmin ks_max = opts . vmax bins = opts . bins for f in fields . split ( "," ) [ 1 : ] : columndata = [ getattr ( x , f ) for x in data ] ks = ( "ks" in f ) if not ks : continue columndata = [ x for x in columndata if ks_min <= x <= ks_max ] st = SummaryStats ( columndata ) title = "{0} ({1}): " . format ( descriptions [ f ] , ks_file ) title += "Median:{0:.3f} (1Q:{1:.3f}|3Q:{2:.3f}||" . format ( st . median , st . firstq , st . thirdq ) title += "Mean:{0:.3f}|Std:{1:.3f}||N:{2})" . format ( st . mean , st . sd , st . size ) tbins = ( 0 , ks_max , bins ) if ks else ( 0 , .6 , 10 ) digit = 2 if ( ks_max * 1. / bins ) < .1 else 1 stem_leaf_plot ( columndata , * tbins , digit = digit , title = title ) if not opts . pdf : return components = opts . components data = [ x . ng_ks for x in data ] data = [ x for x in data if ks_min <= x <= ks_max ] fig = plt . figure ( 1 , ( iopts . w , iopts . h ) ) ax = fig . add_axes ( [ .12 , .1 , .8 , .8 ] ) kp = KsPlot ( ax , ks_max , opts . bins , legendp = opts . legendp ) kp . add_data ( data , components , fill = opts . fill , fitted = opts . fit ) kp . draw ( title = opts . title ) | %prog report ksfile |
11,997 | def passthrough ( args ) : p = OptionParser ( passthrough . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) vcffile , newvcffile = args fp = open ( vcffile ) fw = open ( newvcffile , "w" ) gg = [ "0/0" , "0/1" , "1/1" ] for row in fp : if row [ 0 ] == "#" : print ( row . strip ( ) , file = fw ) continue v = VcfLine ( row ) v . filter = "PASS" v . format = "GT:GP" probs = [ 0 ] * 3 probs [ gg . index ( v . genotype ) ] = 1 v . genotype = v . genotype . replace ( "/" , "|" ) + ":{0}" . format ( "," . join ( "{0:.3f}" . format ( x ) for x in probs ) ) print ( v , file = fw ) fw . close ( ) | %prog passthrough chrY . vcf chrY . new . vcf |
11,998 | def validate ( args ) : p = OptionParser ( validate . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) imputed , withheld = args register = { } fp = open ( withheld ) for row in fp : if row [ 0 ] == "#" : continue v = VcfLine ( row ) register [ ( v . seqid , v . pos ) ] = v . genotype logging . debug ( "Imported {0} records from `{1}`" . format ( len ( register ) , withheld ) ) fp = must_open ( imputed ) hit = concordant = 0 seen = set ( ) for row in fp : if row [ 0 ] == "#" : continue v = VcfLine ( row ) chr , pos , genotype = v . seqid , v . pos , v . genotype if ( chr , pos ) in seen : continue seen . add ( ( chr , pos ) ) if ( chr , pos ) not in register : continue truth = register [ ( chr , pos ) ] imputed = genotype . split ( ":" ) [ 0 ] if "|" in imputed : imputed = "/" . join ( sorted ( genotype . split ( ":" ) [ 0 ] . split ( "|" ) ) ) hit += 1 if truth == imputed : concordant += 1 else : print ( row . strip ( ) , "truth={0}" . format ( truth ) , file = sys . stderr ) logging . debug ( "Total concordant: {0}" . format ( percentage ( concordant , hit ) ) ) | %prog validate imputed . vcf withheld . vcf |
11,999 | def minimac ( args ) : p = OptionParser ( minimac . __doc__ ) p . set_home ( "shapeit" ) p . set_home ( "minimac" ) p . set_outfile ( ) p . set_chr ( ) p . set_ref ( ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) txtfile , = args ref = opts . ref mm = MakeManager ( ) pf = txtfile . split ( "." ) [ 0 ] allrawvcf = [ ] alloutvcf = [ ] chrs = opts . chr . split ( "," ) for x in chrs : px = CM [ x ] chrvcf = pf + ".{0}.vcf" . format ( px ) if txtfile . endswith ( ".vcf" ) : cmd = "vcftools --vcf {0} --chr {1}" . format ( txtfile , x ) cmd += " --out {0}.{1} --recode" . format ( pf , px ) cmd += " && mv {0}.{1}.recode.vcf {2}" . format ( pf , px , chrvcf ) else : cmd = "python -m jcvi.formats.vcf from23andme {0} {1}" . format ( txtfile , x ) cmd += " --ref {0}" . format ( ref ) mm . add ( txtfile , chrvcf , cmd ) chrvcf_hg38 = pf + ".{0}.23andme.hg38.vcf" . format ( px ) minimac_liftover ( mm , chrvcf , chrvcf_hg38 , opts ) allrawvcf . append ( chrvcf_hg38 ) minimacvcf = "{0}.{1}.minimac.dose.vcf" . format ( pf , px ) if x == "X" : minimac_X ( mm , x , chrvcf , opts ) elif x in [ "Y" , "MT" ] : cmd = "python -m jcvi.variation.impute passthrough" cmd += " {0} {1}" . format ( chrvcf , minimacvcf ) mm . add ( chrvcf , minimacvcf , cmd ) else : minimac_autosome ( mm , x , chrvcf , opts ) uniqvcf = "{0}.{1}.minimac.uniq.vcf" . format ( pf , px ) cmd = "python -m jcvi.formats.vcf uniq {0} > {1}" . format ( minimacvcf , uniqvcf ) mm . add ( minimacvcf , uniqvcf , cmd ) minimacvcf_hg38 = "{0}.{1}.minimac.hg38.vcf" . format ( pf , px ) minimac_liftover ( mm , uniqvcf , minimacvcf_hg38 , opts ) alloutvcf . append ( minimacvcf_hg38 ) if len ( allrawvcf ) > 1 : rawhg38vcfgz = pf + ".all.23andme.hg38.vcf.gz" cmd = "vcf-concat {0} | bgzip > {1}" . format ( " " . join ( allrawvcf ) , rawhg38vcfgz ) mm . add ( allrawvcf , rawhg38vcfgz , cmd ) if len ( alloutvcf ) > 1 : outhg38vcfgz = pf + ".all.minimac.hg38.vcf.gz" cmd = "vcf-concat {0} | bgzip > {1}" . format ( " " . join ( alloutvcf ) , outhg38vcfgz ) mm . add ( alloutvcf , outhg38vcfgz , cmd ) mm . write ( ) | %prog batchminimac input . txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.