idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
11,800 | def fromaligns ( args ) : p = OptionParser ( fromaligns . __doc__ ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) alignsfile , = args fp = must_open ( alignsfile ) fw = must_open ( opts . outfile , "w" ) for row in fp : if row . startswith ( "## Alignment" ) : print ( "###" , file = fw ) continue if row [ 0 ] == '#' or not row . strip ( ) : continue atoms = row . split ( ':' ) [ - 1 ] . split ( ) print ( "\t" . join ( atoms [ : 2 ] ) , file = fw ) fw . close ( ) | %prog fromaligns out . aligns |
11,801 | def mcscanq ( args ) : p = OptionParser ( mcscanq . __doc__ ) p . add_option ( "--color" , help = "Add color highlight, used in plotting" ) p . add_option ( "--invert" , default = False , action = "store_true" , help = "Invert query and subject [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) < 2 : sys . exit ( not p . print_help ( ) ) qids , blocksfile = args b = BlockFile ( blocksfile ) fp = open ( qids ) for gene in fp : gene = gene . strip ( ) for line in b . query_gene ( gene , color = opts . color , invert = opts . invert ) : print ( line ) | %prog mcscanq query . ids blocksfile |
11,802 | def spa ( args ) : from jcvi . algorithms . graph import merge_paths from jcvi . utils . cbook import uniqify p = OptionParser ( spa . __doc__ ) p . add_option ( "--unmapped" , default = False , action = "store_true" , help = "Include unmapped scaffolds in the list [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) < 1 : sys . exit ( not p . print_help ( ) ) spafiles = args paths = [ ] mappings = [ ] missings = [ ] for spafile in spafiles : fp = open ( spafile ) path = [ ] mapping = [ ] missing = [ ] for row in fp : if row [ 0 ] == '#' or not row . strip ( ) : continue atoms = row . rstrip ( ) . split ( '\t' ) if len ( atoms ) == 2 : a , c2 = atoms assert a == "unmapped" missing . append ( c2 ) continue c1 , c2 , orientation = atoms path . append ( c1 ) mapping . append ( c2 ) paths . append ( uniqify ( path ) ) mappings . append ( mapping ) missings . append ( missing ) ref = merge_paths ( paths ) print ( "ref" , len ( ref ) , "," . join ( ref ) ) for spafile , mapping , missing in zip ( spafiles , mappings , missings ) : mapping = [ x for x in mapping if "random" not in x ] mapping = uniqify ( mapping ) if len ( mapping ) < 50 and opts . unmapped : mapping = uniqify ( mapping + missing ) print ( spafile , len ( mapping ) , "," . join ( mapping ) ) | %prog spa spafiles |
11,803 | def rebuild ( args ) : p = OptionParser ( rebuild . __doc__ ) p . add_option ( "--header" , default = False , action = "store_true" , help = "First line is header [default: %default]" ) p . add_option ( "--write_blast" , default = False , action = "store_true" , help = "Get blast records of rebuilt anchors [default: %default]" ) p . set_beds ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) blocksfile , blastfile = args bk = BlockFile ( blocksfile , header = opts . header ) fw = open ( "pairs" , "w" ) for a , b , h in bk . iter_all_pairs ( ) : print ( "\t" . join ( ( a , b ) ) , file = fw ) fw . close ( ) if opts . write_blast : AnchorFile ( "pairs" ) . blast ( blastfile , "pairs.blast" ) fw = open ( "tracks" , "w" ) for g , col in bk . iter_gene_col ( ) : print ( "\t" . join ( str ( x ) for x in ( g , col ) ) , file = fw ) fw . close ( ) | %prog rebuild blocksfile blastfile |
11,804 | def coge ( args ) : p = OptionParser ( coge . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) cogefile , = args fp = must_open ( cogefile ) cogefile = cogefile . replace ( ".gz" , "" ) ksfile = cogefile + ".ks" anchorsfile = cogefile + ".anchors" fw_ks = must_open ( ksfile , "w" ) fw_ac = must_open ( anchorsfile , "w" ) tag = "###" print ( tag , file = fw_ks ) for header , lines in read_block ( fp , tag ) : print ( tag , file = fw_ac ) lines = list ( lines ) for line in lines : if line [ 0 ] == '#' : continue ks , ka , achr , a , astart , astop , bchr , b , bstart , bstop , ev , ss = line . split ( ) a = a . split ( "||" ) [ 3 ] b = b . split ( "||" ) [ 3 ] print ( "\t" . join ( ( a , b , ev ) ) , file = fw_ac ) print ( "," . join ( ( ";" . join ( ( a , b ) ) , ks , ka , ks , ka ) ) , file = fw_ks ) fw_ks . close ( ) fw_ac . close ( ) | %prog coge cogefile |
11,805 | def matrix ( args ) : p = OptionParser ( matrix . __doc__ ) p . add_option ( "--seqids" , help = "File with seqids [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) bedfile , anchorfile , matrixfile = args ac = AnchorFile ( anchorfile ) seqidsfile = opts . seqids if seqidsfile : seqids = SetFile ( seqidsfile , delimiter = ',' ) order = Bed ( bedfile ) . order blocks = ac . blocks m = defaultdict ( int ) fw = open ( matrixfile , "w" ) aseqids = set ( ) bseqids = set ( ) for block in blocks : a , b , scores = zip ( * block ) ai , af = order [ a [ 0 ] ] bi , bf = order [ b [ 0 ] ] aseqid = af . seqid bseqid = bf . seqid if seqidsfile : if ( aseqid not in seqids ) or ( bseqid not in seqids ) : continue m [ ( aseqid , bseqid ) ] += len ( block ) aseqids . add ( aseqid ) bseqids . add ( bseqid ) aseqids = list ( aseqids ) bseqids = list ( bseqids ) print ( "\t" . join ( [ "o" ] + bseqids ) , file = fw ) for aseqid in aseqids : print ( "\t" . join ( [ aseqid ] + [ str ( m [ ( aseqid , x ) ] ) for x in bseqids ] ) , file = fw ) | %prog matrix all . bed anchorfile matrixfile |
11,806 | def summary ( args ) : from jcvi . utils . cbook import SummaryStats p = OptionParser ( summary . __doc__ ) p . add_option ( "--prefix" , help = "Generate per block stats [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) anchorfile , = args ac = AnchorFile ( anchorfile ) clusters = ac . blocks if clusters == [ [ ] ] : logging . debug ( "A total of 0 anchor was found. Aborted." ) raise ValueError ( "A total of 0 anchor was found. Aborted." ) nclusters = len ( clusters ) nanchors = [ len ( c ) for c in clusters ] nranchors = [ _score ( c ) for c in clusters ] print ( "A total of {0} (NR:{1}) anchors found in {2} clusters." . format ( sum ( nanchors ) , sum ( nranchors ) , nclusters ) , file = sys . stderr ) print ( "Stats:" , SummaryStats ( nanchors ) , file = sys . stderr ) print ( "NR stats:" , SummaryStats ( nranchors ) , file = sys . stderr ) prefix = opts . prefix if prefix : pad = len ( str ( nclusters ) ) for i , c in enumerate ( clusters ) : block_id = "{0}{1:0{2}d}" . format ( prefix , i + 1 , pad ) print ( "\t" . join ( ( block_id , str ( len ( c ) ) ) ) ) | %prog summary anchorfile |
11,807 | def stats ( args ) : from jcvi . utils . cbook import percentage p = OptionParser ( stats . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) blocksfile , = args fp = open ( blocksfile ) counts = defaultdict ( int ) total = orthologous = 0 for row in fp : atoms = row . rstrip ( ) . split ( "\t" ) hits = [ x for x in atoms [ 1 : ] if x != '.' ] counts [ len ( hits ) ] += 1 total += 1 if atoms [ 1 ] != '.' : orthologous += 1 print ( "Total lines: {0}" . format ( total ) , file = sys . stderr ) for i , n in sorted ( counts . items ( ) ) : print ( "Count {0}: {1}" . format ( i , percentage ( n , total ) ) , file = sys . stderr ) print ( file = sys . stderr ) matches = sum ( n for i , n in counts . items ( ) if i != 0 ) print ( "Total lines with matches: {0}" . format ( percentage ( matches , total ) ) , file = sys . stderr ) for i , n in sorted ( counts . items ( ) ) : if i == 0 : continue print ( "Count {0}: {1}" . format ( i , percentage ( n , matches ) ) , file = sys . stderr ) print ( file = sys . stderr ) print ( "Orthologous matches: {0}" . format ( percentage ( orthologous , matches ) ) , file = sys . stderr ) | %prog stats blocksfile |
11,808 | def write_details ( fw , details , bed ) : for a , b , depth in details : for i in xrange ( a , b ) : gi = bed [ i ] . accn print ( "\t" . join ( ( gi , str ( depth ) ) ) , file = fw ) | Write per gene depth to file |
11,809 | def blast ( self , blastfile = None , outfile = None ) : from jcvi . formats . blast import BlastSlow , BlastLineByConversion if not outfile : outfile = self . filename + ".blast" if blastfile is not None : blasts = BlastSlow ( blastfile ) . to_dict ( ) else : blasts = None fw = must_open ( outfile , "w" , checkexists = True ) nlines = 0 for a , b , id in self . iter_pairs ( ) : if ( a , b ) in blasts : bline = blasts [ ( a , b ) ] elif ( b , a ) in blasts : bline = blasts [ ( b , a ) ] else : line = "\t" . join ( ( a , b ) ) bline = BlastLineByConversion ( line , mode = "110000000000" ) print ( bline , file = fw ) nlines += 1 fw . close ( ) logging . debug ( "A total of {0} BLAST lines written to `{1}`." . format ( nlines , outfile ) ) return outfile | convert anchor file to 12 col blast file |
11,810 | def filter ( args ) : p = OptionParser ( filter . __doc__ ) p . add_option ( "--score" , dest = "score" , default = 0 , type = "int" , help = "Score cutoff" ) p . set_align ( pctid = 95 , hitlen = 100 , evalue = .01 ) p . add_option ( "--noself" , default = False , action = "store_true" , help = "Remove self-self hits" ) p . add_option ( "--ids" , help = "Path to file with ids to retain" ) p . add_option ( "--inverse" , default = False , action = "store_true" , help = "Similar to grep -v, inverse" ) p . set_outfile ( outfile = None ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) if opts . ids : ids = set ( ) for row in must_open ( opts . ids ) : if row [ 0 ] == "#" : continue row = row . replace ( "," , "\t" ) ids . update ( row . split ( ) ) else : ids = None blastfile , = args inverse = opts . inverse outfile = opts . outfile fp = must_open ( blastfile ) score , pctid , hitlen , evalue , noself = opts . score , opts . pctid , opts . hitlen , opts . evalue , opts . noself newblastfile = blastfile + ".P{0}L{1}" . format ( int ( pctid ) , hitlen ) if outfile is None else outfile if inverse : newblastfile += ".inverse" fw = must_open ( newblastfile , "w" ) for row in fp : if row [ 0 ] == '#' : continue c = BlastLine ( row ) if ids : if c . query in ids and c . subject in ids : noids = False else : noids = True else : noids = None remove = c . score < score or c . pctid < pctid or c . hitlen < hitlen or c . evalue > evalue or noids if inverse : remove = not remove remove = remove or ( noself and c . query == c . subject ) if not remove : print ( row . rstrip ( ) , file = fw ) fw . close ( ) return newblastfile | %prog filter test . blast |
11,811 | def collect_gaps ( blast , use_subject = False ) : key = lambda x : x . sstart if use_subject else x . qstart blast . sort ( key = key ) for a , b in zip ( blast , blast [ 1 : ] ) : if use_subject : if a . sstop < b . sstart : yield b . sstart - a . sstop else : if a . qstop < b . qstart : yield b . qstart - a . qstop | Collect the gaps between adjacent HSPs in the BLAST file . |
11,812 | def gaps ( args ) : p = OptionParser ( gaps . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) blastfile , = args blast = BlastSlow ( blastfile ) logging . debug ( "A total of {} records imported" . format ( len ( blast ) ) ) query_gaps = list ( collect_gaps ( blast ) ) subject_gaps = list ( collect_gaps ( blast , use_subject = True ) ) logging . debug ( "Query gaps: {} Subject gaps: {}" . format ( len ( query_gaps ) , len ( subject_gaps ) ) ) from jcvi . graphics . base import savefig import seaborn as sns sns . distplot ( query_gaps ) savefig ( "query_gaps.pdf" ) | %prog gaps A_vs_B . blast |
11,813 | def rbbh ( args ) : p = OptionParser ( rbbh . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) abfile , bafile , = args ab = Blast ( abfile ) ba = Blast ( bafile ) ab_hits = ab . best_hits ba_hits = ba . best_hits for aquery in ab_hits : ahit = ab_hits [ aquery ] . subject ba_bline = ba_hits . get ( ahit ) if ba_bline : bhit = ba_bline . subject if bhit == aquery : print ( "\t" . join ( str ( x ) for x in ( aquery , ahit ) ) ) | %prog rbbh A_vs_B . blast B_vs_A . blast |
11,814 | def score ( args ) : from jcvi . formats . base import SetFile from jcvi . formats . fasta import Fasta p = OptionParser ( score . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) blastfile , fastafile , idsfile = args ids = SetFile ( idsfile ) blast = Blast ( blastfile ) scores = defaultdict ( int ) for b in blast : query = b . query subject = b . subject if subject not in ids : continue scores [ query ] += b . score logging . debug ( "A total of {0} ids loaded." . format ( len ( ids ) ) ) f = Fasta ( fastafile ) for s in f . iterkeys_ordered ( ) : sc = scores . get ( s , 0 ) print ( "\t" . join ( ( s , str ( sc ) ) ) ) | %prog score blastfile query . fasta A . ids |
11,815 | def annotation ( args ) : from jcvi . formats . base import DictFile p = OptionParser ( annotation . __doc__ ) p . add_option ( "--queryids" , help = "Query IDS file to switch [default: %default]" ) p . add_option ( "--subjectids" , help = "Subject IDS file to switch [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) blastfile , = args d = "\t" qids = DictFile ( opts . queryids , delimiter = d ) if opts . queryids else None sids = DictFile ( opts . subjectids , delimiter = d ) if opts . subjectids else None blast = Blast ( blastfile ) for b in blast : query , subject = b . query , b . subject if qids : query = qids [ query ] if sids : subject = sids [ subject ] print ( "\t" . join ( ( query , subject ) ) ) | %prog annotation blastfile > annotations |
11,816 | def completeness ( args ) : from jcvi . utils . range import range_minmax from jcvi . utils . cbook import SummaryStats p = OptionParser ( completeness . __doc__ ) p . add_option ( "--ids" , help = "Save ids that are over 50% complete [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) blastfile , fastafile = args idsfile = opts . ids f = Sizes ( fastafile ) . mapping b = BlastSlow ( blastfile ) valid = [ ] data = [ ] cutoff = 50 for query , blines in groupby ( b , key = lambda x : x . query ) : blines = list ( blines ) ranges = [ ( x . sstart , x . sstop ) for x in blines ] b = blines [ 0 ] query , subject = b . query , b . subject rmin , rmax = range_minmax ( ranges ) subject_len = f [ subject ] nterminal_dist = rmin - 1 cterminal_dist = subject_len - rmax covered = ( rmax - rmin + 1 ) * 100 / subject_len if covered > cutoff : valid . append ( query ) data . append ( ( nterminal_dist , cterminal_dist , covered ) ) print ( "\t" . join ( str ( x ) for x in ( query , subject , nterminal_dist , cterminal_dist , covered ) ) ) nd , cd , cv = zip ( * data ) m = "Total: {0}, Coverage > {1}%: {2}\n" . format ( len ( data ) , cutoff , len ( valid ) ) m += "N-terminal: {0}\n" . format ( SummaryStats ( nd ) ) m += "C-terminal: {0}\n" . format ( SummaryStats ( cd ) ) m += "Coverage: {0}" . format ( SummaryStats ( cv ) ) print ( m , file = sys . stderr ) if idsfile : fw = open ( idsfile , "w" ) print ( "\n" . join ( valid ) , file = fw ) logging . debug ( "A total of {0} ids (cov > {1} %) written to `{2}`." . format ( len ( valid ) , cutoff , idsfile ) ) fw . close ( ) | %prog completeness blastfile ref . fasta > outfile |
11,817 | def annotate ( args ) : from jcvi . assembly . goldenpath import Cutoff , Overlap , Overlap_types p = OptionParser ( annotate . __doc__ ) p . set_align ( pctid = 94 , hitlen = 500 ) p . add_option ( "--hang" , default = 500 , type = "int" , help = "Maximum overhang length" ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) blastfile , afasta , bfasta = args fp = must_open ( blastfile ) asizes = Sizes ( afasta ) . mapping bsizes = Sizes ( bfasta ) . mapping cutoff = Cutoff ( opts . pctid , opts . hitlen , opts . hang ) logging . debug ( str ( cutoff ) ) for row in fp : b = BlastLine ( row ) asize = asizes [ b . query ] bsize = bsizes [ b . subject ] if b . query == b . subject : continue ov = Overlap ( b , asize , bsize , cutoff ) if ov . otype : ov . print_graphic ( ) print ( "{0}\t{1}" . format ( b , Overlap_types [ ov . otype ] ) ) | %prog annotate blastfile query . fasta subject . fasta |
11,818 | def top10 ( args ) : from jcvi . formats . base import DictFile p = OptionParser ( top10 . __doc__ ) p . add_option ( "--top" , default = 10 , type = "int" , help = "Top N taxa to extract [default: %default]" ) p . add_option ( "--ids" , default = None , help = "Two column ids file to query seqid [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) blastfile , = args mapping = DictFile ( opts . ids , delimiter = "\t" ) if opts . ids else { } cmd = "cut -f2 {0}" . format ( blastfile ) cmd += " | sort | uniq -c | sort -k1,1nr | head -n {0}" . format ( opts . top ) fp = popen ( cmd ) for row in fp : count , seqid = row . split ( ) nseqid = mapping . get ( seqid , seqid ) print ( "\t" . join ( ( count , nseqid ) ) ) | %prog top10 blastfile . best |
11,819 | def cscore ( args ) : from jcvi . utils . cbook import gene_name p = OptionParser ( cscore . __doc__ ) p . add_option ( "--cutoff" , default = .9999 , type = "float" , help = "Minimum C-score to report [default: %default]" ) p . add_option ( "--pct" , default = False , action = "store_true" , help = "Also include pct as last column [default: %default]" ) p . add_option ( "--writeblast" , default = False , action = "store_true" , help = "Also write filtered blast file [default: %default]" ) p . set_stripnames ( ) p . set_outfile ( ) opts , args = p . parse_args ( args ) ostrip = opts . strip_names writeblast = opts . writeblast outfile = opts . outfile if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) blastfile , = args blast = Blast ( blastfile ) logging . debug ( "Register best scores .." ) best_score = defaultdict ( float ) for b in blast : query , subject = b . query , b . subject if ostrip : query , subject = gene_name ( query ) , gene_name ( subject ) score = b . score if score > best_score [ query ] : best_score [ query ] = score if score > best_score [ subject ] : best_score [ subject ] = score blast = Blast ( blastfile ) pairs = { } cutoff = opts . cutoff for b in blast : query , subject = b . query , b . subject if ostrip : query , subject = gene_name ( query ) , gene_name ( subject ) score = b . score pctid = b . pctid s = score / max ( best_score [ query ] , best_score [ subject ] ) if s > cutoff : pair = ( query , subject ) if pair not in pairs or s > pairs [ pair ] [ 0 ] : pairs [ pair ] = ( s , pctid , b ) fw = must_open ( outfile , "w" ) if writeblast : fwb = must_open ( outfile + ".filtered.blast" , "w" ) pct = opts . pct for ( query , subject ) , ( s , pctid , b ) in sorted ( pairs . items ( ) ) : args = [ query , subject , "{0:.2f}" . format ( s ) ] if pct : args . append ( "{0:.1f}" . format ( pctid ) ) print ( "\t" . join ( args ) , file = fw ) if writeblast : print ( b , file = fwb ) fw . close ( ) if writeblast : fwb . close ( ) | %prog cscore blastfile > cscoreOut |
11,820 | def get_distance ( a , b , xaxis = True ) : if xaxis : arange = ( "0" , a . qstart , a . qstop , a . orientation ) brange = ( "0" , b . qstart , b . qstop , b . orientation ) else : arange = ( "0" , a . sstart , a . sstop , a . orientation ) brange = ( "0" , b . sstart , b . sstop , b . orientation ) dist , oo = range_distance ( arange , brange , distmode = "ee" ) dist = abs ( dist ) return dist | Returns the distance between two blast HSPs . |
11,821 | def combine_HSPs ( a ) : m = a [ 0 ] if len ( a ) == 1 : return m for b in a [ 1 : ] : assert m . query == b . query assert m . subject == b . subject m . hitlen += b . hitlen m . nmismatch += b . nmismatch m . ngaps += b . ngaps m . qstart = min ( m . qstart , b . qstart ) m . qstop = max ( m . qstop , b . qstop ) m . sstart = min ( m . sstart , b . sstart ) m . sstop = max ( m . sstop , b . sstop ) if m . has_score : m . score += b . score m . pctid = 100 - ( m . nmismatch + m . ngaps ) * 100. / m . hitlen return m | Combine HSPs into a single BlastLine . |
11,822 | def chain ( args ) : p = OptionParser ( chain . __doc__ ) p . add_option ( "--dist" , dest = "dist" , default = 100 , type = "int" , help = "extent of flanking regions to search [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) blastfile , = args dist = opts . dist assert dist > 0 blast = BlastSlow ( blastfile ) logging . debug ( "A total of {} records imported" . format ( len ( blast ) ) ) chained_hsps = chain_HSPs ( blast , xdist = dist , ydist = dist ) logging . debug ( "A total of {} records after chaining" . format ( len ( chained_hsps ) ) ) for b in chained_hsps : print ( b ) | %prog chain blastfile |
11,823 | def condense ( args ) : p = OptionParser ( condense . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) blastfile , = args blast = BlastSlow ( blastfile ) key = lambda x : x . query blast . sort ( key = key ) clusters = [ ] for q , lines in groupby ( blast , key = key ) : lines = list ( lines ) condenser = defaultdict ( list ) for b in lines : condenser [ ( b . subject , b . orientation ) ] . append ( b ) for bs in condenser . values ( ) : clusters . append ( bs ) chained_hsps = [ combine_HSPs ( x ) for x in clusters ] chained_hsps = sorted ( chained_hsps , key = lambda x : ( x . query , - x . score ) ) for b in chained_hsps : print ( b ) | %prog condense blastfile > blastfile . condensed |
11,824 | def mismatches ( args ) : from jcvi . utils . cbook import percentage from jcvi . graphics . histogram import stem_leaf_plot p = OptionParser ( mismatches . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) blastfile , = args data = [ ] matches = 0 b = Blast ( blastfile ) for query , bline in b . iter_best_hit ( ) : mm = bline . nmismatch + bline . ngaps data . append ( mm ) nonzeros = [ x for x in data if x != 0 ] title = "Polymorphic sites: {0}" . format ( percentage ( len ( nonzeros ) , len ( data ) ) ) stem_leaf_plot ( data , 0 , 20 , 20 , title = title ) | %prog mismatches blastfile |
11,825 | def swap ( args ) : p = OptionParser ( swap . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) < 1 : sys . exit ( not p . print_help ( ) ) blastfile , = args swappedblastfile = blastfile + ".swapped" fp = must_open ( blastfile ) fw = must_open ( swappedblastfile , "w" ) for row in fp : b = BlastLine ( row ) print ( b . swapped , file = fw ) fw . close ( ) sort ( [ swappedblastfile ] ) | %prog swap blastfile |
11,826 | def bed ( args ) : from jcvi . formats . bed import sort as bed_sort p = OptionParser ( bed . __doc__ ) p . add_option ( "--swap" , default = False , action = "store_true" , help = "Write query positions [default: %default]" ) p . add_option ( "--both" , default = False , action = "store_true" , help = "Generate one line for each of query and subject" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( p . print_help ( ) ) blastfile , = args positive = ( not opts . swap ) or opts . both negative = opts . swap or opts . both fp = must_open ( blastfile ) bedfile = "{0}.bed" . format ( blastfile . rsplit ( "." , 1 ) [ 0 ] ) if blastfile . endswith ( ".blast" ) else "{0}.bed" . format ( blastfile ) fw = open ( bedfile , "w" ) for row in fp : b = BlastLine ( row ) if positive : print ( b . bedline , file = fw ) if negative : print ( b . swapped . bedline , file = fw ) logging . debug ( "File written to `{0}`." . format ( bedfile ) ) fw . close ( ) bed_sort ( [ bedfile , "-i" ] ) return bedfile | %prog bed blastfile |
11,827 | def best ( args ) : p = OptionParser ( best . __doc__ ) p . add_option ( "-n" , default = 1 , type = "int" , help = "get best N hits [default: %default]" ) p . add_option ( "--nosort" , default = False , action = "store_true" , help = "assume BLAST is already sorted [default: %default]" ) p . add_option ( "--hsps" , default = False , action = "store_true" , help = "get all HSPs for the best pair [default: %default]" ) p . add_option ( "--subject" , default = False , action = "store_true" , help = "get best hit(s) for subject genome instead [default: %default]" ) p . set_tmpdir ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) blastfile , = args n = opts . n hsps = opts . hsps tmpdir = opts . tmpdir ref = "query" if not opts . subject else "subject" if not opts . nosort : sargs = [ blastfile ] if tmpdir : sargs += [ "-T {0}" . format ( tmpdir ) ] if ref != "query" : sargs += [ "--refscore" ] sort ( sargs ) else : logging . debug ( "Assuming sorted BLAST" ) if not opts . subject : bestblastfile = blastfile + ".best" else : bestblastfile = blastfile + ".subject.best" fw = open ( bestblastfile , "w" ) b = Blast ( blastfile ) for q , bline in b . iter_best_hit ( N = n , hsps = hsps , ref = ref ) : print ( bline , file = fw ) return bestblastfile | %prog best blastfile |
11,828 | def summary ( args ) : p = OptionParser ( summary . __doc__ ) p . add_option ( "--strict" , default = False , action = "store_true" , help = "Strict 'gapless' mode. Exclude gaps from covered base." ) p . add_option ( "--tabular" , default = False , action = "store_true" , help = "Print succint tabular output" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) blastfile , = args alignstats = get_stats ( blastfile , strict = opts . strict ) if opts . tabular : print ( str ( alignstats ) ) else : alignstats . print_stats ( ) | %prog summary blastfile |
11,829 | def subset ( args ) : p = OptionParser ( subset . __doc__ ) p . add_option ( "--qchrs" , default = None , help = "query chrs to extract, comma sep [default: %default]" ) p . add_option ( "--schrs" , default = None , help = "subject chrs to extract, comma sep [default: %default]" ) p . add_option ( "--convert" , default = False , action = "store_true" , help = "convert accns to chr_rank [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) blastfile , qbedfile , sbedfile = args qchrs = opts . qchrs schrs = opts . schrs assert qchrs or schrs , p . print_help ( ) convert = opts . convert outfile = blastfile + "." if qchrs : outfile += qchrs + "." qchrs = set ( qchrs . split ( "," ) ) else : qchrs = set ( Bed ( qbedfile ) . seqids ) if schrs : schrs = set ( schrs . split ( "," ) ) if qbedfile != sbedfile or qchrs != schrs : outfile += "," . join ( schrs ) + "." else : schrs = set ( Bed ( sbedfile ) . seqids ) outfile += "blast" qo = Bed ( qbedfile ) . order so = Bed ( sbedfile ) . order fw = must_open ( outfile , "w" ) for b in Blast ( blastfile ) : q , s = b . query , b . subject if qo [ q ] [ 1 ] . seqid in qchrs and so [ s ] [ 1 ] . seqid in schrs : if convert : b . query = qo [ q ] [ 1 ] . seqid + "_" + "{0:05d}" . format ( qo [ q ] [ 0 ] ) b . subject = so [ s ] [ 1 ] . seqid + "_" + "{0:05d}" . format ( so [ s ] [ 0 ] ) print ( b , file = fw ) fw . close ( ) logging . debug ( "Subset blastfile written to `{0}`" . format ( outfile ) ) | %prog subset blastfile qbedfile sbedfile |
11,830 | def flanking ( args ) : p = OptionParser ( flanking . __doc__ ) p . add_option ( "-N" , default = 50 , type = "int" , help = "How many genes on both directions" ) opts , args = p . parse_args ( args ) if len ( args ) != 4 : sys . exit ( not p . print_help ( ) ) SI , liftover , master , te = args N = opts . N SI = SetFile ( SI , column = 0 , delimiter = '.' ) liftover = Bed ( liftover ) order = liftover . order neighbors = set ( ) for s in SI : si , s = order [ s ] LB = max ( si - N , 0 ) RB = min ( si + N , len ( liftover ) ) for j in xrange ( LB , RB + 1 ) : a = liftover [ j ] if a . seqid != s . seqid : continue neighbors . add ( a . accn ) dmain = DictFile ( master , keypos = 0 , valuepos = None , delimiter = '\t' ) dte = DictFile ( te , keypos = 0 , valuepos = None , delimiter = '\t' ) header = next ( open ( master ) ) print ( "\t" . join ( ( "SI/Neighbor" , "Gene/TE" , header . strip ( ) ) ) ) for a in liftover : s = a . accn if s not in neighbors : continue tag = "SI" if s in SI else "neighbor" if s in dmain : d = dmain [ s ] print ( "\t" . join ( [ tag , "gene" ] + d ) ) elif s in dte : d = dte [ s ] print ( "\t" . join ( [ tag , "TE" ] + d ) ) | %prog flanking SI . ids liftover . bed master . txt master - removed . txt |
11,831 | def geneinfo ( args ) : p = OptionParser ( geneinfo . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 5 : sys . exit ( not p . print_help ( ) ) scfbed , liftoverbed , lgbed , note , ipr = args note = DictFile ( note , delimiter = "\t" ) scfbed = Bed ( scfbed ) lgorder = Bed ( lgbed ) . order liftover = Bed ( liftoverbed ) . order header = "Accession Scaffold-position LG-position " "Description Interpro-domain Interpro-description " "GO-term KEGG" . split ( ) ipr = read_interpro ( ipr ) fw_clean = must_open ( "master.txt" , "w" ) fw_removed = must_open ( "master-removed.txt" , "w" ) for fw in ( fw_clean , fw_removed ) : print ( "\t" . join ( header ) , file = fw ) for b in scfbed : accession = b . accn scaffold_position = b . tag if accession in liftover : lg_position = liftover [ accession ] [ - 1 ] . tag else : lg_position = "split" fw = fw_clean if accession in lgorder else fw_removed description = note [ accession ] interpro = interpro_description = go = kegg = "" if accession in ipr : interpro , interpro_description , go , kegg = ipr [ accession ] print ( "\t" . join ( ( accession , scaffold_position , lg_position , description , interpro , interpro_description , go , kegg ) ) , file = fw ) fw . close ( ) | %prog geneinfo pineapple . 20141004 . bed liftover . bed pineapple . 20150413 . bed \ note . txt interproscan . txt |
11,832 | def ploidy ( args ) : p = OptionParser ( ploidy . __doc__ ) p . add_option ( "--switch" , help = "Rename the seqid with two-column file" ) opts , args , iopts = p . set_image_options ( args , figsize = "9x7" ) if len ( args ) != 5 : sys . exit ( not p . print_help ( ) ) seqidsfile , klayout , datafile , bedfile , slayout = args fig = plt . figure ( 1 , ( iopts . w , iopts . h ) ) root = fig . add_axes ( [ 0 , 0 , 1 , 1 ] ) Karyotype ( fig , root , seqidsfile , klayout ) Synteny ( fig , root , datafile , bedfile , slayout , switch = opts . switch ) draw_gene_legend ( root , .27 , .37 , .52 ) fc = 'lightslategrey' x = .09 radius = .012 TextCircle ( root , x , .825 , r'$\tau$' , radius = radius , fc = fc ) TextCircle ( root , x , .8 , r'$\sigma$' , radius = radius , fc = fc ) TextCircle ( root , x , .72 , r'$\rho$' , radius = radius , fc = fc ) for ypos in ( .825 , .8 , .72 ) : root . text ( .12 , ypos , r"$\times2$" , color = fc , ha = "center" , va = "center" ) root . plot ( [ x , x ] , [ .85 , .775 ] , ":" , color = fc , lw = 2 ) root . plot ( [ x , x ] , [ .75 , .675 ] , ":" , color = fc , lw = 2 ) labels = ( ( .04 , .96 , 'A' ) , ( .04 , .54 , 'B' ) ) panel_labels ( root , labels ) root . set_xlim ( 0 , 1 ) root . set_ylim ( 0 , 1 ) root . set_axis_off ( ) pf = "pineapple-karyotype" image_name = pf + "." + iopts . format savefig ( image_name , dpi = iopts . dpi , iopts = iopts ) | %prog ploidy seqids karyotype . layout mcscan . out all . bed synteny . layout |
11,833 | def node_to_edge ( edges , directed = True ) : outgoing = defaultdict ( set ) incoming = defaultdict ( set ) if directed else outgoing nodes = set ( ) for i , edge in enumerate ( edges ) : a , b , = edge [ : 2 ] outgoing [ a ] . add ( i ) incoming [ b ] . add ( i ) nodes . add ( a ) nodes . add ( b ) nodes = sorted ( nodes ) if directed : return outgoing , incoming , nodes return outgoing , nodes | From list of edges record per node incoming and outgoing edges |
11,834 | def resample ( args ) : p = OptionParser ( resample . __doc__ ) opts , args , iopts = p . set_image_options ( args , figsize = "8x4" , dpi = 300 ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) dataA , dataB = args fig = plt . figure ( 1 , ( iopts . w , iopts . h ) ) root = fig . add_axes ( [ 0 , 0 , 1 , 1 ] ) A = fig . add_axes ( [ .1 , .18 , .32 , .64 ] ) B = fig . add_axes ( [ .6 , .18 , .32 , .64 ] ) dataA = import_data ( dataA ) dataB = import_data ( dataB ) xlabel = "Fraction of markers" ylabels = ( "Anchor rate" , "Runtime (m)" ) legend = ( "anchor rate" , "runtime" ) subplot_twinx ( A , dataA , xlabel , ylabels , title = "Yellow catfish" , legend = legend ) subplot_twinx ( B , dataB , xlabel , ylabels , title = "Medicago" , legend = legend ) labels = ( ( .04 , .92 , "A" ) , ( .54 , .92 , "B" ) ) panel_labels ( root , labels ) normalize_axes ( root ) image_name = "resample." + iopts . format savefig ( image_name , dpi = iopts . dpi , iopts = iopts ) | %prog resample yellow - catfish - resample . txt medicago - resample . txt |
11,835 | def resamplestats ( args ) : p = OptionParser ( resamplestats . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) pf , runlog = args fp = open ( runlog ) Real = "real" times = [ ] for row in fp : if not row . startswith ( Real ) : continue tag , time = row . split ( ) assert tag == Real m , s = time . split ( 'm' ) s = s . rstrip ( 's' ) m , s = float ( m ) , float ( s ) time = m + s / 60 times . append ( time ) N = len ( times ) rates = [ ] for i in xrange ( - N + 1 , 1 , 1 ) : summaryfile = "{0}.{1}.summary.txt" . format ( pf , 2 ** i ) fp = open ( summaryfile ) lines = fp . readlines ( ) pct = float ( lines [ - 2 ] . split ( ) [ 3 ] . strip ( "()%" ) ) rates . append ( pct / 100. ) assert len ( rates ) == N print ( "ratio\tanchor-rate\ttime(m)" ) for j , i in enumerate ( xrange ( - N + 1 , 1 , 1 ) ) : print ( "{0}\t{1:.3f}\t{2:.3f}" . format ( i , rates [ j ] , times [ j ] ) ) | %prog resamplestats prefix run . log |
11,836 | def comparebed ( args ) : p = OptionParser ( comparebed . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) abed , bbed = args abed = Bed ( abed ) bbed = Bed ( bbed ) query_links ( abed , bbed ) query_links ( bbed , abed ) | %prog comparebed AP . chr . bed infer . bed |
11,837 | def simulation ( args ) : p = OptionParser ( simulation . __doc__ ) opts , args , iopts = p . set_image_options ( args , dpi = 300 ) if len ( args ) != 4 : sys . exit ( not p . print_help ( ) ) dataA , dataB , dataC , dataD = args fig = plt . figure ( 1 , ( iopts . w , iopts . h ) ) root = fig . add_axes ( [ 0 , 0 , 1 , 1 ] ) A = fig . add_axes ( [ .12 , .62 , .35 , .35 ] ) B = fig . add_axes ( [ .62 , .62 , .35 , .35 ] ) C = fig . add_axes ( [ .12 , .12 , .35 , .35 ] ) D = fig . add_axes ( [ .62 , .12 , .35 , .35 ] ) dataA = import_data ( dataA ) dataB = import_data ( dataB ) dataC = import_data ( dataC ) dataD = import_data ( dataD ) subplot ( A , dataA , "Inversion error rate" , "Accuracy" , xlim = .5 ) subplot ( B , dataB , "Translocation error rate" , "Accuracy" , xlim = .5 , legend = ( "intra-chromosomal" , "inter-chromosomal" , "75\% intra + 25\% inter" ) ) subplot ( C , dataC , "Number of input maps" , "Accuracy" , xcast = int ) subplot ( D , dataD , "Number of input maps" , "Accuracy" , xcast = int ) labels = ( ( .03 , .97 , "A" ) , ( .53 , .97 , "B" ) , ( .03 , .47 , "C" ) , ( .53 , .47 , "D" ) ) panel_labels ( root , labels ) normalize_axes ( root ) image_name = "simulation." + iopts . format savefig ( image_name , dpi = iopts . dpi , iopts = iopts ) | %prog simulation inversion . txt translocation . txt maps . txt multimaps . txt |
11,838 | def digest ( args ) : p = OptionParser ( digest . __doc__ ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) fastafile , enzymes = args enzymes = enzymes . split ( "," ) enzymes = [ x for x in AllEnzymes if str ( x ) in enzymes ] f = Fasta ( fastafile , lazy = True ) fw = must_open ( opts . outfile , "w" ) header = [ "Contig" , "Length" ] + [ str ( x ) for x in enzymes ] print ( "\t" . join ( header ) , file = fw ) for name , rec in f . iteritems_ordered ( ) : row = [ name , len ( rec ) ] for e in enzymes : pos = e . search ( rec . seq ) pos = "na" if not pos else "|" . join ( str ( x ) for x in pos ) row . append ( pos ) print ( "\t" . join ( str ( x ) for x in row ) , file = fw ) | %prog digest fastafile NspI BfuCI |
11,839 | def extract_full ( rec , sites , flank , fw ) : for s in sites : newid = "{0}:{1}" . format ( rec . name , s ) left = max ( s - flank , 0 ) right = min ( s + flank , len ( rec ) ) frag = rec . seq [ left : right ] . strip ( "Nn" ) newrec = SeqRecord ( frag , id = newid , description = "" ) SeqIO . write ( [ newrec ] , fw , "fasta" ) | Full extraction of seq flanking the sites . |
11,840 | def extract_ends ( rec , sites , flank , fw , maxfragsize = 800 ) : nsites = len ( sites ) size = len ( rec ) for i , s in enumerate ( sites ) : newid = "{0}:{1}" . format ( rec . name , s ) recs = [ ] if i == 0 or s - sites [ i - 1 ] <= maxfragsize : newidL = newid + "L" left = max ( s - flank , 0 ) right = s frag = rec . seq [ left : right ] . strip ( "Nn" ) recL = SeqRecord ( frag , id = newidL , description = "" ) if i == 0 and s > maxfragsize : pass else : recs . append ( recL ) if i == nsites - 1 or sites [ i + 1 ] - s <= maxfragsize : newidR = newid + "R" left = s right = min ( s + flank , size ) frag = rec . seq [ left : right ] . strip ( "Nn" ) recR = SeqRecord ( frag , id = newidR , description = "" ) if i == nsites - 1 and size - s > maxfragsize : pass else : recs . append ( recR ) SeqIO . write ( recs , fw , "fasta" ) | Extraction of ends of fragments above certain size . |
11,841 | def fragment ( args ) : p = OptionParser ( fragment . __doc__ ) p . add_option ( "--flank" , default = 150 , type = "int" , help = "Extract flanking bases of the cut sites [default: %default]" ) p . add_option ( "--full" , default = False , action = "store_true" , help = "The full extraction mode [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) fastafile , enzyme = args flank = opts . flank assert flank > 0 extract = extract_full if opts . full else extract_ends tag = "full" if opts . full else "ends" assert enzyme in set ( str ( x ) for x in AllEnzymes ) fragfastafile = fastafile . split ( "." ) [ 0 ] + ".{0}.flank{1}.{2}.fasta" . format ( enzyme , flank , tag ) enzyme = [ x for x in AllEnzymes if str ( x ) == enzyme ] [ 0 ] f = Fasta ( fastafile , lazy = True ) fw = open ( fragfastafile , "w" ) for name , rec in f . iteritems_ordered ( ) : a = Analysis ( [ enzyme ] , rec . seq ) sites = a . full ( ) [ enzyme ] extract ( rec , sites , flank , fw ) logging . debug ( "Fragments written to `{0}`." . format ( fragfastafile ) ) | %prog fragment fastafile enzyme |
11,842 | def calculate_A50 ( ctgsizes , cutoff = 0 , percent = 50 ) : ctgsizes = np . array ( ctgsizes , dtype = "int" ) ctgsizes = np . sort ( ctgsizes ) [ : : - 1 ] ctgsizes = ctgsizes [ ctgsizes >= cutoff ] a50 = np . cumsum ( ctgsizes ) total = np . sum ( ctgsizes ) idx = bisect ( a50 , total * percent / 100. ) l50 = ctgsizes [ idx ] n50 = idx + 1 return a50 , l50 , n50 | Given an array of contig sizes produce A50 N50 and L50 values |
11,843 | def n50 ( args ) : from jcvi . graphics . histogram import loghistogram p = OptionParser ( n50 . __doc__ ) p . add_option ( "--print0" , default = False , action = "store_true" , help = "Print size and L50 to stdout [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) < 1 : sys . exit ( not p . print_help ( ) ) ctgsizes = [ ] probe = open ( args [ 0 ] ) . readline ( ) [ 0 ] isFasta = ( probe == '>' ) if isFasta : for filename in args : f = Fasta ( filename ) ctgsizes += list ( b for a , b in f . itersizes ( ) ) else : for row in must_open ( args ) : try : ctgsize = int ( float ( row . split ( ) [ - 1 ] ) ) except ValueError : continue ctgsizes . append ( ctgsize ) a50 , l50 , nn50 = calculate_A50 ( ctgsizes ) sumsize = sum ( ctgsizes ) minsize = min ( ctgsizes ) maxsize = max ( ctgsizes ) n = len ( ctgsizes ) print ( ", " . join ( args ) , file = sys . stderr ) summary = ( sumsize , l50 , nn50 , minsize , maxsize , n ) print ( " " . join ( "{0}={1}" . format ( a , b ) for a , b in zip ( header , summary ) ) , file = sys . stderr ) loghistogram ( ctgsizes ) if opts . print0 : print ( "\t" . join ( str ( x ) for x in ( "," . join ( args ) , sumsize , l50 ) ) ) return zip ( header , summary ) | %prog n50 filename |
11,844 | def fromovl ( args ) : p = OptionParser ( fromovl . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) ovlfile , fastafile = args ovl = OVL ( ovlfile ) g = ovl . graph fw = open ( "contained.ids" , "w" ) print ( "\n" . join ( sorted ( ovl . contained ) ) , file = fw ) graph_to_agp ( g , ovlfile , fastafile , exclude = ovl . contained , verbose = False ) | %prog graph nucmer2ovl . ovl fastafile |
11,845 | def bed ( args ) : from collections import defaultdict from jcvi . compara . synteny import AnchorFile , check_beds from jcvi . formats . bed import Bed from jcvi . formats . base import get_number p = OptionParser ( bed . __doc__ ) p . add_option ( "--switch" , default = False , action = "store_true" , help = "Switch reference and aligned map elements" ) p . add_option ( "--scale" , type = "float" , help = "Scale the aligned map distance by factor" ) p . set_beds ( ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) anchorsfile , = args switch = opts . switch scale = opts . scale ac = AnchorFile ( anchorsfile ) pairs = defaultdict ( list ) for a , b , block_id in ac . iter_pairs ( ) : pairs [ a ] . append ( b ) qbed , sbed , qorder , sorder , is_self = check_beds ( anchorsfile , p , opts ) bd = Bed ( ) for q in qbed : qseqid , qstart , qend , qaccn = q . seqid , q . start , q . end , q . accn if qaccn not in pairs : continue for s in pairs [ qaccn ] : si , s = sorder [ s ] sseqid , sstart , send , saccn = s . seqid , s . start , s . end , s . accn if switch : qseqid , sseqid = sseqid , qseqid qstart , sstart = sstart , qstart qend , send = send , qend qaccn , saccn = saccn , qaccn if scale : sstart /= scale try : newsseqid = get_number ( sseqid ) except ValueError : raise ValueError ( "`{0}` is on `{1}` with no number to extract" . format ( saccn , sseqid ) ) bedline = "\t" . join ( str ( x ) for x in ( qseqid , qstart - 1 , qend , "{0}:{1}" . format ( newsseqid , sstart ) ) ) bd . add ( bedline ) bd . print_to_file ( filename = opts . outfile , sorted = True ) | %prog bed anchorsfile |
11,846 | def happy_edges ( row , prefix = None ) : trans = maketrans ( "[](){}" , " " ) row = row . strip ( ) . strip ( "+" ) row = row . translate ( trans ) scfs = [ x . strip ( "+" ) for x in row . split ( ":" ) ] for a , b in pairwise ( scfs ) : oa = '<' if a . strip ( ) [ 0 ] == '-' else '>' ob = '<' if b . strip ( ) [ 0 ] == '-' else '>' is_uncertain = a [ - 1 ] == ' ' or b [ 0 ] == ' ' a = a . strip ( ) . strip ( '-' ) b = b . strip ( ) . strip ( '-' ) if prefix : a = prefix + a b = prefix + b yield ( a , b , oa , ob ) , is_uncertain | Convert a row in HAPPY file and yield edges . |
11,847 | def partition ( args ) : allowed_format = ( "png" , "ps" ) p = OptionParser ( partition . __doc__ ) p . add_option ( "--prefix" , help = "Add prefix to the name [default: %default]" ) p . add_option ( "--namestart" , default = 0 , type = "int" , help = "Use a shorter name, starting index [default: %default]" ) p . add_option ( "--format" , default = "png" , choices = allowed_format , help = "Generate image of format [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) happyfile , graphfile = args bg = BiGraph ( ) bg . read ( graphfile , color = "red" ) prefix = opts . prefix fp = open ( happyfile ) for i , row in enumerate ( fp ) : nns = happy_nodes ( row , prefix = prefix ) nodes = set ( nns ) edges = happy_edges ( row , prefix = prefix ) small_graph = BiGraph ( ) for ( a , b , oa , ob ) , is_uncertain in edges : color = "gray" if is_uncertain else "black" small_graph . add_edge ( a , b , oa , ob , color = color ) for ( u , v ) , e in bg . edges . items ( ) : if u in nodes and v in nodes : uv = ( str ( u ) , str ( v ) ) if uv in small_graph . edges : e = small_graph . edges [ uv ] e . color = "blue" else : small_graph . add_edge ( e ) print ( small_graph , file = sys . stderr ) pngfile = "A{0:02d}.{1}" . format ( i + 1 , opts . format ) telomeres = ( nns [ 0 ] , nns [ - 1 ] ) small_graph . draw ( pngfile , namestart = opts . namestart , nodehighlight = telomeres , dpi = 72 ) legend = [ "Edge colors:" ] legend . append ( "[BLUE] Experimental + Synteny" ) legend . append ( "[BLACK] Experimental certain" ) legend . append ( "[GRAY] Experimental uncertain" ) legend . append ( "[RED] Synteny only" ) legend . append ( "Rectangle nodes are telomeres." ) print ( "\n" . join ( legend ) , file = sys . stderr ) | %prog partition happy . txt synteny . graph |
11,848 | def merge ( args ) : p = OptionParser ( merge . __doc__ ) p . add_option ( "--colorlist" , default = "black,red,pink,blue,green" , help = "The color palette [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) < 1 : sys . exit ( not p . print_help ( ) ) colorlist = opts . colorlist . split ( "," ) assert len ( colorlist ) >= len ( args ) , "Need more colors in --colorlist" g = BiGraph ( ) for a , c in zip ( args , colorlist ) : g . read ( a , color = c ) g . draw ( "merged.png" ) | %prog merge graphs |
11,849 | def happy ( args ) : p = OptionParser ( happy . __doc__ ) p . add_option ( "--prefix" , help = "Add prefix to the name [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) happyfile , = args certain = "certain.graph" uncertain = "uncertain.graph" fw1 = open ( certain , "w" ) fw2 = open ( uncertain , "w" ) fp = open ( happyfile ) for row in fp : for e , is_uncertain in happy_edges ( row , prefix = opts . prefix ) : fw = fw2 if is_uncertain else fw1 print ( e , file = fw ) logging . debug ( "Edges written to `{0}`" . format ( "," . join ( ( certain , uncertain ) ) ) ) | %prog happy happy . txt |
11,850 | def fromblast ( args ) : from jcvi . formats . blast import sort from jcvi . utils . range import range_distance p = OptionParser ( fromblast . __doc__ ) p . add_option ( "--clique" , default = False , action = "store_true" , help = "Populate clique instead of linear path [default: %default]" ) p . add_option ( "--maxdist" , default = 100000 , type = "int" , help = "Create edge within certain distance [default: %default]" ) p . set_verbose ( help = "Print verbose reports to stdout" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) blastfile , subjectfasta = args clique = opts . clique maxdist = opts . maxdist sort ( [ blastfile , "--query" ] ) blast = BlastSlow ( blastfile , sorted = True ) g = BiGraph ( ) for query , blines in groupby ( blast , key = lambda x : x . query ) : blines = list ( blines ) iterator = combinations ( blines , 2 ) if clique else pairwise ( blines ) for a , b in iterator : asub , bsub = a . subject , b . subject if asub == bsub : continue arange = ( a . query , a . qstart , a . qstop , "+" ) brange = ( b . query , b . qstart , b . qstop , "+" ) dist , oo = range_distance ( arange , brange , distmode = "ee" ) if dist > maxdist : continue atag = ">" if a . orientation == "+" else "<" btag = ">" if b . orientation == "+" else "<" g . add_edge ( asub , bsub , atag , btag ) graph_to_agp ( g , blastfile , subjectfasta , verbose = opts . verbose ) | %prog fromblast blastfile subject . fasta |
11,851 | def connect ( args ) : p = OptionParser ( connect . __doc__ ) p . add_option ( "--clip" , default = 2000 , type = "int" , help = "Only consider end of contigs [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) fastafile , blastfile = args clip = opts . clip sizes = Sizes ( fastafile ) . mapping blast = Blast ( blastfile ) blasts = [ ] for b in blast : seqid = b . subject size = sizes [ seqid ] start , end = b . sstart , b . sstop cstart , cend = min ( size , clip ) , max ( 0 , size - clip ) if start > cstart and end < cend : continue blasts . append ( b ) key = lambda x : x . query blasts . sort ( key = key ) g = BiGraph ( ) for query , bb in groupby ( blasts , key = key ) : bb = sorted ( bb , key = lambda x : x . qstart ) nsubjects = len ( set ( x . subject for x in bb ) ) if nsubjects == 1 : continue print ( "\n" . join ( str ( x ) for x in bb ) ) for a , b in pairwise ( bb ) : astart , astop = a . qstart , a . qstop bstart , bstop = b . qstart , b . qstop if a . subject == b . subject : continue arange = astart , astop brange = bstart , bstop ov = range_intersect ( arange , brange ) alen = astop - astart + 1 blen = bstop - bstart + 1 if ov : ostart , ostop = ov ov = ostop - ostart + 1 print ( ov , alen , blen ) if ov and ( ov > alen / 2 or ov > blen / 2 ) : print ( "Too much overlap ({0})" . format ( ov ) ) continue asub = a . subject bsub = b . subject atag = ">" if a . orientation == "+" else "<" btag = ">" if b . orientation == "+" else "<" g . add_edge ( asub , bsub , atag , btag ) graph_to_agp ( g , blastfile , fastafile , verbose = False ) | %prog connect assembly . fasta read_mapping . blast |
11,852 | def grasstruth ( args ) : p = OptionParser ( grasstruth . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) james , = args fp = open ( james ) pairs = set ( ) for row in fp : atoms = row . split ( ) genes = [ ] idx = { } for i , a in enumerate ( atoms ) : aa = a . split ( "||" ) for ma in aa : idx [ ma ] = i genes . extend ( aa ) genes = [ x for x in genes if ":" not in x ] Os = [ x for x in genes if x . startswith ( "Os" ) ] for o in Os : for g in genes : if idx [ o ] == idx [ g ] : continue pairs . add ( tuple ( sorted ( ( o , g ) ) ) ) for a , b in sorted ( pairs ) : print ( "\t" . join ( ( a , b ) ) ) | %prog grasstruth james - pan - grass . txt |
11,853 | def cyntenator ( args ) : p = OptionParser ( cyntenator . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) < 2 : sys . exit ( not p . print_help ( ) ) lastfile = args [ 0 ] fp = open ( lastfile ) filteredlastfile = lastfile + ".blast" fw = open ( filteredlastfile , "w" ) for row in fp : b = BlastLine ( row ) if b . query == b . subject : continue print ( "\t" . join ( ( b . query , b . subject , str ( b . score ) ) ) , file = fw ) fw . close ( ) bedfiles = args [ 1 : ] fp = open ( lastfile ) b = BlastLine ( next ( fp ) ) subject = b . subject txtfiles = [ ] for bedfile in bedfiles : order = Bed ( bedfile ) . order if subject in order : db = op . basename ( bedfile ) . split ( "." ) [ 0 ] [ : 20 ] logging . debug ( "Found db: {0}" . format ( db ) ) txtfile = write_txt ( bedfile ) txtfiles . append ( txtfile ) db += ".txt" mm = MakeManager ( ) for txtfile in txtfiles : outfile = txtfile + ".alignment" cmd = 'cyntenator -t "({0} {1})" -h blast {2} > {3}' . format ( txtfile , db , filteredlastfile , outfile ) mm . add ( ( txtfile , db , filteredlastfile ) , outfile , cmd ) mm . write ( ) | %prog cyntenator athaliana . athaliana . last athaliana . bed |
11,854 | def iadhore ( args ) : p = OptionParser ( iadhore . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) < 2 : sys . exit ( not p . print_help ( ) ) lastfile = args [ 0 ] bedfiles = args [ 1 : ] blast_table = "blast_table.txt" fp = open ( lastfile ) seen = set ( ) for row in fp : c = BlastLine ( row ) a , b = c . query , c . subject a , b = gene_name ( a ) , gene_name ( b ) if a > b : a , b = b , a seen . add ( ( a , b ) ) fw = open ( blast_table , "w" ) for a , b in seen : print ( "\t" . join ( ( a , b ) ) , file = fw ) fw . close ( ) logging . debug ( "A total of {0} pairs written to `{1}`" . format ( len ( seen ) , blast_table ) ) fw = open ( "config.txt" , "w" ) for bedfile in bedfiles : pf , stanza = write_lst ( bedfile ) print ( "genome={0}" . format ( pf ) , file = fw ) for seqid , fname in stanza : print ( " " . join ( ( seqid , fname ) ) , file = fw ) print ( file = fw ) print ( "blast_table={0}" . format ( blast_table ) , file = fw ) print ( "cluster_type=colinear" , file = fw ) print ( "tandem_gap=10" , file = fw ) print ( "prob_cutoff=0.001" , file = fw ) print ( "gap_size=20" , file = fw ) print ( "cluster_gap=20" , file = fw ) print ( "q_value=0.9" , file = fw ) print ( "anchor_points=4" , file = fw ) print ( "alignment_method=gg2" , file = fw ) print ( "max_gaps_in_alignment=20" , file = fw ) print ( "output_path=i-adhore_out" , file = fw ) print ( "number_of_threads=4" , file = fw ) fw . close ( ) | %prog iadhore athaliana . athaliana . last athaliana . bed |
11,855 | def athalianatruth ( args ) : p = OptionParser ( athalianatruth . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) atxt , bctxt = args g = Grouper ( ) pairs = set ( ) for txt in ( atxt , bctxt ) : extract_groups ( g , pairs , txt ) fw = open ( "pairs" , "w" ) for pair in sorted ( pairs ) : print ( "\t" . join ( pair ) , file = fw ) fw . close ( ) fw = open ( "groups" , "w" ) for group in list ( g ) : print ( "," . join ( group ) , file = fw ) fw . close ( ) | %prog athalianatruth J_a . txt J_bc . txt |
11,856 | def mcscanx ( args ) : p = OptionParser ( mcscanx . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) < 2 : sys . exit ( not p . print_help ( ) ) blastfile = args [ 0 ] bedfiles = args [ 1 : ] prefix = "_" . join ( op . basename ( x ) [ : 2 ] for x in bedfiles ) symlink ( blastfile , prefix + ".blast" ) allbedfile = prefix + ".gff" fw = open ( allbedfile , "w" ) for i , bedfile in enumerate ( bedfiles ) : prefix = chr ( ord ( 'A' ) + i ) make_gff ( bedfile , prefix , fw ) fw . close ( ) | %prog mcscanx athaliana . athaliana . last athaliana . bed |
11,857 | def grass ( args ) : p = OptionParser ( grass . _doc__ ) p . set_verbose ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) master , james = args fp = open ( master ) next ( fp ) master_store = defaultdict ( set ) for row in fp : atoms = row . split ( ) s = set ( ) for x in atoms [ 1 : 6 ] : m = x . split ( "," ) s |= set ( m ) if '-' in s : s . remove ( '-' ) a = atoms [ 1 ] master_store [ a ] |= set ( s ) fp = open ( james ) next ( fp ) james_store = { } tandems = set ( ) for row in fp : atoms = row . split ( ) s = set ( ) Os = set ( ) for x in atoms [ : - 1 ] : m = x . split ( "||" ) if m [ 0 ] . startswith ( "Os" ) : Os |= set ( m ) if m [ 0 ] . startswith ( "http" ) : continue if m [ 0 ] . startswith ( "chr" ) : m = [ "proxy" ] if "||" in x : tandems |= set ( m ) s |= set ( m ) for x in Os : james_store [ x ] = s jaccards = [ ] corr_jaccards = [ ] perfect_matches = 0 corr_perfect_matches = 0 for k , v in james_store . items ( ) : if k not in master_store : continue m = master_store [ k ] jaccard = len ( v & m ) * 100 / len ( v | m ) jaccards . append ( jaccard ) diff = ( v ^ m ) - tandems corr_jaccard = 100 - len ( diff ) * 100 / len ( v | m ) corr_jaccards . append ( corr_jaccard ) if opts . verbose : print ( k ) print ( v ) print ( m ) print ( diff ) print ( jaccard ) if jaccard > 99 : perfect_matches += 1 if corr_jaccard > 99 : corr_perfect_matches += 1 logging . debug ( "Perfect matches: {0}" . format ( perfect_matches ) ) logging . debug ( "Perfect matches (corrected): {0}" . format ( corr_perfect_matches ) ) print ( "Jaccards:" , SummaryStats ( jaccards ) ) print ( "Corrected Jaccards:" , SummaryStats ( corr_jaccards ) ) | %prog grass coge_master_table . txt james . txt |
11,858 | def ecoli ( args ) : p = OptionParser ( ecoli . __doc__ ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) master , querybed = args fp = open ( master ) header = next ( fp ) assert header [ 0 ] == '#' qorg = header . strip ( ) . split ( "\t" ) [ 1 ] qorg = qorg . split ( ":" ) [ - 1 ] . strip ( ) store = { } MISSING = ( "proxy" , "-" ) for row in fp : a , b , c = row . strip ( ) . split ( "\t" ) [ 1 : 4 ] store [ a ] = b in MISSING and c in MISSING bed = Bed ( querybed ) tags = [ ] for i , b in enumerate ( bed ) : accn = b . accn if accn not in store : logging . warn ( "missing {0}" . format ( accn ) ) continue tags . append ( ( store [ accn ] , accn ) ) large = 4 II = [ ] II_large = [ ] for missing , aa in groupby ( tags , key = lambda x : x [ 0 ] ) : aa = list ( aa ) if not missing : continue glist = list ( a for missing , a in aa ) II . append ( glist ) size = len ( glist ) if size >= large : II_large . append ( glist ) fw = must_open ( opts . outfile , "w" ) for a , t in zip ( ( II , II_large ) , ( "" , ">=4 " ) ) : nmissing = sum ( len ( x ) for x in a ) logging . debug ( "A total of {0} {1}-specific {2}islands found with {3} genes." . format ( len ( a ) , qorg , t , nmissing ) ) for x in II : print ( len ( x ) , "," . join ( x ) , file = fw ) | %prog ecoli coge_master_table . txt query . bed |
11,859 | def parallel ( args ) : from jcvi . formats . base import split p = OptionParser ( parallel . __doc__ ) p . set_home ( "maker" ) p . set_tmpdir ( tmpdir = "tmp" ) p . set_grid_opts ( array = True ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) genome , NN = args threaded = opts . threaded or 1 tmpdir = opts . tmpdir mkdir ( tmpdir ) tmpdir = get_abs_path ( tmpdir ) N = int ( NN ) assert 1 <= N < 1000 , "Required: 1 < N < 1000!" outdir = "outdir" fs = split ( [ genome , outdir , NN ] ) c = CTLFile ( "maker_opts.ctl" ) c . update_abs_path ( ) if threaded > 1 : c . update_tag ( "cpus" , threaded ) cwd = os . getcwd ( ) dirs = [ ] for name in fs . names : fn = get_abs_path ( name ) bn = op . basename ( name ) dirs . append ( bn ) c . update_tag ( "genome" , fn ) mkdir ( bn ) sh ( "cp *.ctl {0}" . format ( bn ) ) os . chdir ( bn ) c . write_file ( "maker_opts.ctl" ) os . chdir ( cwd ) jobs = "jobs" fw = open ( jobs , "w" ) print ( "\n" . join ( dirs ) , file = fw ) fw . close ( ) ncmds = len ( dirs ) runfile = "array.sh" cmd = op . join ( opts . maker_home , "bin/maker" ) if tmpdir : cmd += " -TMP {0}" . format ( tmpdir ) engine = get_grid_engine ( ) contents = arraysh . format ( jobs , cmd ) if engine == "SGE" else arraysh_ua . format ( N , threaded , jobs , cmd ) write_file ( runfile , contents ) if engine == "PBS" : return outfile = "maker.\$TASK_ID.out" p = GridProcess ( runfile , outfile = outfile , errfile = outfile , arr = ncmds , grid_opts = opts ) qsubfile = "qsub.sh" qsub = p . build ( ) write_file ( qsubfile , qsub ) | %prog parallel genome . fasta N |
11,860 | def merge ( args ) : from jcvi . formats . gff import merge as gmerge p = OptionParser ( merge . __doc__ ) p . set_home ( "maker" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) outdir , outputgff = args fsnames , suffix = get_fsnames ( outdir ) nfs = len ( fsnames ) cmd = op . join ( opts . maker_home , "bin/gff3_merge" ) outfile = "merge.sh" write_file ( outfile , mergesh . format ( suffix , cmd ) ) sh ( "parallel -j 8 merge.sh {} ::: " + " " . join ( fsnames ) ) gffnames = glob ( "*.all.gff" ) assert len ( gffnames ) == nfs gfflist = "gfflist" fw = open ( gfflist , "w" ) print ( "\n" . join ( gffnames ) , file = fw ) fw . close ( ) nlines = sum ( 1 for x in open ( gfflist ) ) assert nlines == nfs gmerge ( [ gfflist , "-o" , outputgff ] ) logging . debug ( "Merged GFF file written to `{0}`" . format ( outputgff ) ) | %prog merge outdir output . gff |
11,861 | def validate ( args ) : from jcvi . utils . counter import Counter p = OptionParser ( validate . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) outdir , genome = args counter = Counter ( ) fsnames , suffix = get_fsnames ( outdir ) dsfile = "{0}{1}/{0}.maker.output/{0}_master_datastore_index.log" dslogs = [ dsfile . format ( x , suffix ) for x in fsnames ] all_failed = [ ] for f , d in zip ( fsnames , dslogs ) : dslog = DatastoreIndexFile ( d ) counter . update ( dslog . scaffold_status . values ( ) ) all_failed . extend ( [ ( f , x ) for x in dslog . failed ] ) cmd = 'tail maker.*.out | grep -c "now finished"' n = int ( popen ( cmd ) . read ( ) ) assert len ( fsnames ) == n print ( "ALL jobs have been finished" , file = sys . stderr ) nfailed = len ( all_failed ) if nfailed == 0 : print ( "ALL scaffolds are completed with no errors" , file = sys . stderr ) return print ( "Scaffold status:" , file = sys . stderr ) print ( counter , file = sys . stderr ) failed = "FAILED" fw = open ( failed , "w" ) print ( "\n" . join ( [ "\t" . join ( ( f , x ) ) for f , x in all_failed ] ) , file = fw ) fw . close ( ) nlines = sum ( 1 for x in open ( "FAILED" ) ) assert nlines == nfailed print ( "FAILED !! {0} instances." . format ( nfailed ) , file = sys . stderr ) failed_ids = failed + ".ids" failed_fasta = failed + ".fasta" cmd = "cut -f2 {0}" . format ( failed ) sh ( cmd , outfile = failed_ids ) if need_update ( ( genome , failed_ids ) , failed_fasta ) : cmd = "faSomeRecords {0} {1} {2}" . format ( genome , failed_ids , failed_fasta ) sh ( cmd ) | %prog validate outdir genome . fasta |
11,862 | def batcheval ( args ) : from jcvi . formats . bed import evaluate from jcvi . formats . gff import make_index p = OptionParser ( evaluate . __doc__ ) p . add_option ( "--type" , default = "CDS" , help = "list of features to extract, use comma to separate (e.g." "'five_prime_UTR,CDS,three_prime_UTR') [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 4 : sys . exit ( not p . print_help ( ) ) model_ids , gff_file , evidences_bed , fastafile = args type = set ( opts . type . split ( "," ) ) g = make_index ( gff_file ) fp = open ( model_ids ) prefix = model_ids . rsplit ( "." , 1 ) [ 0 ] fwscores = open ( prefix + ".scores" , "w" ) for row in fp : cid = row . strip ( ) b = next ( g . parents ( cid , 1 ) ) query = "{0}:{1}-{2}" . format ( b . chrom , b . start , b . stop ) children = [ c for c in g . children ( cid , 1 ) ] cidbed = prefix + ".bed" fw = open ( cidbed , "w" ) for c in children : if c . featuretype not in type : continue fw . write ( c . to_bed ( ) ) fw . close ( ) b = evaluate ( [ cidbed , evidences_bed , fastafile , "--query={0}" . format ( query ) ] ) print ( "\t" . join ( ( cid , b . score ) ) , file = fwscores ) fwscores . flush ( ) | %prog batcheval model . ids gff_file evidences . bed fastafile |
11,863 | def get_splits ( split_bed , gff_file , stype , key ) : bed_file = get_bed_file ( gff_file , stype , key ) cmd = "intersectBed -a {0} -b {1} -wao" . format ( split_bed , bed_file ) cmd += " | cut -f4,10" p = popen ( cmd ) splits = defaultdict ( set ) for row in p : a , b = row . split ( ) splits [ a ] . add ( b ) return splits | Use intersectBed to find the fused gene = > split genes mappings . |
11,864 | def split ( args ) : from jcvi . formats . bed import Bed p = OptionParser ( split . __doc__ ) p . add_option ( "--key" , default = "Name" , help = "Key in the attributes to extract predictor.gff [default: %default]" ) p . add_option ( "--parents" , default = "match" , help = "list of features to extract, use comma to separate (e.g." "'gene,mRNA') [default: %default]" ) p . add_option ( "--children" , default = "match_part" , help = "list of features to extract, use comma to separate (e.g." "'five_prime_UTR,CDS,three_prime_UTR') [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 5 : sys . exit ( not p . print_help ( ) ) split_bed , evidences_bed , p1_gff , p2_gff , fastafile = args parents = opts . parents children = opts . children key = opts . key bed = Bed ( split_bed ) s1 = get_splits ( split_bed , p1_gff , parents , key ) s2 = get_splits ( split_bed , p2_gff , parents , key ) for b in bed : query = "{0}:{1}-{2}" . format ( b . seqid , b . start , b . end ) b1 = get_accuracy ( query , p1_gff , evidences_bed , fastafile , children , key ) b2 = get_accuracy ( query , p2_gff , evidences_bed , fastafile , children , key ) accn = b . accn c1 = "|" . join ( s1 [ accn ] ) c2 = "|" . join ( s2 [ accn ] ) ac1 = b1 . accuracy ac2 = b2 . accuracy tag = p1_gff if ac1 >= ac2 else p2_gff tag = tag . split ( "." ) [ 0 ] ac1 = "{0:.3f}" . format ( ac1 ) ac2 = "{0:.3f}" . format ( ac2 ) print ( "\t" . join ( ( accn , tag , ac1 , ac2 , c1 , c2 ) ) ) | %prog split split . bed evidences . bed predictor1 . gff predictor2 . gff fastafile |
11,865 | def datastore ( args ) : p = OptionParser ( datastore . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) ds , = args fp = open ( ds ) for row in fp : fn = row . strip ( ) assert op . exists ( fn ) pp , logfile = op . split ( fn ) flog = open ( fn ) for row in flog : ctg , folder , status = row . split ( ) if status != "FINISHED" : continue gff_file = op . join ( pp , folder , ctg + ".gff" ) assert op . exists ( gff_file ) print ( gff_file ) | %prog datastore datastore . log > gfflist . log |
11,866 | def libsvm ( args ) : from jcvi . formats . base import DictFile p = OptionParser ( libsvm . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) csvfile , prefixids = args d = DictFile ( prefixids ) fp = open ( csvfile ) next ( fp ) for row in fp : atoms = row . split ( ) klass = atoms [ 0 ] kp = klass . split ( "_" ) [ 0 ] klass = d . get ( kp , "0" ) feats = [ "{0}:{1}" . format ( i + 1 , x ) for i , x in enumerate ( atoms [ 1 : ] ) ] print ( " " . join ( [ klass ] + feats ) ) | %prog libsvm csvfile prefix . ids |
11,867 | def determine_positions ( nodes , edges ) : N = len ( nodes ) E = len ( edges ) A = np . zeros ( ( E , N ) , dtype = int ) for i , ( a , b , distance ) in enumerate ( edges ) : A [ i , a ] = 1 A [ i , b ] = - 1 K = np . eye ( E , dtype = int ) L = np . array ( [ x [ - 1 ] for x in edges ] ) s = spring_system ( A , K , L ) return np . array ( [ 0 ] + [ int ( round ( x , 0 ) ) for x in s ] ) | Construct the problem instance to solve the positions of contigs . |
11,868 | def determine_signs ( nodes , edges , cutoff = 1e-10 ) : N = len ( nodes ) M = np . zeros ( ( N , N ) , dtype = float ) for a , b , w in edges : M [ a , b ] += w M = symmetrize ( M ) return get_signs ( M , cutoff = cutoff , validate = False ) | Construct the orientation matrix for the pairs on N molecules . |
11,869 | def fix ( args ) : p = OptionParser ( fix . __doc__ ) p . add_option ( "--ignore_sym_pat" , default = False , action = "store_true" , help = "Do not fix names matching symbol patterns i.e." + " names beginning or ending with gene symbols or a series of numbers." + " e.g. `ARM repeat superfamily protein`, `beta-hexosaminidase 3`," + " `CYCLIN A3;4`, `WALL ASSOCIATED KINASE (WAK)-LIKE 10`" ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) < 1 : sys . exit ( not p . print_help ( ) ) csvfile , = args fp = open ( csvfile ) fw = must_open ( opts . outfile , "w" ) for row in fp : if row [ 0 ] == '#' : continue if row . strip ( ) == "" : continue atoms = row . rstrip ( "\r\n" ) . split ( "\t" ) name , hit , ahrd_code , desc = atoms [ : 4 ] if len ( atoms ) > 2 else ( atoms [ 0 ] , None , None , atoms [ - 1 ] ) newdesc = fix_text ( desc , ignore_sym_pat = opts . ignore_sym_pat ) if hit and hit . strip ( ) != "" and newdesc == Hypothetical : newdesc = "conserved " + newdesc print ( "\t" . join ( atoms [ : 4 ] + [ newdesc ] + atoms [ 4 : ] ) , file = fw ) | %prog fix ahrd . csv > ahrd . fixed . csv |
11,870 | def batch ( args ) : p = OptionParser ( batch . __doc__ ) ahrd_weights = { "blastp" : [ 0.5 , 0.3 , 0.2 ] , "blastx" : [ 0.6 , 0.4 , 0.0 ] } blast_progs = tuple ( ahrd_weights . keys ( ) ) p . add_option ( "--path" , default = "~/code/AHRD/" , help = "Path where AHRD is installed [default: %default]" ) p . add_option ( "--blastprog" , default = "blastp" , choices = blast_progs , help = "Specify the blast program being run. Based on this option," + " the AHRD parameters (score_weights) will be modified." + " [default: %default]" ) p . add_option ( "--iprscan" , default = None , help = "Specify path to InterProScan results file if available." + " If specified, the yml conf file will be modified" + " appropriately. [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) splits , output = args mkdir ( output ) bit_score , db_score , ovl_score = ahrd_weights [ opts . blastprog ] for f in glob ( "{0}/*.fa*" . format ( splits ) ) : fb = op . basename ( f ) . rsplit ( "." , 1 ) [ 0 ] fw = open ( op . join ( output , fb + ".yml" ) , "w" ) path = op . expanduser ( opts . path ) dir = op . join ( path , "test/resources" ) outfile = op . join ( output , fb + ".csv" ) interpro = iprscanTemplate . format ( opts . iprscan ) if opts . iprscan else "" print ( Template . format ( dir , fb , f , outfile , bit_score , db_score , ovl_score , interpro ) , file = fw ) if opts . iprscan : if not op . lexists ( "interpro.xml" ) : symlink ( op . join ( iprscan_datadir , "interpro.xml" ) , "interpro.xml" ) if not op . lexists ( "interpro.dtd" ) : symlink ( op . join ( iprscan_datadir , "interpro.dtd" ) , "interpro.dtd" ) | %prog batch splits output |
11,871 | def to_range ( obj , score = None , id = None , strand = None ) : from jcvi . utils . range import Range if score or id : _score = score if score else obj . score _id = id if id else obj . id return Range ( seqid = obj . seqid , start = obj . start , end = obj . end , score = _score , id = _id ) elif strand : return ( obj . seqid , obj . start , obj . end , obj . strand ) return ( obj . seqid , obj . start , obj . end ) | Given a gffutils object convert it to a range object |
11,872 | def sizes ( args ) : p = OptionParser ( sizes . __doc__ ) p . set_outfile ( ) p . add_option ( "--parents" , dest = "parents" , default = "mRNA" , help = "parent feature(s) for which size is to be calculated" ) p . add_option ( "--child" , dest = "child" , default = "CDS" , help = "child feature to use for size calculations" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) gffile , = args parents , cftype = set ( opts . parents . split ( "," ) ) , opts . child gff = make_index ( gffile ) fw = must_open ( opts . outfile , "w" ) for parent in parents : for feat in gff . features_of_type ( parent , order_by = ( 'seqid' , 'start' ) ) : fsize = 0 fsize = feat . end - feat . start + 1 if cftype == parent else gff . children_bp ( feat , child_featuretype = cftype ) print ( "\t" . join ( str ( x ) for x in ( feat . id , fsize ) ) , file = fw ) fw . close ( ) | %prog sizes gffile |
11,873 | def summary ( args ) : from jcvi . formats . base import SetFile from jcvi . formats . bed import BedSummary from jcvi . utils . table import tabulate p = OptionParser ( summary . __doc__ ) p . add_option ( "--isoform" , default = False , action = "store_true" , help = "Find longest isoform of each id" ) p . add_option ( "--ids" , help = "Only include features from certain IDs" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) gff_file , = args ids = opts . ids if ids : ids = SetFile ( ids ) logging . debug ( "Total ids loaded: {0}" . format ( len ( ids ) ) ) if opts . isoform : pids = set ( ) gff = Gff ( gff_file ) for g in gff : if g . type != "mRNA" : continue if g . parent not in ids : continue if "longest" not in g . attributes : pids = set ( x + ".1" for x in ids ) break if g . attributes [ "longest" ] [ 0 ] == "0" : continue pids . add ( g . id ) ids = pids logging . debug ( "After checking longest: {0}" . format ( len ( ids ) ) ) gff = Gff ( gff_file ) for g in gff : if g . name in ids : ids . add ( g . id ) logging . debug ( "Total ids including aliases: {0}" . format ( len ( ids ) ) ) gff = Gff ( gff_file ) beds = defaultdict ( list ) for g in gff : if ids and not ( g . id in ids or g . name in ids or g . parent in ids ) : continue beds [ g . type ] . append ( g . bedline ) table = { } for type , bb in sorted ( beds . items ( ) ) : bs = BedSummary ( bb ) table [ ( type , "Features" ) ] = bs . nfeats table [ ( type , "Unique bases" ) ] = bs . unique_bases table [ ( type , "Total bases" ) ] = bs . total_bases print ( tabulate ( table ) , file = sys . stdout ) | %prog summary gffile |
11,874 | def gb ( args ) : from Bio . Alphabet import generic_dna try : from BCBio import GFF except ImportError : print ( "You need to install dep first: $ easy_install bcbio-gff" , file = sys . stderr ) p = OptionParser ( gb . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) gff_file , fasta_file = args pf = op . splitext ( gff_file ) [ 0 ] out_file = pf + ".gb" fasta_input = SeqIO . to_dict ( SeqIO . parse ( fasta_file , "fasta" , generic_dna ) ) gff_iter = GFF . parse ( gff_file , fasta_input ) SeqIO . write ( gff_iter , out_file , "genbank" ) | %prog gb gffile fastafile |
11,875 | def orient ( args ) : from jcvi . formats . fasta import longestorf p = OptionParser ( orient . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) ingff3 , fastafile = args idsfile = fastafile . rsplit ( "." , 1 ) [ 0 ] + ".orf.ids" if need_update ( fastafile , idsfile ) : longestorf ( [ fastafile , "--ids" ] ) orientations = DictFile ( idsfile ) gff = Gff ( ingff3 ) flipped = 0 for g in gff : id = None for tag in ( "ID" , "Parent" ) : if tag in g . attributes : id , = g . attributes [ tag ] break assert id orientation = orientations . get ( id , "+" ) if orientation == '-' : g . strand = { "+" : "-" , "-" : "+" } [ g . strand ] flipped += 1 print ( g ) logging . debug ( "A total of {0} features flipped." . format ( flipped ) ) | %prog orient in . gff3 features . fasta > out . gff3 |
11,876 | def rename ( args ) : p = OptionParser ( rename . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) ingff3 , switch = args switch = DictFile ( switch ) gff = Gff ( ingff3 ) for g in gff : id , = g . attributes [ "ID" ] newname = switch . get ( id , id ) g . attributes [ "ID" ] = [ newname ] if "Parent" in g . attributes : parents = g . attributes [ "Parent" ] g . attributes [ "Parent" ] = [ switch . get ( x , x ) for x in parents ] g . update_attributes ( ) print ( g ) | %prog rename in . gff3 switch . ids > reindexed . gff3 |
11,877 | def parents ( args ) : p = OptionParser ( parents . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) gff_file , idsfile = args g = make_index ( gff_file ) fp = open ( idsfile ) for row in fp : cid = row . strip ( ) b = next ( g . parents ( cid , 1 ) ) print ( "\t" . join ( ( cid , b . id ) ) ) | %prog parents gffile models . ids |
11,878 | def liftover ( args ) : p = OptionParser ( liftover . __doc__ ) p . add_option ( "--tilesize" , default = 50000 , type = "int" , help = "The size for each tile [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) gffile , = args gff = Gff ( gffile ) for g in gff : seqid = g . seqid seqid , tilenum = seqid . rsplit ( "." , 1 ) tilenum = int ( tilenum ) g . seqid = seqid offset = tilenum * opts . tilesize g . start += offset g . end += offset print ( g ) | %prog liftover gffile > liftover . gff |
11,879 | def get_piles ( allgenes ) : from jcvi . utils . range import Range , range_piles ranges = [ Range ( a . seqid , a . start , a . end , 0 , i ) for i , a in enumerate ( allgenes ) ] for pile in range_piles ( ranges ) : yield [ allgenes [ x ] for x in pile ] | Before running uniq we need to compute all the piles . The piles are a set of redundant features we want to get rid of . Input are a list of GffLines features . Output are list of list of features distinct piles . |
11,880 | def match_subfeats ( f1 , f2 , dbx1 , dbx2 , featuretype = None , slop = False ) : f1c , f2c = list ( dbx1 . children ( f1 , featuretype = featuretype , order_by = 'start' ) ) , list ( dbx2 . children ( f2 , featuretype = featuretype , order_by = 'start' ) ) lf1c , lf2c = len ( f1c ) , len ( f2c ) if match_nchildren ( f1c , f2c ) : if lf1c > 0 and lf2c > 0 : exclN = set ( ) if featuretype . endswith ( 'UTR' ) or featuretype == 'exon' : N = [ ] if featuretype . startswith ( 'five_prime' ) : N = [ 1 ] if f1 . strand == "+" else [ lf1c ] elif featuretype . startswith ( 'three_prime' ) : N = [ lf1c ] if f1 . strand == "+" else [ 1 ] else : N = [ 1 ] if 1 == lf1c else [ 1 , lf1c ] for n in N : if match_Nth_child ( f1c , f2c , N = n , slop = slop ) : exclN . add ( n - 1 ) else : return False for i , ( cf1 , cf2 ) in enumerate ( zip ( f1c , f2c ) ) : if i in exclN : continue if not match_span ( cf1 , cf2 ) : return False else : if ( lf1c , lf2c ) in [ ( 0 , 1 ) , ( 1 , 0 ) ] and slop and featuretype . endswith ( 'UTR' ) : return True return False return True | Given 2 gffutils features located in 2 separate gffutils databases iterate through all subfeatures of a certain type and check whether they are identical or not |
11,881 | def uniq ( args ) : supported_modes = ( "span" , "score" ) p = OptionParser ( uniq . __doc__ ) p . add_option ( "--type" , default = "gene" , help = "Types of features to non-redundify [default: %default]" ) p . add_option ( "--mode" , default = "span" , choices = supported_modes , help = "Pile mode [default: %default]" ) p . add_option ( "--best" , default = 1 , type = "int" , help = "Use best N features [default: %default]" ) p . add_option ( "--name" , default = False , action = "store_true" , help = "Non-redundify Name attribute [default: %default]" ) p . add_option ( "--iter" , default = "2" , choices = ( "1" , "2" ) , help = "Number of iterations to grab children [default: %default]" ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) gffile , = args mode = opts . mode bestn = opts . best allgenes = import_feats ( gffile , opts . type ) g = get_piles ( allgenes ) bestids = set ( ) for group in g : if mode == "span" : scores_group = [ ( - x . span , x ) for x in group ] else : scores_group = [ ( - float ( x . score ) , x ) for x in group ] scores_group . sort ( ) seen = set ( ) for score , x in scores_group : if len ( seen ) >= bestn : break name = x . attributes [ "Name" ] [ 0 ] if opts . name else x . accn if name in seen : continue seen . add ( name ) bestids . add ( x . accn ) populate_children ( opts . outfile , bestids , gffile , iter = opts . iter ) | %prog uniq gffile > uniq . gff |
11,882 | def sort ( args ) : valid_sort_methods = ( "unix" , "topo" ) p = OptionParser ( sort . __doc__ ) p . add_option ( "--method" , default = "unix" , choices = valid_sort_methods , help = "Specify sort method [default: %default]" ) p . add_option ( "-i" , dest = "inplace" , default = False , action = "store_true" , help = "If doing a unix sort, perform sort inplace [default: %default]" ) p . set_tmpdir ( ) p . set_outfile ( ) p . set_home ( "gt" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) gffile , = args sortedgff = opts . outfile if opts . inplace : if opts . method == "topo" or ( opts . method == "unix" and gffile in ( "-" , "stdin" ) ) : logging . error ( "Cannot perform inplace sort when method is `topo`" + " or method is `unix` and input is `stdin` stream" ) sys . exit ( ) if opts . method == "unix" : cmd = "sort" cmd += " -k1,1 -k4,4n {0}" . format ( gffile ) if opts . tmpdir : cmd += " -T {0}" . format ( opts . tmpdir ) if opts . inplace : cmd += " -o {0}" . gffile sortedgff = None sh ( cmd , outfile = sortedgff ) elif opts . method == "topo" : GT_HOME = opts . gt_home if not op . isdir ( GT_HOME ) : logging . error ( "GT_HOME={0} directory does not exist" . format ( GT_HOME ) ) sys . exit ( ) cmd = "{0}" . format ( op . join ( GT_HOME , "bin" , "gt" ) ) cmd += " gff3 -sort -tidy -retainids -addids no {0}" . format ( gffile ) sh ( cmd , outfile = sortedgff ) | %prog sort gffile |
11,883 | def fromgtf ( args ) : p = OptionParser ( fromgtf . __doc__ ) p . add_option ( "--transcript_id" , default = "transcript_id" , help = "Field name for transcript [default: %default]" ) p . add_option ( "--gene_id" , default = "gene_id" , help = "Field name for gene [default: %default]" ) p . add_option ( "--augustus" , default = False , action = "store_true" , help = "Input is AUGUSTUS gtf [default: %default]" ) p . set_home ( "augustus" ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) gtffile , = args outfile = opts . outfile if opts . augustus : ahome = opts . augustus_home s = op . join ( ahome , "scripts/gtf2gff.pl" ) cmd = "{0} --gff3 < {1} --out={2}" . format ( s , gtffile , outfile ) sh ( cmd ) return gff = Gff ( gtffile ) fw = must_open ( outfile , "w" ) transcript_id = opts . transcript_id gene_id = opts . gene_id nfeats = 0 for g in gff : if g . type in ( "transcript" , "mRNA" ) : g . type = "mRNA" g . update_tag ( transcript_id , "ID" ) g . update_tag ( "mRNA" , "ID" ) g . update_tag ( gene_id , "Parent" ) g . update_tag ( "Gene" , "Parent" ) elif g . type in ( "exon" , "CDS" ) or "UTR" in g . type : g . update_tag ( "transcript_id" , "Parent" ) g . update_tag ( g . type , "Parent" ) elif g . type == "gene" : g . update_tag ( gene_id , "ID" ) g . update_tag ( "Gene" , "ID" ) else : assert 0 , "Don't know how to deal with {0}" . format ( g . type ) g . update_attributes ( ) print ( g , file = fw ) nfeats += 1 logging . debug ( "A total of {0} features written." . format ( nfeats ) ) | %prog fromgtf gtffile |
11,884 | def fromsoap ( args ) : p = OptionParser ( fromsoap . __doc__ ) p . add_option ( "--type" , default = "nucleotide_match" , help = "GFF feature type [default: %default]" ) p . add_option ( "--source" , default = "soap" , help = "GFF source qualifier [default: %default]" ) p . set_fixchrnames ( orgn = "maize" ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) soapfile , = args pad0 = len ( str ( sum ( 1 for line in open ( soapfile ) ) ) ) fw = must_open ( opts . outfile , "w" ) fp = must_open ( soapfile ) for idx , line in enumerate ( fp ) : if opts . fix_chr_name : from jcvi . utils . cbook import fixChromName line = fixChromName ( line , orgn = opts . fix_chr_name ) atoms = line . strip ( ) . split ( "\t" ) attributes = "ID=match{0};Name={1}" . format ( str ( idx ) . zfill ( pad0 ) , atoms [ 0 ] ) start , end = int ( atoms [ 8 ] ) , int ( atoms [ 5 ] ) + int ( atoms [ 8 ] ) - 1 seqid = atoms [ 7 ] print ( "\t" . join ( str ( x ) for x in ( seqid , opts . source , opts . type , start , end , "." , atoms [ 6 ] , "." , attributes ) ) , file = fw ) | %prog fromsoap soapfile > gff_file |
11,885 | def gtf ( args ) : p = OptionParser ( gtf . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) gffile , = args gff = Gff ( gffile ) transcript_info = AutoVivification ( ) for g in gff : if g . type . endswith ( ( "RNA" , "transcript" ) ) : if "ID" in g . attributes and "Parent" in g . attributes : transcript_id = g . get_attr ( "ID" ) gene_id = g . get_attr ( "Parent" ) elif "mRNA" in g . attributes and "Gene" in g . attributes : transcript_id = g . get_attr ( "mRNA" ) gene_id = g . get_attr ( "Gene" ) else : transcript_id = g . get_attr ( "ID" ) gene_id = transcript_id transcript_info [ transcript_id ] [ "gene_id" ] = gene_id transcript_info [ transcript_id ] [ "gene_type" ] = g . type continue if g . type not in valid_gff_to_gtf_type . keys ( ) : continue try : transcript_id = g . get_attr ( "Parent" , first = False ) except IndexError : transcript_id = g . get_attr ( "mRNA" , first = False ) g . type = valid_gff_to_gtf_type [ g . type ] for tid in transcript_id : if tid not in transcript_info : continue gene_type = transcript_info [ tid ] [ "gene_type" ] if not gene_type . endswith ( "RNA" ) and not gene_type . endswith ( "transcript" ) : continue gene_id = transcript_info [ tid ] [ "gene_id" ] g . attributes = dict ( gene_id = [ gene_id ] , transcript_id = [ tid ] ) g . update_attributes ( gtf = True , urlquote = False ) print ( g ) | %prog gtf gffile |
11,886 | def merge ( args ) : p = OptionParser ( merge . __doc__ ) p . add_option ( "--seq" , default = False , action = "store_true" , help = "Print FASTA sequences at the end" ) p . set_outfile ( ) opts , args = p . parse_args ( args ) nargs = len ( args ) if nargs < 1 : sys . exit ( not p . print_help ( ) ) if nargs == 1 : listfile , = args fp = open ( listfile ) gffiles = [ x . strip ( ) for x in fp ] else : gffiles = args outfile = opts . outfile deflines = set ( ) fw = must_open ( outfile , "w" ) fastarecs = { } for gffile in natsorted ( gffiles , key = lambda x : op . basename ( x ) ) : logging . debug ( gffile ) fp = open ( gffile ) for row in fp : row = row . rstrip ( ) if not row or row [ 0 ] == '#' : if row == FastaTag : break if row in deflines : continue else : deflines . add ( row ) print ( row , file = fw ) if not opts . seq : continue f = Fasta ( gffile , lazy = True ) for key , rec in f . iteritems_ordered ( ) : if key in fastarecs : continue fastarecs [ key ] = rec if opts . seq : print ( FastaTag , file = fw ) SeqIO . write ( fastarecs . values ( ) , fw , "fasta" ) fw . close ( ) | %prog merge gffiles |
11,887 | def extract ( args ) : p = OptionParser ( extract . __doc__ ) p . add_option ( "--contigs" , help = "Extract features from certain contigs [default: %default]" ) p . add_option ( "--names" , help = "Extract features with certain names [default: %default]" ) p . add_option ( "--types" , type = "str" , default = None , help = "Extract features of certain feature types [default: %default]" ) p . add_option ( "--children" , default = 0 , choices = [ "1" , "2" ] , help = "Specify number of iterations: `1` grabs children, " + "`2` grabs grand-children [default: %default]" ) p . add_option ( "--tag" , default = "ID" , help = "Scan the tags for the names [default: %default]" ) p . add_option ( "--fasta" , default = False , action = "store_true" , help = "Write FASTA if available [default: %default]" ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) gffile , = args contigfile = opts . contigs namesfile = opts . names typesfile = opts . types nametag = opts . tag contigID = parse_multi_values ( contigfile ) names = parse_multi_values ( namesfile ) types = parse_multi_values ( typesfile ) outfile = opts . outfile if opts . children : assert types is not None or names is not None , "Must set --names or --types" if names == None : names = list ( ) populate_children ( outfile , names , gffile , iter = opts . children , types = types ) return fp = must_open ( gffile ) fw = must_open ( opts . outfile , "w" ) for row in fp : atoms = row . split ( ) if len ( atoms ) == 0 : continue tag = atoms [ 0 ] if row [ 0 ] == "#" : if row . strip ( ) == "###" : continue if not ( tag == RegionTag and contigID and atoms [ 1 ] not in contigID ) : print ( row . rstrip ( ) , file = fw ) if tag == FastaTag : break continue b = GffLine ( row ) attrib = b . attributes if contigID and tag not in contigID : continue if types and b . type in types : _id = b . accn if _id not in names : names . append ( _id ) if names is not None : if nametag not in attrib : continue if attrib [ nametag ] [ 0 ] not in names : continue print ( row . rstrip ( ) , file = fw ) if not opts . fasta : return f = Fasta ( gffile ) for s in contigID : if s in f : SeqIO . write ( [ f [ s ] ] , fw , "fasta" ) | %prog extract gffile |
11,888 | def split ( args ) : p = OptionParser ( split . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) gffile , outdir = args mkdir ( outdir ) g = Gff ( gffile ) seqids = g . seqids for s in seqids : outfile = op . join ( outdir , s + ".gff" ) extract ( [ gffile , "--contigs=" + s , "--outfile=" + outfile ] ) | %prog split gffile outdir |
11,889 | def note ( args ) : p = OptionParser ( note . __doc__ ) p . add_option ( "--type" , default = None , help = "Only process certain types, multiple types allowed with comma" ) p . add_option ( "--attribute" , default = "Parent,Note" , help = "Attribute field to extract, multiple fields allowd with comma" ) p . add_option ( "--AED" , type = "float" , help = "Only extract lines with AED score <=" ) p . add_option ( "--exoncount" , default = False , action = "store_true" , help = "Get the exon count for each mRNA feat" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) gffile , = args type = opts . type if type : type = type . split ( "," ) g = make_index ( gffile ) exoncounts = { } if opts . exoncount : for feat in g . features_of_type ( "mRNA" ) : nexons = 0 for c in g . children ( feat . id , 1 ) : if c . featuretype != "exon" : continue nexons += 1 exoncounts [ feat . id ] = nexons attrib = opts . attribute . split ( "," ) gff = Gff ( gffile ) seen = set ( ) AED = opts . AED for g in gff : if type and g . type not in type : continue if AED is not None and float ( g . attributes [ "_AED" ] [ 0 ] ) > AED : continue keyval = [ g . accn ] + [ "," . join ( g . attributes [ x ] ) for x in attrib if x in g . attributes ] if exoncounts : nexons = exoncounts . get ( g . accn , 0 ) keyval . append ( str ( nexons ) ) keyval = tuple ( keyval ) if keyval not in seen : print ( "\t" . join ( keyval ) ) seen . add ( keyval ) | %prog note gffile > tabfile |
11,890 | def make_index ( gff_file ) : import gffutils db_file = gff_file + ".db" if need_update ( gff_file , db_file ) : if op . exists ( db_file ) : os . remove ( db_file ) logging . debug ( "Indexing `{0}`" . format ( gff_file ) ) gffutils . create_db ( gff_file , db_file , merge_strategy = "create_unique" ) else : logging . debug ( "Load index `{0}`" . format ( gff_file ) ) return gffutils . FeatureDB ( db_file ) | Make a sqlite database for fast retrieval of features . |
11,891 | def children ( args ) : p = OptionParser ( children . __doc__ ) p . add_option ( "--parents" , default = "gene" , help = "list of features to extract, use comma to separate (e.g." "'gene,mRNA') [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) gff_file , = args g = make_index ( gff_file ) parents = set ( opts . parents . split ( ',' ) ) for feat in get_parents ( gff_file , parents ) : cc = [ c . id for c in g . children ( feat . id , 1 ) ] if len ( cc ) <= 1 : continue print ( "\t" . join ( str ( x ) for x in ( feat . id , feat . start , feat . stop , "|" . join ( cc ) ) ) ) | %prog children gff_file |
11,892 | def bed12 ( args ) : p = OptionParser ( bed12 . __doc__ ) p . add_option ( "--parent" , default = "mRNA" , help = "Top feature type [default: %default]" ) p . add_option ( "--block" , default = "exon" , help = "Feature type for regular blocks [default: %default]" ) p . add_option ( "--thick" , default = "CDS" , help = "Feature type for thick blocks [default: %default]" ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) gffile , = args parent , block , thick = opts . parent , opts . block , opts . thick outfile = opts . outfile g = make_index ( gffile ) fw = must_open ( outfile , "w" ) for f in g . features_of_type ( parent ) : chrom = f . chrom chromStart = f . start - 1 chromEnd = f . stop name = f . id score = 0 strand = f . strand thickStart = 1e15 thickEnd = 0 blocks = [ ] for c in g . children ( name , 1 ) : cstart , cend = c . start - 1 , c . stop if c . featuretype == block : blockStart = cstart - chromStart blockSize = cend - cstart blocks . append ( ( blockStart , blockSize ) ) elif c . featuretype == thick : thickStart = min ( thickStart , cstart ) thickEnd = max ( thickEnd , cend ) blocks . sort ( ) blockStarts , blockSizes = zip ( * blocks ) blockCount = len ( blocks ) blockSizes = "," . join ( str ( x ) for x in blockSizes ) + "," blockStarts = "," . join ( str ( x ) for x in blockStarts ) + "," itemRgb = 0 print ( "\t" . join ( str ( x ) for x in ( chrom , chromStart , chromEnd , name , score , strand , thickStart , thickEnd , itemRgb , blockCount , blockSizes , blockStarts ) ) , file = fw ) | %prog bed12 gffile > bedfile |
11,893 | def bed ( args ) : p = OptionParser ( bed . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( p . print_help ( ) ) flist = args prefix = flist [ 0 ] . split ( "." ) [ 0 ] j = 0 for f in flist : reader = Maf ( f ) . reader for rec in reader : a , b = rec . components for a , tag in zip ( ( a , b ) , "ab" ) : name = "{0}_{1:07d}{2}" . format ( prefix , j , tag ) print ( "\t" . join ( str ( x ) for x in ( a . src , a . forward_strand_start , a . forward_strand_end , name ) ) ) j += 1 | %prog bed maffiles > out . bed |
11,894 | def blast ( args ) : p = OptionParser ( blast . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) == 0 : sys . exit ( p . print_help ( ) ) flist = args for f in flist : maf_to_blast8 ( f ) | %prog blast maffiles > out . blast |
11,895 | def genome_mutation ( candidate ) : size = len ( candidate ) prob = random . random ( ) if prob > .5 : p = random . randint ( 0 , size - 1 ) q = random . randint ( 0 , size - 1 ) if p > q : p , q = q , p q += 1 s = candidate [ p : q ] x = candidate [ : p ] + s [ : : - 1 ] + candidate [ q : ] return creator . Individual ( x ) , else : p = random . randint ( 0 , size - 1 ) q = random . randint ( 0 , size - 1 ) cq = candidate . pop ( q ) candidate . insert ( p , cq ) return candidate , | Return the mutants created by inversion mutation on the candidates . |
11,896 | def frombed ( args ) : from jcvi . formats . fasta import Fasta from jcvi . formats . bed import Bed from jcvi . utils . cbook import fill p = OptionParser ( frombed . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) bedfile , contigfasta , readfasta = args prefix = bedfile . rsplit ( "." , 1 ) [ 0 ] contigfile = prefix + ".contig" idsfile = prefix + ".ids" contigfasta = Fasta ( contigfasta ) readfasta = Fasta ( readfasta ) bed = Bed ( bedfile ) checksum = "00000000 checksum." fw_ids = open ( idsfile , "w" ) fw = open ( contigfile , "w" ) for ctg , reads in bed . sub_beds ( ) : ctgseq = contigfasta [ ctg ] ctgline = "##{0} {1} {2} bases, {3}" . format ( ctg , len ( reads ) , len ( ctgseq ) , checksum ) print ( ctg , file = fw_ids ) print ( ctgline , file = fw ) print ( fill ( ctgseq . seq ) , file = fw ) for b in reads : read = b . accn strand = b . strand readseq = readfasta [ read ] rc = " [RC]" if strand == "-" else "" readlen = len ( readseq ) rstart , rend = 1 , readlen if strand == "-" : rstart , rend = rend , rstart readrange = "{{{0} {1}}}" . format ( rstart , rend ) conrange = "<{0} {1}>" . format ( b . start , b . end ) readline = "#{0}(0){1} {2} bases, {3} {4} {5}" . format ( read , rc , readlen , checksum , readrange , conrange ) print ( readline , file = fw ) print ( fill ( readseq . seq ) , file = fw ) logging . debug ( "Mapped contigs written to `{0}`." . format ( contigfile ) ) logging . debug ( "Contig IDs written to `{0}`." . format ( idsfile ) ) | %prog frombed bedfile contigfasta readfasta |
11,897 | def bed ( args ) : p = OptionParser ( main . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) contigfile , = args bedfile = contigfile . rsplit ( "." , 1 ) [ 0 ] + ".bed" fw = open ( bedfile , "w" ) c = ContigFile ( contigfile ) for rec in c . iter_records ( ) : for r in rec . reads : print ( r . bedline , file = fw ) logging . debug ( "File written to `{0}`." . format ( bedfile ) ) return bedfile | %prog bed contigfile |
11,898 | def get_errors ( error_string ) : lines = error_string . splitlines ( ) error_lines = tuple ( line for line in lines if line . find ( 'Error' ) >= 0 ) if len ( error_lines ) > 0 : return '\n' . join ( error_lines ) else : return error_string . strip ( ) | returns all lines in the error_string that start with the string error |
11,899 | def tempnam ( ) : stderr = sys . stderr try : sys . stderr = cStringIO . StringIO ( ) return os . tempnam ( None , 'tess_' ) finally : sys . stderr = stderr | returns a temporary file - name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.