idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
11,700
def link ( args ) : from jcvi . apps . base import mkdir p = OptionParser ( link . __doc__ ) p . add_option ( "--dir" , help = "Place links in a subdirectory [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) meta , = args d = opts . dir if d : mkdir ( d ) fp = open ( meta ) cwd = op . dirname ( get_abs_path ( meta ) ) for row in fp : source , target = row . split ( ) source = op . join ( cwd , source ) if d : target = op . join ( d , target ) lnsf ( source , target , log = True )
%prog link metafile
11,701
def touch ( args ) : p = OptionParser ( touch . __doc__ ) opts , args = p . parse_args ( args ) fp = sys . stdin for link_name in fp : link_name = link_name . strip ( ) if not op . islink ( link_name ) : continue if not op . exists ( link_name ) : continue source = get_abs_path ( link_name ) lnsf ( source , link_name )
find . - type l | %prog touch
11,702
def cp ( args ) : p = OptionParser ( cp . __doc__ ) fp = sys . stdin for link_name in fp : link_name = link_name . strip ( ) if not op . exists ( link_name ) : continue source = get_abs_path ( link_name ) link_name = op . basename ( link_name ) if not op . exists ( link_name ) : os . symlink ( source , link_name ) logging . debug ( " => " . join ( ( source , link_name ) ) )
find folder - type l | %prog cp
11,703
def size ( args ) : from jcvi . utils . cbook import human_size p = OptionParser ( size . __doc__ ) fp = sys . stdin results = [ ] for link_name in fp : link_name = link_name . strip ( ) if not op . islink ( link_name ) : continue source = get_abs_path ( link_name ) link_name = op . basename ( link_name ) filesize = op . getsize ( source ) results . append ( ( filesize , link_name ) ) for filesize , link_name in sorted ( results , reverse = True ) : filesize = human_size ( filesize , a_kilobyte_is_1024_bytes = True ) print ( "%10s\t%s" % ( filesize , link_name ) , file = sys . stderr )
find folder - type l | %prog size
11,704
def nucmer ( args ) : p = OptionParser ( nucmer . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 5 : sys . exit ( not p . print_help ( ) ) mapbed , mtrfasta , asmfasta , chr , idx = args idx = int ( idx ) m1 = 1000000 bedfile = "sample.bed" bed = Bed ( ) bed . add ( "\t" . join ( str ( x ) for x in ( chr , ( idx - 1 ) * m1 , idx * m1 ) ) ) bed . print_to_file ( bedfile ) cmd = "intersectBed -a {0} -b {1} -nonamecheck -sorted | cut -f4" . format ( mapbed , bedfile ) idsfile = "query.ids" sh ( cmd , outfile = idsfile ) sfasta = fastaFromBed ( bedfile , mtrfasta ) qfasta = "query.fasta" cmd = "faSomeRecords {0} {1} {2}" . format ( asmfasta , idsfile , qfasta ) sh ( cmd ) cmd = "nucmer {0} {1}" . format ( sfasta , qfasta ) sh ( cmd ) mummerplot_main ( [ "out.delta" , "--refcov=0" ] ) sh ( "mv out.pdf {0}.{1}.pdf" . format ( chr , idx ) )
%prog nucmer mappings . bed MTR . fasta assembly . fasta chr1 3
11,705
def validate_term ( term , so = None , method = "verify" ) : if so is None : so = load_GODag ( ) oterm = term if term not in so . valid_names : if "resolve" in method : if "_" in term : tparts = deque ( term . split ( "_" ) ) tparts . pop ( ) if "prefix" in method else tparts . popleft ( ) nterm = "_" . join ( tparts ) . strip ( ) term = validate_term ( nterm , so = so , method = method ) if term is None : return None else : logging . error ( "Term `{0}` does not exist" . format ( term ) ) sys . exit ( 1 ) if oterm != term : logging . debug ( "Resolved term `{0}` to `{1}`" . format ( oterm , term ) ) return term
Validate an SO term against so . obo
11,706
def agp ( args ) : p = OptionParser ( agp . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) tablefile , = args fp = open ( tablefile ) for row in fp : atoms = row . split ( ) hr = atoms [ 0 ] scaf = atoms [ 1 ] scaf_start = int ( atoms [ 2 ] ) + 1 scaf_end = int ( atoms [ 3 ] ) strand = atoms [ 4 ] hr_start = int ( atoms [ 5 ] ) + 1 hr_end = int ( atoms [ 6 ] ) print ( "\t" . join ( str ( x ) for x in ( hr , hr_start , hr_end , 1 , 'W' , scaf , scaf_start , scaf_end , strand ) ) )
%prog agp Siirt_Female_pistachio_23May2017_table . txt
11,707
def traits ( args ) : p = OptionParser ( traits . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) < 1 : sys . exit ( not p . print_help ( ) ) samples = [ ] for folder in args : targets = iglob ( folder , "*-traits.json" ) if not targets : continue filename = targets [ 0 ] js = json . load ( open ( filename ) ) js [ "skin_rgb" ] = make_rgb ( js [ "traits" ] [ "skin-color" ] [ "L" ] , js [ "traits" ] [ "skin-color" ] [ "A" ] , js [ "traits" ] [ "skin-color" ] [ "B" ] ) js [ "eye_rgb" ] = make_rgb ( js [ "traits" ] [ "eye-color" ] [ "L" ] , js [ "traits" ] [ "eye-color" ] [ "A" ] , js [ "traits" ] [ "eye-color" ] [ "B" ] ) samples . append ( js ) template = Template ( traits_template ) fw = open ( "report.html" , "w" ) print ( template . render ( samples = samples ) , file = fw ) logging . debug ( "Report written to `{}`" . format ( fw . name ) ) fw . close ( )
%prog traits directory
11,708
def regression ( args ) : p = OptionParser ( regression . __doc__ ) opts , args , iopts = p . set_image_options ( args , figsize = "8x8" ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) tsvfile , = args df = pd . read_csv ( tsvfile , sep = "\t" ) chrono = "Chronological age (yr)" pred = "Predicted age (yr)" resdf = pd . DataFrame ( { chrono : df [ "hli_calc_age_sample_taken" ] , pred : df [ "Predicted Age" ] } ) g = sns . jointplot ( chrono , pred , resdf , joint_kws = { "s" : 6 } , xlim = ( 0 , 100 ) , ylim = ( 0 , 80 ) ) g . fig . set_figwidth ( iopts . w ) g . fig . set_figheight ( iopts . h ) outfile = tsvfile . rsplit ( "." , 1 ) [ 0 ] + ".regression.pdf" savefig ( outfile )
%prog regression postgenomic - s . tsv
11,709
def composite_correlation ( df , size = ( 12 , 8 ) ) : fig = plt . figure ( 1 , size ) ax1 = plt . subplot2grid ( ( 2 , 2 ) , ( 0 , 0 ) ) ax2 = plt . subplot2grid ( ( 2 , 2 ) , ( 0 , 1 ) ) ax3 = plt . subplot2grid ( ( 2 , 2 ) , ( 1 , 0 ) ) ax4 = plt . subplot2grid ( ( 2 , 2 ) , ( 1 , 1 ) ) chemistry = [ "V1" , "V2" , "V2.5" , float ( "nan" ) ] colors = sns . color_palette ( "Set2" , 8 ) color_map = dict ( zip ( chemistry , colors ) ) age_label = "Chronological age (yr)" ax1 . scatter ( df [ "hli_calc_age_sample_taken" ] , df [ "teloLength" ] , s = 10 , marker = '.' , color = df [ "Chemistry" ] . map ( color_map ) ) ax1 . set_ylim ( 0 , 15 ) ax1 . set_ylabel ( "Telomere length (Kb)" ) ax2 . scatter ( df [ "hli_calc_age_sample_taken" ] , df [ "ccn.chrX" ] , s = 10 , marker = '.' , color = df [ "Chemistry" ] . map ( color_map ) ) ax2 . set_ylim ( 1.8 , 2.1 ) ax2 . set_ylabel ( "ChrX copy number" ) ax4 . scatter ( df [ "hli_calc_age_sample_taken" ] , df [ "ccn.chrY" ] , s = 10 , marker = '.' , color = df [ "Chemistry" ] . map ( color_map ) ) ax4 . set_ylim ( 0.8 , 1.1 ) ax4 . set_ylabel ( "ChrY copy number" ) ax3 . scatter ( df [ "hli_calc_age_sample_taken" ] , df [ "TRA.PPM" ] , s = 10 , marker = '.' , color = df [ "Chemistry" ] . map ( color_map ) ) ax3 . set_ylim ( 0 , 250 ) ax3 . set_ylabel ( "$TCR-\\alpha$ deletions (count per million reads)" ) from matplotlib . lines import Line2D legend_elements = [ Line2D ( [ 0 ] , [ 0 ] , marker = '.' , color = 'w' , label = chem , markerfacecolor = color , markersize = 16 ) for ( chem , color ) in zip ( chemistry , colors ) [ : 3 ] ] for ax in ( ax1 , ax2 , ax3 , ax4 ) : ax . set_xlabel ( age_label ) ax . legend ( handles = legend_elements , loc = "upper right" ) plt . tight_layout ( ) root = fig . add_axes ( ( 0 , 0 , 1 , 1 ) ) labels = ( ( .02 , .98 , "A" ) , ( .52 , .98 , "B" ) , ( .02 , .5 , "C" ) , ( .52 , .5 , "D" ) ) panel_labels ( root , labels ) root . set_xlim ( 0 , 1 ) root . set_ylim ( 0 , 1 ) root . set_axis_off ( )
Plot composite correlation figure
11,710
def correlation ( args ) : p = OptionParser ( correlation . __doc__ ) opts , args , iopts = p . set_image_options ( args , figsize = "12x8" ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) tsvfile , = args df = pd . read_csv ( tsvfile , sep = "\t" ) composite_correlation ( df , size = ( iopts . w , iopts . h ) ) outfile = tsvfile . rsplit ( "." , 1 ) [ 0 ] + ".correlation.pdf" savefig ( outfile )
%prog correlation postgenomic - s . tsv
11,711
def extract_twin_values ( triples , traits , gender = None ) : traitValuesAbsent = 0 nanValues = 0 genderSkipped = 0 twinValues = [ ] for a , b , t in triples : if gender is not None and t != gender : genderSkipped += 1 continue if not ( a in traits and b in traits ) : traitValuesAbsent += 1 continue if np . isnan ( traits [ a ] ) or np . isnan ( traits [ b ] ) : nanValues += 1 continue twinValues . append ( ( traits [ a ] , traits [ b ] ) ) print ( "A total of {} pairs extracted ({} absent; {} nan; {} genderSkipped)" . format ( len ( twinValues ) , traitValuesAbsent , nanValues , genderSkipped ) ) return twinValues
Calculate the heritability of certain traits in triplets .
11,712
def heritability ( args ) : p = OptionParser ( heritability . __doc__ ) opts , args , iopts = p . set_image_options ( args , figsize = "12x18" ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) combined , mz , dz = args def get_pairs ( filename ) : with open ( filename ) as fp : for row in fp : yield row . strip ( ) . split ( "," ) MZ = list ( get_pairs ( mz ) ) DZ = list ( get_pairs ( dz ) ) print ( len ( MZ ) , "monozygotic twins" ) print ( len ( DZ ) , "dizygotic twins" ) df = pd . read_csv ( combined , sep = "\t" , index_col = 0 ) df [ "Sample name" ] = np . array ( df [ "Sample name" ] , dtype = np . str ) gender = extract_trait ( df , "Sample name" , "hli_calc_gender" ) sameGenderMZ = list ( filter_same_gender ( MZ , gender ) ) sameGenderDZ = list ( filter_same_gender ( DZ , gender ) ) composite ( df , sameGenderMZ , sameGenderDZ , size = ( iopts . w , iopts . h ) ) logging . getLogger ( ) . setLevel ( logging . CRITICAL ) savefig ( "heritability.pdf" )
%prog pg . tsv MZ - twins . csv DZ - twins . csv
11,713
def compile ( args ) : p = OptionParser ( compile . __doc__ ) p . set_outfile ( outfile = "age.tsv" ) opts , args = p . parse_args ( args ) if len ( args ) < 1 : sys . exit ( not p . print_help ( ) ) dfs = [ ] for folder in args : ofolder = os . listdir ( folder ) subdir = [ x for x in ofolder if x . startswith ( "telomeres" ) ] [ 0 ] subdir = op . join ( folder , subdir ) filename = op . join ( subdir , "tel_lengths.txt" ) df = pd . read_csv ( filename , sep = "\t" ) d1 = df . ix [ 0 ] . to_dict ( ) subdir = [ x for x in ofolder if x . startswith ( "ccn" ) ] [ 0 ] subdir = op . join ( folder , subdir ) filename = iglob ( subdir , "*.ccn.json" ) [ 0 ] js = json . load ( open ( filename ) ) d1 . update ( js ) df = pd . DataFrame ( d1 , index = [ 0 ] ) dfs . append ( df ) df = pd . concat ( dfs , ignore_index = True ) df . to_csv ( opts . outfile , sep = "\t" , index = False )
%prog compile directory
11,714
def simulate_one ( fw , name , size ) : from random import choice seq = Seq ( '' . join ( choice ( 'ACGT' ) for _ in xrange ( size ) ) ) s = SeqRecord ( seq , id = name , description = "Fake sequence" ) SeqIO . write ( [ s ] , fw , "fasta" )
Simulate a random sequence with name and size
11,715
def simulate ( args ) : p = OptionParser ( simulate . __doc__ ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) idsfile , = args fp = open ( idsfile ) fw = must_open ( opts . outfile , "w" ) for row in fp : name , size = row . split ( ) size = int ( size ) simulate_one ( fw , name , size ) fp . close ( )
%prog simulate idsfile
11,716
def gc ( args ) : p = OptionParser ( gc . __doc__ ) p . add_option ( "--binsize" , default = 500 , type = "int" , help = "Bin size to use" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) fastafile , = args binsize = opts . binsize allbins = [ ] for name , seq in parse_fasta ( fastafile ) : for i in range ( len ( seq ) / binsize ) : atcnt = gccnt = 0 for c in seq [ i * binsize : ( i + 1 ) * binsize ] . upper ( ) : if c in "AT" : atcnt += 1 elif c in "GC" : gccnt += 1 totalcnt = atcnt + gccnt if totalcnt == 0 : continue gcpct = gccnt * 100 / totalcnt allbins . append ( gcpct ) from jcvi . graphics . base import asciiplot from collections import Counter title = "Total number of bins={}" . format ( len ( allbins ) ) c = Counter ( allbins ) x , y = zip ( * sorted ( c . items ( ) ) ) asciiplot ( x , y , title = title )
%prog gc fastafile
11,717
def trimsplit ( args ) : from jcvi . utils . cbook import SummaryStats p = OptionParser ( trimsplit . __doc__ ) p . add_option ( "--minlength" , default = 1000 , type = "int" , help = "Min length of contigs to keep" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) fastafile , = args minlength = opts . minlength fw = must_open ( fastafile . rsplit ( "." , 1 ) [ 0 ] + ".split.fasta" , "w" ) ntotal = 0 removed = [ ] Ns = [ ] for name , seq in parse_fasta ( fastafile ) : stretches = [ ] ntotal += len ( seq ) for lower , stretch in groupby ( seq , key = lambda x : x . islower ( ) ) : stretch = "" . join ( stretch ) if lower or len ( stretch ) < minlength : removed . append ( len ( stretch ) ) continue for isN , s in groupby ( stretch , key = lambda x : x in "Nn" ) : s = "" . join ( s ) if isN or len ( s ) < minlength : Ns . append ( len ( s ) ) continue stretches . append ( s ) for i , seq in enumerate ( stretches ) : id = "{0}_{1}" . format ( name . split ( "|" ) [ 0 ] , i ) s = SeqRecord ( Seq ( seq ) , id = id , description = "" ) SeqIO . write ( [ s ] , fw , "fasta" ) fw . close ( ) if removed : logging . debug ( "Total bases removed: {0}" . format ( percentage ( sum ( removed ) , ntotal ) ) ) print ( SummaryStats ( removed ) , file = sys . stderr ) if Ns : logging . debug ( "Total Ns removed: {0}" . format ( percentage ( sum ( Ns ) , ntotal ) ) ) print ( SummaryStats ( Ns ) , file = sys . stderr )
%prog trimsplit fastafile
11,718
def qual ( args ) : from jcvi . formats . sizes import Sizes p = OptionParser ( qual . __doc__ ) p . add_option ( "--qv" , default = 31 , type = "int" , help = "Dummy qv score for extended bases" ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) fastafile , = args sizes = Sizes ( fastafile ) qvchar = str ( opts . qv ) fw = must_open ( opts . outfile , "w" ) total = 0 for s , slen in sizes . iter_sizes ( ) : print ( ">" + s , file = fw ) print ( " " . join ( [ qvchar ] * slen ) , file = fw ) total += 1 fw . close ( ) logging . debug ( "Written {0} records in `{1}`." . format ( total , opts . outfile ) )
%prog qual fastafile
11,719
def fromtab ( args ) : p = OptionParser ( fromtab . __doc__ ) p . set_sep ( sep = None ) p . add_option ( "--noheader" , default = False , action = "store_true" , help = "Ignore first line" ) p . add_option ( "--replace" , help = "Replace spaces in name to char [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) tabfile , fastafile = args sep = opts . sep replace = opts . replace fp = must_open ( tabfile ) fw = must_open ( fastafile , "w" ) nseq = 0 if opts . noheader : next ( fp ) for row in fp : row = row . strip ( ) if not row or row [ 0 ] == '#' : continue name , seq = row . rsplit ( sep , 1 ) if replace : name = name . replace ( " " , replace ) print ( ">{0}\n{1}" . format ( name , seq ) , file = fw ) nseq += 1 fw . close ( ) logging . debug ( "A total of {0} sequences written to `{1}`." . format ( nseq , fastafile ) )
%prog fromtab tabfile fastafile
11,720
def longestorf ( args ) : p = OptionParser ( longestorf . __doc__ ) p . add_option ( "--ids" , action = "store_true" , help = "Generate table with ORF info [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) fastafile , = args pf = fastafile . rsplit ( "." , 1 ) [ 0 ] orffile = pf + ".orf.fasta" idsfile = None if opts . ids : idsfile = pf + ".orf.ids" fwids = open ( idsfile , "w" ) f = Fasta ( fastafile , lazy = True ) fw = must_open ( orffile , "w" ) before , after = 0 , 0 for name , rec in f . iteritems_ordered ( ) : cds = rec . seq before += len ( cds ) orf = ORFFinder ( cds ) lorf = orf . get_longest_orf ( ) newcds = Seq ( lorf ) after += len ( newcds ) newrec = SeqRecord ( newcds , id = name , description = rec . description ) SeqIO . write ( [ newrec ] , fw , "fasta" ) if idsfile : print ( "\t" . join ( ( name , orf . info ) ) , file = fwids ) fw . close ( ) if idsfile : fwids . close ( ) logging . debug ( "Longest ORFs written to `{0}` ({1})." . format ( orffile , percentage ( after , before ) ) ) return orffile
%prog longestorf fastafile
11,721
def ispcr ( args ) : from jcvi . utils . iter import grouper p = OptionParser ( ispcr . __doc__ ) p . add_option ( "-r" , dest = "rclip" , default = 1 , type = "int" , help = "pair ID is derived from rstrip N chars [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) fastafile , = args ispcrfile = fastafile + ".isPcr" fw = open ( ispcrfile , "w" ) N = opts . rclip strip_name = lambda x : x [ : - N ] if N else str npairs = 0 fastaiter = SeqIO . parse ( fastafile , "fasta" ) for a , b in grouper ( fastaiter , 2 ) : aid , bid = [ strip_name ( x ) for x in ( a . id , b . id ) ] assert aid == bid , "Name mismatch {0}" . format ( ( aid , bid ) ) print ( "\t" . join ( ( aid , str ( a . seq ) , str ( b . seq ) ) ) , file = fw ) npairs += 1 fw . close ( ) logging . debug ( "A total of {0} pairs written to `{1}`." . format ( npairs , ispcrfile ) )
%prog ispcr fastafile
11,722
def parse_fasta ( infile , upper = False ) : try : fp = must_open ( infile ) except : fp = infile fa_iter = ( x [ 1 ] for x in groupby ( fp , lambda row : row [ 0 ] == '>' ) ) for header in fa_iter : header = next ( header ) if header [ 0 ] != '>' : continue header = header . strip ( ) [ 1 : ] seq = "" . join ( s . strip ( ) for s in next ( fa_iter ) ) if upper : seq = seq . upper ( ) yield header , seq
parse a fasta - formatted file and returns header can be a fasta file that contains multiple records .
11,723
def clean ( args ) : p = OptionParser ( clean . __doc__ ) p . add_option ( "--fancy" , default = False , action = "store_true" , help = "Pretty print the sequence [default: %default]" ) p . add_option ( "--canonical" , default = False , action = "store_true" , help = "Use only acgtnACGTN [default: %default]" ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) fastafile , = args fw = must_open ( opts . outfile , "w" ) if opts . fancy : for header , seq in iter_clean_fasta ( fastafile ) : print ( ">" + header , file = fw ) fancyprint ( fw , seq ) return 0 iterator = iter_canonical_fasta if opts . canonical else iter_clean_fasta for header , seq in iterator ( fastafile ) : seq = Seq ( seq ) s = SeqRecord ( seq , id = header , description = "" ) SeqIO . write ( [ s ] , fw , "fasta" )
%prog clean fastafile
11,724
def filter ( args ) : p = OptionParser ( filter . __doc__ ) p . add_option ( "--less" , default = False , action = "store_true" , help = "filter the sizes < certain cutoff [default: >=]" ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) fastafile , cutoff = args try : cutoff = int ( cutoff ) except ValueError : sys . exit ( not p . print_help ( ) ) f = Fasta ( fastafile , lazy = True ) fw = must_open ( opts . outfile , "w" ) for name , rec in f . iteritems_ordered ( ) : if opts . less and len ( rec ) >= cutoff : continue if ( not opts . less ) and len ( rec ) < cutoff : continue SeqIO . write ( [ rec ] , fw , "fasta" ) fw . flush ( ) return fw . name
%prog filter fastafile 100
11,725
def pool ( args ) : from jcvi . formats . base import longest_unique_prefix p = OptionParser ( pool . __doc__ ) p . add_option ( "--sep" , default = "." , help = "Separator between prefix and name" ) p . add_option ( "--sequential" , default = False , action = "store_true" , help = "Add sequential IDs" ) opts , args = p . parse_args ( args ) if len ( args ) < 1 : sys . exit ( not p . print_help ( ) ) for fastafile in args : pf = longest_unique_prefix ( fastafile , args ) print ( fastafile , "=>" , pf , file = sys . stderr ) prefixopt = "--prefix={0}{1}" . format ( pf , opts . sep ) format_args = [ fastafile , "stdout" , prefixopt ] if opts . sequential : format_args += [ "--sequential=replace" ] format ( format_args )
%prog pool fastafiles > pool . fasta
11,726
def ids ( args ) : p = OptionParser ( ids . __doc__ ) p . add_option ( "--until" , default = None , help = "Truncate the name and description at words [default: %default]" ) p . add_option ( "--description" , default = False , action = "store_true" , help = "Generate a second column with description [default: %default]" ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) < 1 : sys . exit ( not p . print_help ( ) ) until = opts . until fw = must_open ( opts . outfile , "w" ) for row in must_open ( args ) : if row [ 0 ] == ">" : row = row [ 1 : ] . rstrip ( ) if until : row = row . split ( until ) [ 0 ] atoms = row . split ( None , 1 ) if opts . description : outrow = "\t" . join ( atoms ) else : outrow = atoms [ 0 ] print ( outrow , file = fw ) fw . close ( )
%prog ids fastafiles
11,727
def sort ( args ) : p = OptionParser ( sort . __doc__ ) p . add_option ( "--sizes" , default = False , action = "store_true" , help = "Sort by decreasing size [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( p . print_help ( ) ) fastafile , = args sortedfastafile = fastafile . rsplit ( "." , 1 ) [ 0 ] + ".sorted.fasta" f = Fasta ( fastafile , index = False ) fw = must_open ( sortedfastafile , "w" ) if opts . sizes : sortlist = sorted ( f . itersizes ( ) , key = lambda x : ( - x [ 1 ] , x [ 0 ] ) ) logging . debug ( "Sort by size: max: {0}, min: {1}" . format ( sortlist [ 0 ] , sortlist [ - 1 ] ) ) sortlist = [ x for x , s in sortlist ] else : sortlist = sorted ( f . iterkeys ( ) ) for key in sortlist : rec = f [ key ] SeqIO . write ( [ rec ] , fw , "fasta" ) logging . debug ( "Sorted file written to `{0}`." . format ( sortedfastafile ) ) fw . close ( ) return sortedfastafile
%prog sort fastafile
11,728
def print_first_difference ( arec , brec , ignore_case = False , ignore_N = False , rc = False , report_match = True ) : plus_match = _print_first_difference ( arec , brec , ignore_case = ignore_case , ignore_N = ignore_N , report_match = report_match ) if rc and not plus_match : logging . debug ( "trying reverse complement of %s" % brec . id ) brec . seq = brec . seq . reverse_complement ( ) minus_match = _print_first_difference ( arec , brec , ignore_case = ignore_case , ignore_N = ignore_N , report_match = report_match ) return minus_match else : return plus_match
Returns the first different nucleotide in two sequence comparisons runs both Plus and Minus strand
11,729
def _print_first_difference ( arec , brec , ignore_case = False , ignore_N = False , report_match = True ) : aseq , bseq = arec . seq , brec . seq asize , bsize = len ( aseq ) , len ( bseq ) matched = True for i , ( a , b ) in enumerate ( zip_longest ( aseq , bseq ) ) : if ignore_case and None not in ( a , b ) : a , b = a . upper ( ) , b . upper ( ) if ignore_N and ( 'N' in ( a , b ) or 'X' in ( a , b ) ) : continue if a != b : matched = False break if i + 1 == asize and matched : if report_match : print ( green ( "Two sequences match" ) ) match = True else : print ( red ( "Two sequences do not match" ) ) snippet_size = 20 print ( red ( "Sequence start to differ at position %d:" % ( i + 1 ) ) ) begin = max ( i - snippet_size , 0 ) aend = min ( i + snippet_size , asize ) bend = min ( i + snippet_size , bsize ) print ( red ( aseq [ begin : i ] + "|" + aseq [ i : aend ] ) ) print ( red ( bseq [ begin : i ] + "|" + bseq [ i : bend ] ) ) match = False return match
Returns the first different nucleotide in two sequence comparisons
11,730
def hash_fasta ( seq , ignore_case = False , ignore_N = False , ignore_stop = False , checksum = "MD5" ) : if ignore_stop : seq = seq . rstrip ( "*" ) if ignore_case : seq = seq . upper ( ) if ignore_N : if not all ( c . upper ( ) in 'ATGCN' for c in seq ) : seq = re . sub ( 'X' , '' , seq ) else : seq = re . sub ( 'N' , '' , seq ) if checksum == "MD5" : hashed = md5 ( seq ) . hexdigest ( ) elif checksum == "GCG" : hashed = seguid ( seq ) return hashed
Generates checksum of input sequence element
11,731
def get_qual ( fastafile , suffix = QUALSUFFIX , check = True ) : qualfile1 = fastafile . rsplit ( "." , 1 ) [ 0 ] + suffix qualfile2 = fastafile + suffix if check : if op . exists ( qualfile1 ) : logging . debug ( "qual file `{0}` found" . format ( qualfile1 ) ) return qualfile1 elif op . exists ( qualfile2 ) : logging . debug ( "qual file `{0}` found" . format ( qualfile2 ) ) return qualfile2 else : logging . warning ( "qual file not found" ) return None return qualfile1
Check if current folder contains a qual file associated with the fastafile
11,732
def some ( args ) : p = OptionParser ( some . __doc__ ) p . add_option ( "--exclude" , default = False , action = "store_true" , help = "Output sequences not in the list file [default: %default]" ) p . add_option ( "--uniprot" , default = False , action = "store_true" , help = "Header is from uniprot [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( p . print_help ( ) ) fastafile , listfile , outfastafile = args outfastahandle = must_open ( outfastafile , "w" ) qualfile = get_qual ( fastafile ) names = set ( x . strip ( ) for x in open ( listfile ) ) if qualfile : outqualfile = outfastafile + ".qual" outqualhandle = open ( outqualfile , "w" ) parser = iter_fasta_qual ( fastafile , qualfile ) else : parser = SeqIO . parse ( fastafile , "fasta" ) num_records = 0 for rec in parser : name = rec . id if opts . uniprot : name = name . split ( "|" ) [ - 1 ] if opts . exclude : if name in names : continue else : if name not in names : continue SeqIO . write ( [ rec ] , outfastahandle , "fasta" ) if qualfile : SeqIO . write ( [ rec ] , outqualhandle , "qual" ) num_records += 1 logging . debug ( "A total of %d records written to `%s`" % ( num_records , outfastafile ) )
%prog some fastafile listfile outfastafile
11,733
def fastq ( args ) : from jcvi . formats . fastq import FastqLite p = OptionParser ( fastq . __doc__ ) p . add_option ( "--qv" , type = "int" , help = "Use generic qv value [dafault: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) fastafile , = args fastqfile = fastafile . rsplit ( "." , 1 ) [ 0 ] + ".fastq" fastqhandle = open ( fastqfile , "w" ) num_records = 0 if opts . qv is not None : qv = chr ( ord ( '!' ) + opts . qv ) logging . debug ( "QV char '{0}' ({1})" . format ( qv , opts . qv ) ) else : qv = None if qv : f = Fasta ( fastafile , lazy = True ) for name , rec in f . iteritems_ordered ( ) : r = FastqLite ( "@" + name , str ( rec . seq ) . upper ( ) , qv * len ( rec . seq ) ) print ( r , file = fastqhandle ) num_records += 1 else : qualfile = get_qual ( fastafile ) for rec in iter_fasta_qual ( fastafile , qualfile ) : SeqIO . write ( [ rec ] , fastqhandle , "fastq" ) num_records += 1 fastqhandle . close ( ) logging . debug ( "A total of %d records written to `%s`" % ( num_records , fastqfile ) )
%prog fastq fastafile
11,734
def pair ( args ) : p = OptionParser ( pair . __doc__ ) p . set_sep ( sep = None , help = "Separator in name to reduce to clone id" + "e.g. GFNQ33242/1 use /, BOT01-2453H.b1 use ." ) p . add_option ( "-m" , dest = "matepairs" , default = False , action = "store_true" , help = "generate .matepairs file [often used for Celera Assembler]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( p . print_help ( ) ) fastafile , = args qualfile = get_qual ( fastafile ) prefix = fastafile . rsplit ( "." , 1 ) [ 0 ] pairsfile = prefix + ".pairs.fasta" fragsfile = prefix + ".frags.fasta" pairsfw = open ( pairsfile , "w" ) fragsfw = open ( fragsfile , "w" ) if opts . matepairs : matepairsfile = prefix + ".matepairs" matepairsfw = open ( matepairsfile , "w" ) if qualfile : pairsqualfile = pairsfile + ".qual" pairsqualhandle = open ( pairsqualfile , "w" ) fragsqualfile = fragsfile + ".qual" fragsqualhandle = open ( fragsqualfile , "w" ) f = Fasta ( fastafile ) if qualfile : q = SeqIO . index ( qualfile , "qual" ) all_keys = list ( f . keys ( ) ) all_keys . sort ( ) sep = opts . sep if sep : key_fun = lambda x : x . split ( sep , 1 ) [ 0 ] else : key_fun = lambda x : x [ : - 1 ] for key , variants in groupby ( all_keys , key = key_fun ) : variants = list ( variants ) paired = ( len ( variants ) == 2 ) if paired and opts . matepairs : print ( "\t" . join ( ( "%s/1" % key , "%s/2" % key ) ) , file = matepairsfw ) fw = pairsfw if paired else fragsfw if qualfile : qualfw = pairsqualhandle if paired else fragsqualhandle for i , var in enumerate ( variants ) : rec = f [ var ] if qualfile : recqual = q [ var ] newid = "%s/%d" % ( key , i + 1 ) rec . id = newid rec . description = "" SeqIO . write ( [ rec ] , fw , "fasta" ) if qualfile : recqual . id = newid recqual . description = "" SeqIO . write ( [ recqual ] , qualfw , "qual" ) logging . debug ( "sequences written to `%s` and `%s`" % ( pairsfile , fragsfile ) ) if opts . matepairs : logging . debug ( "mates written to `%s`" % matepairsfile )
%prog pair fastafile
11,735
def pairinplace ( args ) : from jcvi . utils . iter import pairwise p = OptionParser ( pairinplace . __doc__ ) p . add_option ( "-r" , dest = "rclip" , default = 1 , type = "int" , help = "pair ID is derived from rstrip N chars [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) fastafile , = args base = op . basename ( fastafile ) . split ( "." ) [ 0 ] frags = base + ".frags.fasta" pairs = base + ".pairs.fasta" if fastafile . endswith ( ".gz" ) : frags += ".gz" pairs += ".gz" fragsfw = must_open ( frags , "w" ) pairsfw = must_open ( pairs , "w" ) N = opts . rclip strip_name = lambda x : x [ : - N ] if N else str skipflag = False fastaiter = SeqIO . parse ( fastafile , "fasta" ) for a , b in pairwise ( fastaiter ) : aid , bid = [ strip_name ( x ) for x in ( a . id , b . id ) ] if skipflag : skipflag = False continue if aid == bid : SeqIO . write ( [ a , b ] , pairsfw , "fasta" ) skipflag = True else : SeqIO . write ( [ a ] , fragsfw , "fasta" ) if not skipflag : SeqIO . write ( [ a ] , fragsfw , "fasta" ) logging . debug ( "Reads paired into `%s` and `%s`" % ( pairs , frags ) )
%prog pairinplace bulk . fasta
11,736
def _uniq_rec ( fastafile , seq = False ) : seen = set ( ) for rec in SeqIO . parse ( fastafile , "fasta" ) : name = str ( rec . seq ) if seq else rec . id if name in seen : logging . debug ( "ignore {0}" . format ( rec . id ) ) continue seen . add ( name ) yield rec
Returns unique records
11,737
def uniq ( args ) : p = OptionParser ( uniq . __doc__ ) p . add_option ( "--seq" , default = False , action = "store_true" , help = "Uniqify the sequences [default: %default]" ) p . add_option ( "-t" , "--trimname" , dest = "trimname" , action = "store_true" , default = False , help = "turn on the defline trim to first space [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( p . print_help ( ) ) fastafile , uniqfastafile = args fw = must_open ( uniqfastafile , "w" ) seq = opts . seq for rec in _uniq_rec ( fastafile , seq = seq ) : if opts . trimname : rec . description = "" SeqIO . write ( [ rec ] , fw , "fasta" )
%prog uniq fasta uniq . fasta
11,738
def random ( args ) : from random import sample p = OptionParser ( random . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) fastafile , N = args N = int ( N ) assert N > 0 f = Fasta ( fastafile ) fw = must_open ( "stdout" , "w" ) for key in sample ( f . keys ( ) , N ) : rec = f [ key ] SeqIO . write ( [ rec ] , fw , "fasta" ) fw . close ( )
%prog random fasta 100 > random100 . fasta
11,739
def iter_fasta_qual ( fastafile , qualfile , defaultqual = OKQUAL , modify = False ) : from Bio . SeqIO . QualityIO import PairedFastaQualIterator if not qualfile : qualfile = make_qual ( fastafile , score = defaultqual ) rec_iter = PairedFastaQualIterator ( open ( fastafile ) , open ( qualfile ) ) for rec in rec_iter : yield rec if not modify else modify_qual ( rec )
used by trim emits one SeqRecord with quality values in it
11,740
def trim ( args ) : from jcvi . algorithms . maxsum import max_sum p = OptionParser ( trim . __doc__ ) p . add_option ( "-c" , dest = "min_length" , type = "int" , default = 64 , help = "minimum sequence length after trimming" ) p . add_option ( "-s" , dest = "score" , default = QUAL , help = "quality trimming cutoff [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( p . print_help ( ) ) fastafile , newfastafile = args qualfile = get_qual ( fastafile ) newqualfile = get_qual ( newfastafile , check = False ) logging . debug ( "Trim bad sequence from fasta file `%s` to `%s`" % ( fastafile , newfastafile ) ) fw = must_open ( newfastafile , "w" ) fw_qual = open ( newqualfile , "w" ) dropped = trimmed = 0 for rec in iter_fasta_qual ( fastafile , qualfile , modify = True ) : qv = [ x - opts . score for x in rec . letter_annotations [ "phred_quality" ] ] msum , trim_start , trim_end = max_sum ( qv ) score = trim_end - trim_start + 1 if score < opts . min_length : dropped += 1 continue if score < len ( rec ) : trimmed += 1 rec = rec [ trim_start : trim_end + 1 ] write_fasta_qual ( rec , fw , fw_qual ) print ( "A total of %d sequences modified." % trimmed , file = sys . stderr ) print ( "A total of %d sequences dropped (length < %d)." % ( dropped , opts . min_length ) , file = sys . stderr ) fw . close ( ) fw_qual . close ( )
%prog trim fasta . screen newfasta
11,741
def sequin ( args ) : p = OptionParser ( sequin . __doc__ ) p . add_option ( "--unk" , default = 100 , type = "int" , help = "The size for unknown gaps [default: %default]" ) p . add_option ( "--newid" , default = None , help = "Use this identifier instead [default: %default]" ) p . add_option ( "--chromosome" , default = None , help = "Add [chromosome= ] to FASTA header [default: %default]" ) p . add_option ( "--clone" , default = None , help = "Add [clone= ] to FASTA header [default: %default]" ) p . set_mingap ( default = 100 ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) inputfasta , = args unk = opts . unk outputfasta = inputfasta . rsplit ( "." , 1 ) [ 0 ] + ".split" rec = next ( SeqIO . parse ( must_open ( inputfasta ) , "fasta" ) ) seq = "" unknowns , knowns = 0 , 0 for gap , gap_group in groupby ( rec . seq , lambda x : x . upper ( ) == 'N' ) : subseq = "" . join ( gap_group ) if gap : gap_length = len ( subseq ) if gap_length == unk : subseq = "\n>?unk{0}\n" . format ( unk ) unknowns += 1 elif gap_length >= opts . mingap : subseq = "\n>?{0}\n" . format ( gap_length ) knowns += 1 seq += subseq fw = must_open ( outputfasta , "w" ) id = opts . newid or rec . id fastaheader = ">{0}" . format ( id ) if opts . chromosome : fastaheader += " [chromosome={0}]" . format ( opts . chromosome ) if opts . clone : fastaheader += " [clone={0}]" . format ( opts . clone ) print ( fastaheader , file = fw ) print ( seq , file = fw ) fw . close ( ) logging . debug ( "Sequin FASTA written to `{0}` (gaps: {1} unknowns, {2} knowns)." . format ( outputfasta , unknowns , knowns ) ) return outputfasta , unknowns + knowns
%prog sequin inputfasta
11,742
def tidy ( args ) : p = OptionParser ( tidy . __doc__ ) p . add_option ( "--gapsize" , dest = "gapsize" , default = 0 , type = "int" , help = "Set all gaps to the same size [default: %default]" ) p . add_option ( "--minlen" , dest = "minlen" , default = 100 , type = "int" , help = "Minimum component size [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) fastafile , = args gapsize = opts . gapsize minlen = opts . minlen tidyfastafile = fastafile . rsplit ( "." , 1 ) [ 0 ] + ".tidy.fasta" fw = must_open ( tidyfastafile , "w" ) removed = normalized = 0 fasta = Fasta ( fastafile , lazy = True ) for name , rec in fasta . iteritems_ordered ( ) : rec . seq = rec . seq . upper ( ) if minlen : removed += remove_small_components ( rec , minlen ) trim_terminal_Ns ( rec ) if gapsize : normalized += normalize_gaps ( rec , gapsize ) if len ( rec ) == 0 : logging . debug ( "Drop seq {0}" . format ( rec . id ) ) continue SeqIO . write ( [ rec ] , fw , "fasta" ) if removed : logging . debug ( "Total discarded bases: {0}" . format ( removed ) ) if normalized : logging . debug ( "Gaps normalized: {0}" . format ( normalized ) ) logging . debug ( "Tidy FASTA written to `{0}`." . format ( tidyfastafile ) ) fw . close ( ) return tidyfastafile
%prog tidy fastafile
11,743
def gaps ( args ) : from jcvi . formats . sizes import agp from jcvi . formats . agp import mask , build p = OptionParser ( gaps . __doc__ ) p . add_option ( "--split" , default = False , action = "store_true" , help = "Generate .split.fasta [default: %default]" ) p . set_mingap ( default = 100 ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) inputfasta , = args mingap = opts . mingap split = opts . split prefix = inputfasta . rsplit ( "." , 1 ) [ 0 ] bedfile = prefix + ".gaps.bed" if need_update ( inputfasta , bedfile ) : write_gaps_bed ( inputfasta , prefix , mingap , opts . cpus ) if split : splitfile = prefix + ".split.fasta" oagpfile = prefix + ".splitobject.agp" cagpfile = prefix + ".splitcomponent.agp" if need_update ( ( inputfasta , bedfile ) , splitfile ) : sizesagpfile = agp ( [ inputfasta ] ) maskedagpfile = mask ( [ sizesagpfile , bedfile , "--splitobject" ] ) shutil . move ( maskedagpfile , oagpfile ) logging . debug ( "AGP file written to `{0}`." . format ( oagpfile ) ) maskedagpfile = mask ( [ sizesagpfile , bedfile , "--splitcomponent" ] ) shutil . move ( maskedagpfile , cagpfile ) logging . debug ( "AGP file written to `{0}`." . format ( cagpfile ) ) build ( [ oagpfile , inputfasta , splitfile ] ) os . remove ( sizesagpfile ) return splitfile , oagpfile , cagpfile
%prog gaps fastafile
11,744
def scan_sequence ( self , frame , direction ) : orf_start = None for c , index in self . codons ( frame ) : if ( c not in self . stop and ( c in self . start or not self . start ) and orf_start is None ) : orf_start = index elif c in self . stop and orf_start is not None : self . _update_longest ( orf_start , index + 3 , direction , frame ) orf_start = None if orf_start is not None : self . _update_longest ( orf_start , index + 3 , direction , frame )
Search in one reading frame
11,745
def bed_to_bedpe ( bedfile , bedpefile , pairsbedfile = None , matesfile = None , ca = False , strand = False ) : fp = must_open ( bedfile ) fw = must_open ( bedpefile , "w" ) if pairsbedfile : fwpairs = must_open ( pairsbedfile , "w" ) clones = defaultdict ( list ) for row in fp : b = BedLine ( row ) name = b . accn clonename = clone_name ( name , ca = ca ) clones [ clonename ] . append ( b ) if matesfile : fp = open ( matesfile ) libraryline = next ( fp ) lib , name , smin , smax = libraryline . split ( ) assert lib == "library" smin , smax = int ( smin ) , int ( smax ) logging . debug ( "Happy mates for lib {0} fall between {1} - {2}" . format ( name , smin , smax ) ) nbedpe = 0 nspan = 0 for clonename , blines in clones . items ( ) : nlines = len ( blines ) if nlines == 2 : a , b = blines aseqid , astart , aend = a . seqid , a . start , a . end bseqid , bstart , bend = b . seqid , b . start , b . end outcols = [ aseqid , astart - 1 , aend , bseqid , bstart - 1 , bend , clonename ] if strand : outcols . extend ( [ 0 , a . strand , b . strand ] ) print ( "\t" . join ( str ( x ) for x in outcols ) , file = fw ) nbedpe += 1 elif nlines == 1 : a , = blines aseqid , astart , aend = a . seqid , a . start , a . end bseqid , bstart , bend = 0 , 0 , 0 else : pass if pairsbedfile : start = min ( astart , bstart ) if bstart > 0 else astart end = max ( aend , bend ) if bend > 0 else aend if aseqid != bseqid : continue span = end - start + 1 if ( not matesfile ) or ( smin <= span <= smax ) : print ( "\t" . join ( str ( x ) for x in ( aseqid , start - 1 , end , clonename ) ) , file = fwpairs ) nspan += 1 fw . close ( ) logging . debug ( "A total of {0} bedpe written to `{1}`." . format ( nbedpe , bedpefile ) ) if pairsbedfile : fwpairs . close ( ) logging . debug ( "A total of {0} spans written to `{1}`." . format ( nspan , pairsbedfile ) )
This converts the bedfile to bedpefile assuming the reads are from CA .
11,746
def posmap ( args ) : p = OptionParser ( posmap . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( p . print_help ( ) ) frgscffile , fastafile , scf = args cmd = "faOneRecord {0} {1}" . format ( fastafile , scf ) scffastafile = scf + ".fasta" if not op . exists ( scffastafile ) : sh ( cmd , outfile = scffastafile ) sizesfile = scffastafile + ".sizes" sizes = Sizes ( scffastafile ) . mapping scfsize = sizes [ scf ] logging . debug ( "`{0}` has length of {1}." . format ( scf , scfsize ) ) gapsbedfile = scf + ".gaps.bed" if not op . exists ( gapsbedfile ) : args = [ scffastafile , "--bed" , "--mingap=100" ] gaps ( args ) posmapfile = scf + ".posmap" if not op . exists ( posmapfile ) : args = [ frgscffile , scf ] query ( args ) bedfile = scf + ".bed" if not op . exists ( bedfile ) : args = [ posmapfile ] bed ( args ) bedpefile = scf + ".bedpe" pairsbedfile = scf + ".pairs.bed" if not ( op . exists ( bedpefile ) and op . exists ( pairsbedfile ) ) : bed_to_bedpe ( bedfile , bedpefile , pairsbedfile = pairsbedfile , ca = True ) Coverage ( bedfile , sizesfile ) Coverage ( pairsbedfile , sizesfile )
%prog posmap frgscf . sorted scf . fasta scfID
11,747
def update ( self , pbar ) : if pbar . finished : return self . markers [ 0 ] self . curmark = ( self . curmark + 1 ) % len ( self . markers ) return self . markers [ self . curmark ]
Updates the widget to show the next marker or the first marker when finished
11,748
def _format_line ( self ) : 'Joins the widgets and justifies the line' widgets = '' . join ( self . _format_widgets ( ) ) if self . left_justify : return widgets . ljust ( self . term_width ) else : return widgets . rjust ( self . term_width )
Joins the widgets and justifies the line
11,749
def _update_widgets ( self ) : 'Checks all widgets for the time sensitive bit' self . _time_sensitive = any ( getattr ( w , 'TIME_SENSITIVE' , False ) for w in self . widgets )
Checks all widgets for the time sensitive bit
11,750
def prepare ( bedfile ) : pf = bedfile . rsplit ( "." , 1 ) [ 0 ] abedfile = pf + ".a.bed" bbedfile = pf + ".b.bed" fwa = open ( abedfile , "w" ) fwb = open ( bbedfile , "w" ) bed = Bed ( bedfile ) seen = set ( ) for b in bed : accns = b . accn . split ( ";" ) new_accns = [ ] for accn in accns : if ":" in accn : method , a = accn . split ( ":" , 1 ) if method in ( "liftOver" , "GMAP" , "" ) : accn = a if accn in seen : logging . error ( "Duplicate id {0} found. Ignored." . format ( accn ) ) continue new_accns . append ( accn ) b . accn = accn print ( b , file = fwa ) seen . add ( accn ) b . accn = ";" . join ( new_accns ) print ( b , file = fwb ) fwa . close ( ) fwb . close ( )
Remove prepended tags in gene names .
11,751
def renumber ( args ) : from jcvi . algorithms . lis import longest_increasing_subsequence from jcvi . utils . grouper import Grouper p = OptionParser ( renumber . __doc__ ) p . set_annot_reformat_opts ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) bedfile , = args pf = bedfile . rsplit ( "." , 1 ) [ 0 ] abedfile = pf + ".a.bed" bbedfile = pf + ".b.bed" if need_update ( bedfile , ( abedfile , bbedfile ) ) : prepare ( bedfile ) mbed = Bed ( bbedfile ) g = Grouper ( ) for s in mbed : accn = s . accn g . join ( * accn . split ( ";" ) ) bed = Bed ( abedfile ) for chr , sbed in bed . sub_beds ( ) : current_chr = chr_number ( chr ) if not current_chr : continue ranks = [ ] gg = set ( ) for s in sbed : accn = s . accn achr , arank = atg_name ( accn ) if achr != current_chr : continue ranks . append ( arank ) gg . add ( accn ) lranks = longest_increasing_subsequence ( ranks ) print ( current_chr , len ( sbed ) , "==>" , len ( ranks ) , "==>" , len ( lranks ) , file = sys . stderr ) granks = set ( gene_name ( current_chr , x , prefix = opts . prefix , pad0 = opts . pad0 , uc = opts . uc ) for x in lranks ) | set ( gene_name ( current_chr , x , prefix = opts . prefix , pad0 = opts . pad0 , sep = "te" , uc = opts . uc ) for x in lranks ) tagstore = { } for s in sbed : achr , arank = atg_name ( s . accn ) accn = s . accn if accn in granks : tag = ( accn , FRAME ) elif accn in gg : tag = ( accn , RETAIN ) else : tag = ( "." , NEW ) tagstore [ accn ] = tag for s in sbed : accn = s . accn gaccn = g [ accn ] tags = [ ( ( tagstore [ x ] [ - 1 ] if x in tagstore else NEW ) , x ) for x in gaccn ] group = [ ( PRIORITY . index ( tag ) , x ) for tag , x in tags ] best = min ( group ) [ - 1 ] if accn != best : tag = ( best , OVERLAP ) else : tag = tagstore [ accn ] print ( "\t" . join ( ( str ( s ) , "|" . join ( tag ) ) ) )
%prog renumber Mt35 . consolidated . bed > tagged . bed
11,752
def publocus ( args ) : p = OptionParser ( publocus . __doc__ ) p . add_option ( "--locus_tag" , default = "MTR_" , help = "GenBank locus tag [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) locus_tag = opts . locus_tag index = AutoVivification ( ) idsfile , = args fp = must_open ( idsfile ) for row in fp : locus , chrom , sep , rank , iso = atg_name ( row , retval = "locus,chr,sep,rank,iso" ) if None in ( locus , chrom , sep , rank , iso ) : logging . warning ( "{0} is not a valid gene model identifier" . format ( row ) ) continue if locus not in index . keys ( ) : pub_locus = gene_name ( chrom , rank , prefix = locus_tag , sep = sep ) index [ locus ] [ 'pub_locus' ] = pub_locus index [ locus ] [ 'isos' ] = set ( ) index [ locus ] [ 'isos' ] . add ( int ( iso ) ) for locus in index : pub_locus = index [ locus ] [ 'pub_locus' ] index [ locus ] [ 'isos' ] = sorted ( index [ locus ] [ 'isos' ] ) if len ( index [ locus ] [ 'isos' ] ) > 1 : new = [ chr ( n + 64 ) for n in index [ locus ] [ 'isos' ] if n < 27 ] for i , ni in zip ( index [ locus ] [ 'isos' ] , new ) : print ( "\t" . join ( x for x in ( "{0}.{1}" . format ( locus , i ) , "{0}{1}" . format ( pub_locus , ni ) ) ) ) else : print ( "\t" . join ( x for x in ( "{0}.{1}" . format ( locus , index [ locus ] [ 'isos' ] [ 0 ] ) , pub_locus ) ) )
%prog publocus idsfile > idsfiles . publocus
11,753
def augustus ( args ) : from jcvi . formats . gff import Gff p = OptionParser ( augustus . __doc__ ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) ingff3 , = args gff = Gff ( ingff3 ) fw = must_open ( opts . outfile , "w" ) seen = defaultdict ( int ) for g in gff : if g . type not in ( "gene" , "transcript" , "CDS" ) : continue if g . type == "transcript" : g . type = "mRNA" prefix = g . seqid + "_" pid = prefix + g . id newid = "{0}-{1}" . format ( pid , seen [ pid ] ) if pid in seen else pid seen [ pid ] += 1 g . attributes [ "ID" ] = [ newid ] g . attributes [ "Parent" ] = [ ( prefix + x ) for x in g . attributes [ "Parent" ] ] g . update_attributes ( ) print ( g , file = fw ) fw . close ( )
%prog augustus augustus . gff3 > reformatted . gff3
11,754
def tRNAscan ( args ) : from jcvi . formats . gff import sort p = OptionParser ( tRNAscan . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) trnaout , = args gffout = trnaout + ".gff3" fp = open ( trnaout ) fw = open ( gffout , "w" ) next ( fp ) next ( fp ) row = next ( fp ) assert row . startswith ( "--------" ) for row in fp : atoms = [ x . strip ( ) for x in row . split ( "\t" ) ] contig , trnanum , start , end , aa , codon , intron_start , intron_end , score = atoms start , end = int ( start ) , int ( end ) orientation = '+' if start > end : start , end = end , start orientation = '-' source = "tRNAscan" type = "tRNA" if codon == "???" : codon = "XXX" comment = "ID={0}.tRNA.{1};Name=tRNA-{2} (anticodon: {3})" . format ( contig , trnanum , aa , codon ) print ( "\t" . join ( str ( x ) for x in ( contig , source , type , start , end , score , orientation , "." , comment ) ) , file = fw ) fw . close ( ) sort ( [ gffout , "-i" ] )
%prog tRNAscan all . trna > all . trna . gff3
11,755
def summary ( args ) : p = OptionParser ( summary . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) fastafile , = args f = Fasta ( fastafile , index = False ) halfmaskedseqs = set ( ) allmasked = 0 allbases = 0 cutoff = 50 for key , seq in f . iteritems ( ) : masked = 0 for base in seq : if base not in "AGCT" : masked += 1 seqlen = len ( seq ) if masked * 100. / seqlen > cutoff : halfmaskedseqs . add ( key ) allmasked += masked allbases += seqlen seqnum = len ( f ) maskedseqnum = len ( halfmaskedseqs ) print ( "Total masked bases: {0}" . format ( percentage ( allmasked , allbases ) ) , file = sys . stderr ) print ( "Total masked sequences (contain > {0}% masked): {1}" . format ( cutoff , percentage ( maskedseqnum , seqnum ) ) , file = sys . stderr )
%prog summary fastafile
11,756
def find_synteny_region ( query , sbed , data , window , cutoff , colinear = False ) : regions = [ ] ysorted = sorted ( data , key = lambda x : x [ 1 ] ) g = Grouper ( ) a , b = tee ( ysorted ) next ( b , None ) for ia , ib in izip ( a , b ) : pos1 , pos2 = ia [ 1 ] , ib [ 1 ] if pos2 - pos1 < window and sbed [ pos1 ] . seqid == sbed [ pos2 ] . seqid : g . join ( ia , ib ) for group in sorted ( g ) : ( qflanker , syntelog ) , ( far_flanker , far_syntelog ) , flanked = get_flanker ( group , query ) if colinear : y_indexed_group = [ ( y , i ) for i , ( x , y ) in enumerate ( group ) ] lis = longest_increasing_subsequence ( y_indexed_group ) lds = longest_decreasing_subsequence ( y_indexed_group ) if len ( lis ) >= len ( lds ) : track = lis orientation = "+" else : track = lds orientation = "-" group = [ group [ i ] for ( y , i ) in track ] xpos , ypos = zip ( * group ) score = min ( len ( set ( xpos ) ) , len ( set ( ypos ) ) ) if qflanker == query : gray = "S" else : gray = "G" if not flanked else "F" score -= 1 if score < cutoff : continue left , right = group [ 0 ] [ 1 ] , group [ - 1 ] [ 1 ] syn_region = ( syntelog , far_syntelog , left , right , gray , orientation , score ) regions . append ( syn_region ) return sorted ( regions , key = lambda x : - x [ - 1 ] )
Get all synteny blocks for a query algorithm is single linkage anchors are a window centered on query
11,757
def get_segments ( ranges , extra , minsegment = 40 ) : from jcvi . utils . range import range_chain , LEFT , RIGHT NUL = 2 selected , score = range_chain ( ranges ) endpoints = [ ( x . start , NUL ) for x in selected ] endpoints += [ ( x [ 0 ] , LEFT ) for x in extra ] endpoints += [ ( x [ 1 ] , RIGHT ) for x in extra ] endpoints . sort ( ) current_left = 0 for a , ai in endpoints : if ai == LEFT : current_left = a if ai == RIGHT : yield current_left , a elif ai == NUL : if a - current_left < minsegment : continue yield current_left , a - 1 current_left = a
Given a list of Range perform chaining on the ranges and select a highest scoring subset and cut based on their boundaries . Let s say the projection of the synteny blocks onto one axis look like the following .
11,758
def entropy ( args ) : p = OptionParser ( entropy . __doc__ ) p . add_option ( "--threshold" , default = 0 , type = "int" , help = "Complexity needs to be above" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) kmc_out , = args fp = open ( kmc_out ) for row in fp : kmer , count = row . split ( ) score = entropy_score ( kmer ) if score >= opts . threshold : print ( " " . join ( ( kmer , count , "{:.2f}" . format ( score ) ) ) )
%prog entropy kmc_dump . out
11,759
def bed ( args ) : from jcvi . formats . fasta import rc , parse_fasta p = OptionParser ( bed . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) fastafile , dumpfile = args fp = open ( dumpfile ) KMERS = set ( ) for row in fp : kmer = row . split ( ) [ 0 ] kmer_rc = rc ( kmer ) KMERS . add ( kmer ) KMERS . add ( kmer_rc ) K = len ( kmer ) logging . debug ( "Imported {} {}-mers" . format ( len ( KMERS ) , K ) ) for name , seq in parse_fasta ( fastafile ) : name = name . split ( ) [ 0 ] for i in range ( len ( seq ) - K ) : if i % 5000000 == 0 : print ( "{}:{}" . format ( name , i ) , file = sys . stderr ) kmer = seq [ i : i + K ] if kmer in KMERS : print ( "\t" . join ( str ( x ) for x in ( name , i , i + K , kmer ) ) )
%prog bed fastafile kmer . dump . txt
11,760
def kmc ( args ) : p = OptionParser ( kmc . __doc__ ) p . add_option ( "-k" , default = 21 , type = "int" , help = "Kmer size" ) p . add_option ( "--ci" , default = 2 , type = "int" , help = "Exclude kmers with less than ci counts" ) p . add_option ( "--cs" , default = 2 , type = "int" , help = "Maximal value of a counter" ) p . add_option ( "--cx" , default = None , type = "int" , help = "Exclude kmers with more than cx counts" ) p . add_option ( "--single" , default = False , action = "store_true" , help = "Input is single-end data, only one FASTQ/FASTA" ) p . add_option ( "--fasta" , default = False , action = "store_true" , help = "Input is FASTA instead of FASTQ" ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) folder , = args K = opts . k n = 1 if opts . single else 2 pattern = "*.fa,*.fa.gz,*.fasta,*.fasta.gz" if opts . fasta else "*.fq,*.fq.gz,*.fastq,*.fastq.gz" mm = MakeManager ( ) for p , pf in iter_project ( folder , pattern = pattern , n = n , commonprefix = False ) : pf = pf . split ( "_" ) [ 0 ] + ".ms{}" . format ( K ) infiles = pf + ".infiles" fw = open ( infiles , "w" ) print ( "\n" . join ( p ) , file = fw ) fw . close ( ) cmd = "kmc -k{} -m64 -t{}" . format ( K , opts . cpus ) cmd += " -ci{} -cs{}" . format ( opts . ci , opts . cs ) if opts . cx : cmd += " -cx{}" . format ( opts . cx ) if opts . fasta : cmd += " -fm" cmd += " @{} {} ." . format ( infiles , pf ) outfile = pf + ".kmc_suf" mm . add ( p , outfile , cmd ) mm . write ( )
%prog kmc folder
11,761
def meryl ( args ) : p = OptionParser ( meryl . __doc__ ) p . add_option ( "-k" , default = 19 , type = "int" , help = "Kmer size" ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) folder , = args K = opts . k cpus = opts . cpus mm = MakeManager ( ) for p , pf in iter_project ( folder ) : cmds = [ ] mss = [ ] for i , ip in enumerate ( p ) : ms = "{}{}.ms{}" . format ( pf , i + 1 , K ) mss . append ( ms ) cmd = "meryl -B -C -m {} -threads {}" . format ( K , cpus ) cmd += " -s {} -o {}" . format ( ip , ms ) cmds . append ( cmd ) ams , bms = mss pms = "{}.ms{}" . format ( pf , K ) cmd = "meryl -M add -s {} -s {} -o {}" . format ( ams , bms , pms ) cmds . append ( cmd ) cmd = "rm -f {}.mcdat {}.mcidx {}.mcdat {}.mcidx" . format ( ams , ams , bms , bms ) cmds . append ( cmd ) mm . add ( p , pms + ".mcdat" , cmds ) mm . write ( )
%prog meryl folder
11,762
def model ( args ) : from scipy . stats import binom , poisson p = OptionParser ( model . __doc__ ) p . add_option ( "-k" , default = 23 , type = "int" , help = "Kmer size" ) p . add_option ( "--cov" , default = 50 , type = "int" , help = "Expected coverage" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) erate , = args erate = float ( erate ) cov = opts . cov k = opts . k xy = [ ] for c in xrange ( 0 , cov * 2 + 1 ) : Prob_Yk = 0 for i in xrange ( k + 1 ) : pi_i = binom . pmf ( i , k , erate ) mu_i = cov * ( erate / 3 ) ** i * ( 1 - erate ) ** ( k - i ) Prob_Yk_i = poisson . pmf ( c , mu_i ) Prob_Yk += pi_i * Prob_Yk_i xy . append ( ( c , Prob_Yk ) ) x , y = zip ( * xy ) asciiplot ( x , y , title = "Model" )
%prog model erate
11,763
def logodds ( args ) : from math import log from jcvi . formats . base import DictFile p = OptionParser ( logodds . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) cnt1 , cnt2 = args d = DictFile ( cnt2 ) fp = open ( cnt1 ) for row in fp : scf , c1 = row . split ( ) c2 = d [ scf ] c1 , c2 = float ( c1 ) , float ( c2 ) c1 += 1 c2 += 1 score = int ( 100 * ( log ( c1 ) - log ( c2 ) ) ) print ( "{0}\t{1}" . format ( scf , score ) )
%prog logodds cnt1 cnt2
11,764
def count ( args ) : from bitarray import bitarray p = OptionParser ( count . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) fastafile , jfdb = args K = get_K ( jfdb ) cmd = "jellyfish query {0} -C | cut -d' ' -f 2" . format ( jfdb ) t = must_open ( "tmp" , "w" ) proc = Popen ( cmd , stdin = PIPE , stdout = t ) t . flush ( ) f = Fasta ( fastafile , lazy = True ) for name , rec in f . iteritems_ordered ( ) : kmers = list ( make_kmers ( rec . seq , K ) ) print ( "\n" . join ( kmers ) , file = proc . stdin ) proc . stdin . close ( ) logging . debug ( cmd ) proc . wait ( ) a = bitarray ( ) binfile = "." . join ( ( fastafile , jfdb , "bin" ) ) fw = open ( binfile , "w" ) t . seek ( 0 ) for row in t : c = row . strip ( ) a . append ( int ( c ) ) a . tofile ( fw ) logging . debug ( "Serialize {0} bits to `{1}`." . format ( len ( a ) , binfile ) ) fw . close ( ) sh ( "rm {0}" . format ( t . name ) ) logging . debug ( "Shared K-mers (K={0}) between `{1}` and `{2}` written to `{3}`." . format ( K , fastafile , jfdb , binfile ) ) cntfile = "." . join ( ( fastafile , jfdb , "cnt" ) ) bincount ( [ fastafile , binfile , "-o" , cntfile , "-K {0}" . format ( K ) ] ) logging . debug ( "Shared K-mer counts written to `{0}`." . format ( cntfile ) )
%prog count fastafile jf . db
11,765
def bincount ( args ) : from bitarray import bitarray from jcvi . formats . sizes import Sizes p = OptionParser ( bincount . __doc__ ) p . add_option ( "-K" , default = 23 , type = "int" , help = "K-mer size [default: %default]" ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) fastafile , binfile = args K = opts . K fp = open ( binfile ) a = bitarray ( ) a . fromfile ( fp ) f = Sizes ( fastafile ) tsize = 0 fw = must_open ( opts . outfile , "w" ) for name , seqlen in f . iter_sizes ( ) : ksize = seqlen - K + 1 b = a [ tsize : tsize + ksize ] bcount = b . count ( ) print ( "\t" . join ( str ( x ) for x in ( name , bcount ) ) , file = fw ) tsize += ksize
%prog bincount fastafile binfile
11,766
def bin ( args ) : from bitarray import bitarray p = OptionParser ( bin . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) inp , outp = args fp = must_open ( inp ) fw = must_open ( outp , "w" ) a = bitarray ( ) for row in fp : c = row . split ( ) [ - 1 ] a . append ( int ( c ) ) a . tofile ( fw ) fw . close ( )
%prog bin filename filename . bin
11,767
def dump ( args ) : p = OptionParser ( dump . __doc__ ) p . add_option ( "-K" , default = 23 , type = "int" , help = "K-mer size [default: %default]" ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) fastafile , = args K = opts . K fw = must_open ( opts . outfile , "w" ) f = Fasta ( fastafile , lazy = True ) for name , rec in f . iteritems_ordered ( ) : kmers = list ( make_kmers ( rec . seq , K ) ) print ( "\n" . join ( kmers ) , file = fw ) fw . close ( )
%prog dump fastafile
11,768
def nucmer ( args ) : from itertools import product from jcvi . apps . grid import MakeManager from jcvi . formats . base import split p = OptionParser ( nucmer . __doc__ ) p . add_option ( "--chunks" , type = "int" , help = "Split both query and subject into chunks" ) p . set_params ( prog = "nucmer" , params = "-l 100 -c 500" ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) ref , query = args cpus = opts . cpus nrefs = nqueries = opts . chunks or int ( cpus ** .5 ) refdir = ref . split ( "." ) [ 0 ] + "-outdir" querydir = query . split ( "." ) [ 0 ] + "-outdir" reflist = split ( [ ref , refdir , str ( nrefs ) ] ) . names querylist = split ( [ query , querydir , str ( nqueries ) ] ) . names mm = MakeManager ( ) for i , ( r , q ) in enumerate ( product ( reflist , querylist ) ) : pf = "{0:04d}" . format ( i ) cmd = "nucmer -maxmatch" cmd += " {0}" . format ( opts . extra ) cmd += " {0} {1} -p {2}" . format ( r , q , pf ) deltafile = pf + ".delta" mm . add ( ( r , q ) , deltafile , cmd ) print ( cmd ) mm . write ( )
%prog nucmer ref . fasta query . fasta
11,769
def blasr ( args ) : from jcvi . apps . grid import MakeManager from jcvi . utils . iter import grouper p = OptionParser ( blasr . __doc__ ) p . set_cpus ( cpus = 8 ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) reffasta , fofn = args flist = sorted ( [ x . strip ( ) for x in open ( fofn ) ] ) h5list = [ ] mm = MakeManager ( ) for i , fl in enumerate ( grouper ( flist , 3 ) ) : chunkname = "chunk{0:03d}" . format ( i ) fn = chunkname + ".fofn" h5 = chunkname + ".cmp.h5" fw = open ( fn , "w" ) print ( "\n" . join ( fl ) , file = fw ) fw . close ( ) cmd = "pbalign {0} {1} {2}" . format ( fn , reffasta , h5 ) cmd += " --nproc {0} --forQuiver --tmpDir ." . format ( opts . cpus ) mm . add ( ( fn , reffasta ) , h5 , cmd ) h5list . append ( h5 ) allh5 = "all.cmp.h5" tmph5 = "tmp.cmp.h5" cmd_merge = "cmph5tools.py merge --outFile {0}" . format ( allh5 ) cmd_merge += " " + " " . join ( h5list ) cmd_sort = "cmph5tools.py sort --deep {0} --tmpDir ." . format ( allh5 ) cmd_repack = "h5repack -f GZIP=1 {0} {1}" . format ( allh5 , tmph5 ) cmd_repack += " && mv {0} {1}" . format ( tmph5 , allh5 ) mm . add ( h5list , allh5 , [ cmd_merge , cmd_sort , cmd_repack ] ) pf = reffasta . rsplit ( "." , 1 ) [ 0 ] variantsgff = pf + ".variants.gff" consensusfasta = pf + ".consensus.fasta" cmd_faidx = "samtools faidx {0}" . format ( reffasta ) cmd = "quiver -j 32 {0}" . format ( allh5 ) cmd += " -r {0} -o {1} -o {2}" . format ( reffasta , variantsgff , consensusfasta ) mm . add ( allh5 , consensusfasta , [ cmd_faidx , cmd ] ) mm . write ( )
%prog blasr ref . fasta fofn
11,770
def blat ( args ) : p = OptionParser ( blat . __doc__ ) p . set_align ( pctid = 95 , hitlen = 30 ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) reffasta , queryfasta = args blastfile = get_outfile ( reffasta , queryfasta , suffix = "blat" ) run_blat ( infile = queryfasta , outfile = blastfile , db = reffasta , pctid = opts . pctid , hitlen = opts . hitlen , cpus = opts . cpus , overwrite = False ) return blastfile
%prog blat ref . fasta query . fasta
11,771
def blast ( args ) : task_choices = ( "blastn" , "blastn-short" , "dc-megablast" , "megablast" , "vecscreen" ) p = OptionParser ( blast . __doc__ ) p . set_align ( pctid = 0 , evalue = .01 ) p . add_option ( "--wordsize" , type = "int" , help = "Word size [default: %default]" ) p . add_option ( "--best" , default = 1 , type = "int" , help = "Only look for best N hits [default: %default]" ) p . add_option ( "--task" , default = "megablast" , choices = task_choices , help = "Task of the blastn [default: %default]" ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) reffasta , queryfasta = args blastfile = get_outfile ( reffasta , queryfasta ) run_megablast ( infile = queryfasta , outfile = blastfile , db = reffasta , wordsize = opts . wordsize , pctid = opts . pctid , evalue = opts . evalue , hitlen = None , best = opts . best , task = opts . task , cpus = opts . cpus ) return blastfile
%prog blast ref . fasta query . fasta
11,772
def lastgenome ( args ) : from jcvi . apps . grid import MakeManager p = OptionParser ( lastgenome . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) gA , gB = args mm = MakeManager ( ) bb = lambda x : op . basename ( x ) . rsplit ( "." , 1 ) [ 0 ] gA_pf , gB_pf = bb ( gA ) , bb ( gB ) dbname = "-" . join ( ( gA_pf , "NEAR" ) ) dbfile = dbname + ".suf" build_db_cmd = "lastdb -P0 -uNEAR -R01 {} {}" . format ( dbfile , gA ) mm . add ( gA , dbfile , build_db_cmd ) maffile = "{}.{}.1-1.maf" . format ( gA_pf , gB_pf ) lastal_cmd = "lastal -E0.05 -C2 {} {}" . format ( dbname , gB ) lastal_cmd += " | last-split -m1" lastal_cmd += " | maf-swap" lastal_cmd += " | last-split -m1 -fMAF > {}" . format ( maffile ) mm . add ( [ dbfile , gB ] , maffile , lastal_cmd ) blastfile = maffile . replace ( ".maf" , ".blast" ) convert_cmd = "maf-convert -n blasttab {} > {}" . format ( maffile , blastfile ) mm . add ( maffile , blastfile , convert_cmd ) mm . write ( )
%prog genome_A . fasta genome_B . fasta
11,773
def last ( args , dbtype = None ) : p = OptionParser ( last . __doc__ ) p . add_option ( "--dbtype" , default = "nucl" , choices = ( "nucl" , "prot" ) , help = "Molecule type of subject database" ) p . add_option ( "--path" , help = "Specify LAST path" ) p . add_option ( "--mask" , default = False , action = "store_true" , help = "Invoke -c in lastdb" ) p . add_option ( "--format" , default = "BlastTab" , choices = ( "TAB" , "MAF" , "BlastTab" , "BlastTab+" ) , help = "Output format" ) p . add_option ( "--minlen" , default = 0 , type = "int" , help = "Filter alignments by how many bases match" ) p . add_option ( "--minid" , default = 0 , type = "int" , help = "Minimum sequence identity" ) p . set_cpus ( ) p . set_params ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) subject , query = args path = opts . path cpus = opts . cpus if not dbtype : dbtype = opts . dbtype getpath = lambda x : op . join ( path , x ) if path else x lastdb_bin = getpath ( "lastdb" ) lastal_bin = getpath ( "lastal" ) subjectdb = subject . rsplit ( "." , 1 ) [ 0 ] run_lastdb ( infile = subject , outfile = subjectdb + ".prj" , mask = opts . mask , lastdb_bin = lastdb_bin , dbtype = dbtype ) u = 2 if opts . mask else 0 cmd = "{0} -u {1}" . format ( lastal_bin , u ) cmd += " -P {0} -i3G" . format ( cpus ) cmd += " -f {0}" . format ( opts . format ) cmd += " {0} {1}" . format ( subjectdb , query ) minlen = opts . minlen minid = opts . minid extra = opts . extra assert minid != 100 , "Perfect match not yet supported" mm = minid / ( 100 - minid ) if minlen : extra += " -e{0}" . format ( minlen ) if minid : extra += " -r1 -q{0} -a{0} -b{0}" . format ( mm ) if extra : cmd += " " + extra . strip ( ) lastfile = get_outfile ( subject , query , suffix = "last" ) sh ( cmd , outfile = lastfile )
%prog database . fasta query . fasta
11,774
def fillstats ( args ) : from jcvi . utils . cbook import SummaryStats , percentage , thousands p = OptionParser ( fillstats . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) fillfile , = args fp = open ( fillfile ) scaffolds = 0 gaps = [ ] for row in fp : if row [ 0 ] == ">" : scaffolds += 1 continue fl = FillLine ( row ) gaps . append ( fl ) print ( "{0} scaffolds in total" . format ( scaffolds ) , file = sys . stderr ) closed = [ x for x in gaps if x . closed ] closedbp = sum ( x . before for x in closed ) notClosed = [ x for x in gaps if not x . closed ] notClosedbp = sum ( x . before for x in notClosed ) totalgaps = len ( closed ) + len ( notClosed ) print ( "Closed gaps: {0} size: {1} bp" . format ( percentage ( len ( closed ) , totalgaps ) , thousands ( closedbp ) ) , file = sys . stderr ) ss = SummaryStats ( [ x . after for x in closed ] ) print ( ss , file = sys . stderr ) ss = SummaryStats ( [ x . delta for x in closed ] ) print ( "Delta:" , ss , file = sys . stderr ) print ( "Remaining gaps: {0} size: {1} bp" . format ( percentage ( len ( notClosed ) , totalgaps ) , thousands ( notClosedbp ) ) , file = sys . stderr ) ss = SummaryStats ( [ x . after for x in notClosed ] ) print ( ss , file = sys . stderr )
%prog fillstats genome . fill
11,775
def bed ( args ) : p = OptionParser ( bed . __doc__ ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) pslfile , = args fw = must_open ( opts . outfile , "w" ) psl = Psl ( pslfile ) for p in psl : print ( p . bed12line , file = fw )
%prog bed pslfile
11,776
def gff ( args ) : p = OptionParser ( gff . __doc__ ) p . add_option ( "--source" , default = "GMAP" , help = "specify GFF source [default: %default]" ) p . add_option ( "--type" , default = "EST_match" , help = "specify GFF feature type [default: %default]" ) p . add_option ( "--suffix" , default = ".match" , help = "match ID suffix [default: \"%default\"]" ) p . add_option ( "--swap" , default = False , action = "store_true" , help = "swap query and target features [default: %default]" ) p . add_option ( "--simple_score" , default = False , action = "store_true" , help = "calculate a simple percent score [default: %default]" ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) pslfile , = args fw = must_open ( opts . outfile , "w" ) print ( "##gff-version 3" , file = fw ) psl = Psl ( pslfile ) for p in psl : if opts . swap : p . swap psl . trackMatches ( p . qName ) p . qStart += 1 p . tStart += 1 print ( p . gffline ( source = opts . source , type = opts . type , suffix = opts . suffix , primary_tag = "ID" , alt_score = opts . simple_score , count = psl . getMatchCount ( p . qName ) ) , file = fw ) part = PslLine ( "\t" . join ( str ( x ) for x in [ 0 ] * p . nargs ) ) part . tName , part . qName , part . strand = p . tName , p . qName , p . strand nparts = len ( p . qStarts ) for n in xrange ( nparts ) : part . qStart , part . tStart , aLen = p . qStarts [ n ] + 1 , p . tStarts [ n ] + 1 , p . blockSizes [ n ] part . qEnd = part . qStart + aLen - 1 part . tEnd = part . tStart + aLen - 1 if part . strand == "-" : part . qStart = p . qSize - ( p . qStarts [ n ] + p . blockSizes [ n ] ) + 1 part . qEnd = p . qSize - p . qStarts [ n ] print ( part . gffline ( source = opts . source , suffix = opts . suffix , count = psl . getMatchCount ( part . qName ) ) , file = fw )
%prog gff pslfile
11,777
def _isProtein ( self ) : last = self . blockCount - 1 return ( ( self . tEnd == self . tStarts [ last ] + 3 * self . blockSizes [ last ] ) and self . strand == "+" ) or ( ( self . tStart == self . tSize - ( self . tStarts [ last ] + 3 * self . blockSizes [ last ] ) and self . strand == "-" ) )
check if blockSizes and scores are in the protein space or not
11,778
def _milliBad ( self , ismRNA = False ) : sizeMult = self . _sizeMult qAlnSize , tAlnSize = self . qspan * sizeMult , self . tspan alnSize = min ( qAlnSize , tAlnSize ) if alnSize <= 0 : return 0 sizeDiff = qAlnSize - tAlnSize if sizeDiff < 0 : sizeDiff = 0 if ismRNA else - sizeDiff insertFactor = self . qNumInsert if not ismRNA : insertFactor += self . tNumInsert total = ( self . matches + self . repMatches + self . misMatches ) * sizeMult return ( 1000 * ( self . misMatches * sizeMult + insertFactor + round ( 3 * math . log ( 1 + sizeDiff ) ) ) ) / total if total != 0 else 0
calculate badness in parts per thousand i . e . number of non - identical matches
11,779
def get_prefix ( dir = "../" ) : prefix = glob ( dir + "*.gkpStore" ) [ 0 ] prefix = op . basename ( prefix ) . rsplit ( "." , 1 ) [ 0 ] return prefix
Look for prefix . gkpStore in the upper directory .
11,780
def cnsfix ( args ) : from jcvi . formats . base import read_block p = OptionParser ( cnsfix . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) cnsfixout , = args fp = open ( cnsfixout ) utgs = [ ] saves = [ ] for header , contents in read_block ( fp , "Evaluating" ) : contents = list ( contents ) utg = header . split ( ) [ 2 ] utgs . append ( utg ) for c in contents : if not c . startswith ( "save" ) : continue ident = c . split ( ) [ 3 ] . split ( "=" ) [ - 1 ] saves . append ( ident ) print ( "\n" . join ( saves ) )
%prog cnsfix consensus - fix . out . FAILED > blacklist . ids
11,781
def error ( args ) : p = OptionParser ( error . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) version , backup_folder = args mkdir ( backup_folder ) fw = open ( "errors.log" , "w" ) seen = set ( ) for g in glob ( "../5-consensus/*.err" ) : if "partitioned" in g : continue fp = open ( g ) partID = op . basename ( g ) . rsplit ( ".err" , 1 ) [ 0 ] partID = int ( partID . split ( "_" ) [ - 1 ] ) for row in fp : if row . startswith ( working ) : unitigID = row . split ( "(" ) [ 0 ] . split ( ) [ - 1 ] continue if not failed . upper ( ) in row . upper ( ) : continue uu = ( version , partID , unitigID ) if uu in seen : continue seen . add ( uu ) print ( "\t" . join ( str ( x ) for x in ( partID , unitigID ) ) , file = fw ) s = [ str ( x ) for x in uu ] unitigfile = pull ( s ) cmd = "mv {0} {1}" . format ( unitigfile , backup_folder ) sh ( cmd ) fp . close ( ) logging . debug ( "A total of {0} unitigs saved to {1}." . format ( len ( seen ) , backup_folder ) )
%prog error version backup_folder
11,782
def cut ( args ) : from jcvi . formats . base import SetFile p = OptionParser ( cut . __doc__ ) p . add_option ( "-s" , dest = "shredafter" , default = False , action = "store_true" , help = "Shred fragments after the given fragID [default: %default]" ) p . add_option ( "--notest" , default = False , action = "store_true" , help = "Do not test the unitigfile after edits [default: %default]" ) p . add_option ( "--blacklist" , help = "File that contains blacklisted fragments to be popped " "[default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) s , fragID = args u = UnitigLayout ( s ) blacklist = opts . blacklist black = SetFile ( blacklist ) if blacklist else None if opts . shredafter : u . shredafter ( fragID ) elif black : assert fragID == "0" , "Must set fragID to 0 when --blacklist is on" u . pop ( black ) else : u . cut ( fragID ) u . print_to_file ( inplace = True ) if not opts . notest : test ( [ s ] )
%prog cut unitigfile fragID
11,783
def shred ( args ) : p = OptionParser ( shred . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) s , = args u = UnitigLayout ( s ) u . shred ( ) u . print_to_file ( inplace = True )
%prog shred unitigfile
11,784
def pull ( args ) : p = OptionParser ( pull . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) prefix = get_prefix ( ) version , partID , unitigID = args s = "." . join ( args ) cmd = "tigStore" cmd += " -g ../{0}.gkpStore -t ../{0}.tigStore" . format ( prefix ) cmd += " {0} -up {1} -d layout -u {2}" . format ( version , partID , unitigID ) unitigfile = "unitig" + s sh ( cmd , outfile = unitigfile ) return unitigfile
%prog pull version partID unitigID
11,785
def mtdotplots ( args ) : from jcvi . graphics . dotplot import check_beds , dotplot p = OptionParser ( mtdotplots . __doc__ ) p . set_beds ( ) opts , args , iopts = p . set_image_options ( args , figsize = "16x8" , dpi = 90 ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) a , b , ac = args fig = plt . figure ( 1 , ( iopts . w , iopts . h ) ) root = fig . add_axes ( [ 0 , 0 , 1 , 1 ] ) r1 = fig . add_axes ( [ 0 , 0 , .5 , 1 ] ) r2 = fig . add_axes ( [ .5 , 0 , .5 , 1 ] ) a1 = fig . add_axes ( [ .05 , .1 , .4 , .8 ] ) a2 = fig . add_axes ( [ .55 , .1 , .4 , .8 ] ) anchorfile = op . join ( a , ac ) qbed , sbed , qorder , sorder , is_self = check_beds ( anchorfile , p , opts ) dotplot ( anchorfile , qbed , sbed , fig , r1 , a1 , is_self = is_self , genomenames = "Mt3.5_Mt3.5" ) opts . qbed = opts . sbed = None anchorfile = op . join ( b , ac ) qbed , sbed , qorder , sorder , is_self = check_beds ( anchorfile , p , opts ) dotplot ( anchorfile , qbed , sbed , fig , r2 , a2 , is_self = is_self , genomenames = "Mt4.0_Mt4.0" ) root . text ( .03 , .95 , "A" , ha = "center" , va = "center" , size = 36 ) root . text ( .53 , .95 , "B" , ha = "center" , va = "center" , size = 36 ) root . set_xlim ( 0 , 1 ) root . set_ylim ( 0 , 1 ) root . set_axis_off ( ) pf = "mtdotplots" image_name = pf + "." + iopts . format savefig ( image_name , dpi = iopts . dpi , iopts = iopts )
%prog mtdotplots Mt3 . 5 Mt4 . 0 medicago . medicago . lifted . 1x1 . anchors
11,786
def oropetium ( args ) : p = OptionParser ( oropetium . __doc__ ) p . add_option ( "--extra" , help = "Extra features in BED format" ) opts , args , iopts = p . set_image_options ( args , figsize = "9x6" ) if len ( args ) != 4 : sys . exit ( not p . print_help ( ) ) datafile , bedfile , slayout , switch = args fig = plt . figure ( 1 , ( iopts . w , iopts . h ) ) root = fig . add_axes ( [ 0 , 0 , 1 , 1 ] ) Synteny ( fig , root , datafile , bedfile , slayout , switch = switch , extra_features = opts . extra ) draw_gene_legend ( root , .4 , .57 , .74 , text = True , repeat = True ) fc = 'lightslategrey' coords = { } xs , xp = .16 , .03 coords [ "oropetium" ] = ( xs , .7 ) coords [ "setaria" ] = ( xs , .6 ) coords [ "sorghum" ] = ( xs , .5 ) coords [ "rice" ] = ( xs , .4 ) coords [ "brachypodium" ] = ( xs , .3 ) xs -= xp coords [ "Panicoideae" ] = join_nodes ( root , coords , "setaria" , "sorghum" , xs ) xs -= xp coords [ "BEP" ] = join_nodes ( root , coords , "rice" , "brachypodium" , xs ) coords [ "PACMAD" ] = join_nodes ( root , coords , "oropetium" , "Panicoideae" , xs ) xs -= xp coords [ "Poaceae" ] = join_nodes ( root , coords , "BEP" , "PACMAD" , xs ) for tag in ( "BEP" , "Poaceae" ) : nx , ny = coords [ tag ] nx , ny = nx - .005 , ny - .02 root . text ( nx , ny , tag , rotation = 90 , ha = "right" , va = "top" , color = fc ) for tag in ( "PACMAD" , ) : nx , ny = coords [ tag ] nx , ny = nx - .005 , ny + .02 root . text ( nx , ny , tag , rotation = 90 , ha = "right" , va = "bottom" , color = fc ) root . set_xlim ( 0 , 1 ) root . set_ylim ( 0 , 1 ) root . set_axis_off ( ) pf = "oropetium" image_name = pf + "." + iopts . format savefig ( image_name , dpi = iopts . dpi , iopts = iopts )
%prog oropetium mcscan . out all . bed layout switch . ids
11,787
def amborella ( args ) : p = OptionParser ( amborella . __doc__ ) p . add_option ( "--tree" , help = "Display trees on the bottom of the figure [default: %default]" ) p . add_option ( "--switch" , help = "Rename the seqid with two-column file [default: %default]" ) opts , args , iopts = p . set_image_options ( args , figsize = "8x7" ) if len ( args ) != 5 : sys . exit ( not p . print_help ( ) ) seqidsfile , klayout , datafile , bedfile , slayout = args switch = opts . switch tree = opts . tree 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 = switch , tree = tree ) draw_gene_legend ( root , .5 , .68 , .5 ) fc = 'lightslategrey' x = .05 radius = .012 TextCircle ( root , x , .86 , '$\gamma$' , radius = radius ) TextCircle ( root , x , .95 , '$\epsilon$' , radius = radius ) root . plot ( [ x , x ] , [ .83 , .9 ] , ":" , color = fc , lw = 2 ) pts = plot_cap ( ( x , .95 ) , np . radians ( range ( - 70 , 250 ) ) , .02 ) x , y = zip ( * pts ) root . plot ( x , y , ":" , color = fc , lw = 2 ) root . set_xlim ( 0 , 1 ) root . set_ylim ( 0 , 1 ) root . set_axis_off ( ) pf = "amborella" image_name = pf + "." + iopts . format savefig ( image_name , dpi = iopts . dpi , iopts = iopts )
%prog amborella seqids karyotype . layout mcscan . out all . bed synteny . layout
11,788
def annotate ( args ) : from jcvi . formats . agp import AGP , bed , tidy p = OptionParser ( annotate . __doc__ ) p . add_option ( "--minsize" , default = 200 , help = "Smallest component size [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) agpfile , linkagebed , assemblyfasta = args linkagebed = Bed ( linkagebed ) spannedgaps = set ( ) for b in linkagebed : score = int ( b . score ) if score == 0 : spannedgaps . add ( ( b . accn , b . start , b . end ) ) agp = AGP ( agpfile ) newagpfile = agpfile . rsplit ( "." , 1 ) [ 0 ] + ".linkage.agp" newagp = open ( newagpfile , "w" ) contig_id = 0 minsize = opts . minsize for a in agp : if not a . is_gap : cs = a . component_span if cs < minsize : a . is_gap = True a . component_type = "N" a . gap_length = cs a . gap_type = "scaffold" a . linkage = "yes" a . linkage_evidence = [ ] else : contig_id += 1 a . component_id = "contig{0:04d}" . format ( contig_id ) a . component_beg = 1 a . component_end = cs a . component_type = "W" print ( a , file = newagp ) continue gapinfo = ( a . object , a . object_beg , a . object_end ) gaplen = a . gap_length if gaplen == 100 and gapinfo not in spannedgaps : a . component_type = "U" tag = "map" else : tag = "paired-ends" a . linkage_evidence . append ( tag ) print ( a , file = newagp ) newagp . close ( ) logging . debug ( "Annotated AGP written to `{0}`." . format ( newagpfile ) ) contigbed = assemblyfasta . rsplit ( "." , 1 ) [ 0 ] + ".contigs.bed" bedfile = bed ( [ newagpfile , "--nogaps" , "--outfile=" + contigbed ] ) contigfasta = fastaFromBed ( bedfile , assemblyfasta , name = True , stranded = True ) tidy ( [ newagpfile , contigfasta ] )
%prog annotate agpfile gaps . linkage . bed assembly . fasta
11,789
def estimate ( args ) : from collections import defaultdict from jcvi . formats . bed import intersectBed_wao from jcvi . formats . posmap import MatesFile p = OptionParser ( estimate . __doc__ ) p . add_option ( "--minlinks" , default = 3 , type = "int" , help = "Minimum number of links to place [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) gapsbed , spansbed , matesfile = args mf = MatesFile ( matesfile ) bed = Bed ( gapsbed ) order = bed . order gap2mate = defaultdict ( set ) mate2gap = defaultdict ( set ) for a , b in intersectBed_wao ( gapsbed , spansbed ) : gapsize = a . span if gapsize != 100 : continue gapname = a . accn if b is None : gap2mate [ gapname ] = set ( ) continue matename = b . accn gap2mate [ gapname ] . add ( matename ) mate2gap [ matename ] . add ( gapname ) omgapsbed = "gaps.linkage.bed" fw = open ( omgapsbed , "w" ) for gapname , mates in sorted ( gap2mate . items ( ) ) : i , b = order [ gapname ] nmates = len ( mates ) if nmates < opts . minlinks : print ( "{0}\t{1}" . format ( b , nmates ) , file = fw ) continue print ( gapname , mates ) fw . close ( )
%prog estimate gaps . bed all . spans . bed all . mates
11,790
def sizes ( args ) : from jcvi . formats . base import DictFile from jcvi . apps . align import blast p = OptionParser ( sizes . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) gapsbed , afasta , bfasta = args pf = gapsbed . rsplit ( "." , 1 ) [ 0 ] extbed = pf + ".ext.bed" extfasta = pf + ".ext.fasta" if need_update ( gapsbed , extfasta ) : extbed , extfasta = flanks ( [ gapsbed , afasta ] ) q = op . basename ( extfasta ) . split ( "." ) [ 0 ] r = op . basename ( bfasta ) . split ( "." ) [ 0 ] blastfile = "{0}.{1}.blast" . format ( q , r ) if need_update ( [ extfasta , bfasta ] , blastfile ) : blastfile = blast ( [ bfasta , extfasta , "--wordsize=50" , "--pctid=98" ] ) labelsfile = blast_to_twobeds ( blastfile ) labels = DictFile ( labelsfile , delimiter = '\t' ) bed = Bed ( gapsbed ) for b in bed : b . score = b . span accn = b . accn print ( "\t" . join ( ( str ( x ) for x in ( b . seqid , b . start - 1 , b . end , accn , b . score , labels . get ( accn , "na" ) ) ) ) )
%prog sizes gaps . bed a . fasta b . fasta
11,791
def flanks ( args ) : p = OptionParser ( flanks . __doc__ ) p . add_option ( "--extend" , default = 2000 , type = "int" , help = "Extend seq flanking the gaps [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) gapsbed , fastafile = args Ext = opts . extend sizes = Sizes ( fastafile ) . mapping bed = Bed ( gapsbed ) pf = gapsbed . rsplit ( "." , 1 ) [ 0 ] extbed = pf + ".ext.bed" fw = open ( extbed , "w" ) for i , b in enumerate ( bed ) : seqid = b . seqid gapname = b . accn size = sizes [ seqid ] prev_b = bed [ i - 1 ] if i > 0 else None next_b = bed [ i + 1 ] if i + 1 < len ( bed ) else None if prev_b and prev_b . seqid != seqid : prev_b = None if next_b and next_b . seqid != seqid : next_b = None start = prev_b . end + 1 if prev_b else 1 start , end = max ( start , b . start - Ext ) , b . start - 1 print ( "\t" . join ( str ( x ) for x in ( b . seqid , start - 1 , end , gapname + "L" ) ) , file = fw ) end = next_b . start - 1 if next_b else size start , end = b . end + 1 , min ( end , b . end + Ext ) print ( "\t" . join ( str ( x ) for x in ( b . seqid , start - 1 , end , gapname + "R" ) ) , file = fw ) fw . close ( ) extfasta = fastaFromBed ( extbed , fastafile , name = True ) return extbed , extfasta
%prog flanks gaps . bed fastafile
11,792
def index ( args ) : p = OptionParser ( index . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( p . print_help ( ) ) frgscffile , = args gzfile = frgscffile + ".gz" cmd = "bgzip -c {0}" . format ( frgscffile ) if not op . exists ( gzfile ) : sh ( cmd , outfile = gzfile ) tbifile = gzfile + ".tbi" cmd = "tabix -s 2 -b 3 -e 4 {0}" . format ( gzfile ) if not op . exists ( tbifile ) : sh ( cmd )
%prog index frgscf . sorted
11,793
def reads ( args ) : p = OptionParser ( reads . __doc__ ) p . add_option ( "-p" , dest = "prefix_length" , default = 4 , type = "int" , help = "group the reads based on the first N chars [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( p . print_help ( ) ) frgscffile , = args prefix_length = opts . prefix_length fp = open ( frgscffile ) keyfn = lambda : defaultdict ( int ) counts = defaultdict ( keyfn ) for row in fp : f = FrgScfLine ( row ) fi = f . fragmentID [ : prefix_length ] counts [ f . scaffoldID ] [ fi ] += 1 for scf , count in sorted ( counts . items ( ) ) : print ( "{0}\t{1}" . format ( scf , ", " . join ( "{0}:{1}" . format ( * x ) for x in sorted ( count . items ( ) ) ) ) )
%prog reads frgscffile
11,794
def bed ( args ) : p = OptionParser ( bed . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) frgscffile , = args bedfile = frgscffile . rsplit ( "." , 1 ) [ 0 ] + ".bed" fw = open ( bedfile , "w" ) fp = open ( frgscffile ) for row in fp : f = FrgScfLine ( row ) print ( f . bedline , file = fw ) logging . debug ( "File written to `{0}`." . format ( bedfile ) ) return bedfile
%prog bed frgscffile
11,795
def dup ( args ) : p = OptionParser ( dup . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( p . print_help ( ) ) frgscffile , = args fp = open ( frgscffile ) data = [ FrgScfLine ( row ) for row in fp ] forward_data = [ x for x in data if x . orientation == '+' ] reverse_data = [ x for x in data if x . orientation == '-' ] counts = defaultdict ( int ) key = lambda x : ( x . scaffoldID , x . begin ) forward_data . sort ( key = key ) for k , data in groupby ( forward_data , key = key ) : data = list ( data ) count = len ( data ) counts [ count ] += 1 key = lambda x : ( x . scaffoldID , x . end ) reverse_data . sort ( key = key ) for k , data in groupby ( forward_data , key = key ) : data = list ( data ) count = len ( data ) counts [ count ] += 1 prefix = frgscffile . split ( "." ) [ 0 ] print ( "Duplication level in `{0}`" . format ( prefix ) , file = sys . stderr ) print ( "=" * 40 , file = sys . stderr ) for c , v in sorted ( counts . items ( ) ) : if c > 10 : break label = "unique" if c == 1 else "{0} copies" . format ( c ) print ( "{0}: {1}" . format ( label , v ) , file = sys . stderr )
%prog dup frgscffile
11,796
def _score ( cluster ) : x , y = zip ( * cluster ) [ : 2 ] return min ( len ( set ( x ) ) , len ( set ( y ) ) )
score of the cluster in this case is the number of non - repetitive matches
11,797
def read_blast ( blast_file , qorder , sorder , is_self = False , ostrip = True ) : filtered_blast = [ ] seen = set ( ) bl = Blast ( blast_file ) for b in bl : query , subject = b . query , b . subject if query == subject : continue if ostrip : query , subject = gene_name ( query ) , gene_name ( subject ) if query not in qorder or subject not in sorder : continue qi , q = qorder [ query ] si , s = sorder [ subject ] if is_self : if qi > si : query , subject = subject , query qi , si = si , qi q , s = s , q if q . seqid == s . seqid and si - qi < 40 : continue key = query , subject if key in seen : continue seen . add ( key ) b . qseqid , b . sseqid = q . seqid , s . seqid b . qi , b . si = qi , si b . query , b . subject = query , subject filtered_blast . append ( b ) logging . debug ( "A total of {0} BLAST imported from `{1}`." . format ( len ( filtered_blast ) , blast_file ) ) return filtered_blast
Read the blast and convert name into coordinates
11,798
def add_options ( p , args , dist = 10 ) : p . set_beds ( ) p . add_option ( "--dist" , default = dist , type = "int" , help = "Extent of flanking regions to search [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) blast_file , anchor_file = args return blast_file , anchor_file , opts . dist , opts
scan and liftover has similar interfaces so share common options returns opts files
11,799
def layout ( args ) : from jcvi . algorithms . ec import GA_setup , GA_run p = OptionParser ( layout . __doc__ ) p . set_beds ( ) p . set_cpus ( cpus = 32 ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) simplefile , qseqids , sseqids = args qbed , sbed , qorder , sorder , is_self = check_beds ( simplefile , p , opts ) qseqids = qseqids . strip ( ) . split ( "," ) sseqids = sseqids . strip ( ) . split ( "," ) qseqids_ii = dict ( ( s , i ) for i , s in enumerate ( qseqids ) ) sseqids_ii = dict ( ( s , i ) for i , s in enumerate ( sseqids ) ) blocks = SimpleFile ( simplefile ) . blocks scores = defaultdict ( int ) for a , b , c , d , score , orientation , hl in blocks : qi , q = qorder [ a ] si , s = sorder [ c ] qseqid , sseqid = q . seqid , s . seqid if sseqid not in sseqids : continue scores [ sseqids_ii [ sseqid ] , qseqid ] += score data = [ ] for ( a , b ) , score in sorted ( scores . items ( ) ) : if b not in qseqids_ii : continue data . append ( ( qseqids_ii [ b ] , score ) ) tour = range ( len ( qseqids ) ) toolbox = GA_setup ( tour ) toolbox . register ( "evaluate" , colinear_evaluate_weights , data = data ) tour , fitness = GA_run ( toolbox , ngen = 100 , npop = 100 , cpus = opts . cpus ) tour = [ qseqids [ x ] for x in tour ] print ( "," . join ( tour ) )
%prog layout query . subject . simple query . seqids subject . seqids