idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
12,000
def beagle ( args ) : p = OptionParser ( beagle . __doc__ ) p . set_home ( "beagle" ) p . set_ref ( ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) vcffile , chr = args pf = vcffile . rsplit ( "." , 1 ) [ 0 ] outpf = pf + ".beagle" outfile = outpf + ".vcf.gz" mm = MakeManager ( ) beagle_cmd = opts . beagle_home kg = op . join ( opts . ref , "1000GP_Phase3" ) cmd = beagle_cmd + " gt={0}" . format ( vcffile ) cmd += " ref={0}/chr{1}.1kg.phase3.v5a.bref" . format ( kg , chr ) cmd += " map={0}/plink.chr{1}.GRCh37.map" . format ( kg , chr ) cmd += " out={0}" . format ( outpf ) cmd += " nthreads=16 gprobs=true" mm . add ( vcffile , outfile , cmd ) mm . write ( )
%prog beagle input . vcf 1
12,001
def impute ( args ) : from pyfaidx import Fasta p = OptionParser ( impute . __doc__ ) p . set_home ( "shapeit" ) p . set_home ( "impute" ) p . set_ref ( ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) vcffile , fastafile , chr = args mm = MakeManager ( ) pf = vcffile . rsplit ( "." , 1 ) [ 0 ] hapsfile = pf + ".haps" kg = op . join ( opts . ref , "1000GP_Phase3" ) shapeit_phasing ( mm , chr , vcffile , opts ) fasta = Fasta ( fastafile ) size = len ( fasta [ chr ] ) binsize = 5000000 bins = size / binsize if size % binsize : bins += 1 impute_cmd = op . join ( opts . impute_home , "impute2" ) chunks = [ ] for x in xrange ( bins + 1 ) : chunk_start = x * binsize + 1 chunk_end = min ( chunk_start + binsize - 1 , size ) outfile = pf + ".chunk{0:02d}.impute2" . format ( x ) mapfile = "{0}/genetic_map_chr{1}_combined_b37.txt" . format ( kg , chr ) rpf = "{0}/1000GP_Phase3_chr{1}" . format ( kg , chr ) cmd = impute_cmd + " -m {0}" . format ( mapfile ) cmd += " -known_haps_g {0}" . format ( hapsfile ) cmd += " -h {0}.hap.gz -l {0}.legend.gz" . format ( rpf ) cmd += " -Ne 20000 -int {0} {1}" . format ( chunk_start , chunk_end ) cmd += " -o {0} -allow_large_regions -seed 367946" . format ( outfile ) cmd += " && touch {0}" . format ( outfile ) mm . add ( hapsfile , outfile , cmd ) chunks . append ( outfile ) imputefile = pf + ".impute2" cmd = "cat {0} > {1}" . format ( " " . join ( chunks ) , imputefile ) mm . add ( chunks , imputefile , cmd ) vcffile = pf + ".impute2.vcf" cmd = "python -m jcvi.formats.vcf fromimpute2 {0} {1} {2} > {3}" . format ( imputefile , fastafile , chr , vcffile ) mm . add ( imputefile , vcffile , cmd ) mm . write ( )
%prog impute input . vcf hs37d5 . fa 1
12,002
def summary ( args ) : p = OptionParser ( summary . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) gff_file , ref = args s = Fasta ( ref ) g = make_index ( gff_file ) geneseqs , exonseqs , intronseqs = [ ] , [ ] , [ ] for f in g . features_of_type ( "gene" ) : fid = f . id fseq = s . sequence ( { 'chr' : f . chrom , 'start' : f . start , 'stop' : f . stop } ) geneseqs . append ( fseq ) exons = set ( ( c . chrom , c . start , c . stop ) for c in g . children ( fid , 2 ) if c . featuretype == "exon" ) exons = list ( exons ) for chrom , start , stop in exons : fseq = s . sequence ( { 'chr' : chrom , 'start' : start , 'stop' : stop } ) exonseqs . append ( fseq ) introns = range_interleave ( exons ) for chrom , start , stop in introns : fseq = s . sequence ( { 'chr' : chrom , 'start' : start , 'stop' : stop } ) intronseqs . append ( fseq ) r = { } for t , tseqs in zip ( ( "Gene" , "Exon" , "Intron" ) , ( geneseqs , exonseqs , intronseqs ) ) : tsizes = [ len ( x ) for x in tseqs ] tsummary = SummaryStats ( tsizes , dtype = "int" ) r [ t , "Number" ] = tsummary . size r [ t , "Average size (bp)" ] = tsummary . mean r [ t , "Median size (bp)" ] = tsummary . median r [ t , "Total length (Mb)" ] = human_size ( tsummary . sum , precision = 0 , target = "Mb" ) r [ t , "% of genome" ] = percentage ( tsummary . sum , s . totalsize , precision = 0 , mode = - 1 ) r [ t , "% GC" ] = gc ( tseqs ) print ( tabulate ( r ) , file = sys . stderr )
%prog summary gffile fastafile
12,003
def run ( self , clean = True ) : template = self . template parameters = self . parameters fw = must_open ( "tmp" , "w" ) path = fw . name fw . write ( template . safe_substitute ( ** parameters ) ) fw . close ( ) sh ( "Rscript %s" % path ) if clean : os . remove ( path ) rplotspdf = "Rplots.pdf" if op . exists ( rplotspdf ) : os . remove ( rplotspdf )
Create a temporary file and run it
12,004
def transitive_reduction ( G ) : H = G . copy ( ) for a , b , w in G . edges_iter ( data = True ) : H . remove_edge ( a , b ) if not nx . has_path ( H , a , b ) : H . add_edge ( a , b , w ) return H
Returns a transitive reduction of a graph . The original graph is not modified .
12,005
def merge_paths ( paths , weights = None ) : G = make_paths ( paths , weights = weights ) G = reduce_paths ( G ) return G
Zip together sorted lists .
12,006
def get_next ( self , tag = "<" ) : next , ntag = None , None L = self . outs if tag == "<" else self . ins if len ( L ) == 1 : e , = L if e . v1 . v == self . v : next , ntag = e . v2 , e . o2 ntag = "<" if ntag == ">" else ">" else : next , ntag = e . v1 , e . o1 if next : B = next . ins if ntag == "<" else next . outs if len ( B ) > 1 : return None , None return next , ntag
This function is tricky and took me a while to figure out .
12,007
def dust2bed ( args ) : from jcvi . formats . base import read_block p = OptionParser ( dust2bed . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) fastafile , = args interval = fastafile + ".iv" if need_update ( fastafile , interval ) : cmd = "dustmasker -in {0}" . format ( fastafile ) sh ( cmd , outfile = interval ) fp = open ( interval ) bedfile = fastafile . rsplit ( "." , 1 ) [ 0 ] + ".dust.bed" fw = must_open ( bedfile , "w" ) nlines = 0 nbases = 0 for header , block in read_block ( fp , ">" ) : header = header . strip ( ">" ) for b in block : start , end = b . split ( " - " ) start , end = int ( start ) , int ( end ) print ( "\t" . join ( str ( x ) for x in ( header , start , end ) ) , file = fw ) nlines += 1 nbases += end - start logging . debug ( "A total of {0} DUST intervals ({1} bp) exported to `{2}`" . format ( nlines , nbases , bedfile ) )
%prog dust2bed fastafile
12,008
def fasta2bed ( fastafile ) : dustfasta = fastafile . rsplit ( "." , 1 ) [ 0 ] + ".dust.fasta" for name , seq in parse_fasta ( dustfasta ) : for islower , ss in groupby ( enumerate ( seq ) , key = lambda x : x [ - 1 ] . islower ( ) ) : if not islower : continue ss = list ( ss ) ms , mn = min ( ss ) xs , xn = max ( ss ) print ( "\t" . join ( str ( x ) for x in ( name , ms , xs ) ) )
Alternative BED generation from FASTA file . Used for sanity check .
12,009
def circular ( args ) : from jcvi . assembly . goldenpath import overlap p = OptionParser ( circular . __doc__ ) p . add_option ( "--flip" , default = False , action = "store_true" , help = "Reverse complement the sequence" ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) fastafile , startpos = args startpos = int ( startpos ) key , seq = next ( parse_fasta ( fastafile ) ) aseq = seq [ startpos : ] bseq = seq [ : startpos ] aseqfile , bseqfile = "a.seq" , "b.seq" for f , s in zip ( ( aseqfile , bseqfile ) , ( aseq , bseq ) ) : fw = must_open ( f , "w" ) print ( ">{0}\n{1}" . format ( f , s ) , file = fw ) fw . close ( ) o = overlap ( [ aseqfile , bseqfile ] ) seq = aseq [ : o . qstop ] + bseq [ o . sstop : ] seq = Seq ( seq ) if opts . flip : seq = seq . reverse_complement ( ) for f in ( aseqfile , bseqfile ) : os . remove ( f ) fw = must_open ( opts . outfile , "w" ) rec = SeqRecord ( seq , id = key , description = "" ) SeqIO . write ( [ rec ] , fw , "fasta" ) fw . close ( )
%prog circular fastafile startpos
12,010
def dust ( args ) : p = OptionParser ( dust . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) fastafile , = args dustfastafile = fastafile . rsplit ( "." , 1 ) [ 0 ] + ".dust.fasta" if need_update ( fastafile , dustfastafile ) : cmd = "dustmasker -in {0}" . format ( fastafile ) cmd += " -out {0} -outfmt fasta" . format ( dustfastafile ) sh ( cmd ) for name , seq in parse_fasta ( dustfastafile ) : nlow = sum ( 1 for x in seq if x in "acgtnN" ) pctlow = nlow * 100. / len ( seq ) if pctlow < 98 : continue print ( name )
%prog dust assembly . fasta
12,011
def dedup ( args ) : from jcvi . formats . blast import BlastLine p = OptionParser ( dedup . __doc__ ) p . set_align ( pctid = 0 , pctcov = 98 ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) blastfile , fastafile = args cov = opts . pctcov / 100. sizes = Sizes ( fastafile ) . mapping fp = open ( blastfile ) removed = set ( ) for row in fp : b = BlastLine ( row ) query , subject = b . query , b . subject if query == subject : continue qsize , ssize = sizes [ query ] , sizes [ subject ] qspan = abs ( b . qstop - b . qstart ) if qspan < qsize * cov : continue if ( qsize , query ) < ( ssize , subject ) : removed . add ( query ) print ( "\n" . join ( sorted ( removed ) ) )
%prog dedup assembly . assembly . blast assembly . fasta
12,012
def build ( args ) : from jcvi . apps . cdhit import deduplicate from jcvi . apps . vecscreen import mask from jcvi . formats . fasta import sort p = OptionParser ( build . __doc__ ) p . add_option ( "--nodedup" , default = False , action = "store_true" , help = "Do not deduplicate [default: deduplicate]" ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) fastafile , bacteria , pf = args dd = deduplicate ( [ fastafile , "--pctid=100" ] ) if not opts . nodedup else fastafile screenfasta = screen ( [ dd , bacteria ] ) tidyfasta = mask ( [ screenfasta ] ) sortedfasta = sort ( [ tidyfasta , "--sizes" ] ) scaffoldfasta = pf + ".assembly.fasta" format ( [ sortedfasta , scaffoldfasta , "--prefix=scaffold_" , "--sequential" ] ) gapsplitfasta = pf + ".gapSplit.fasta" cmd = "gapSplit -minGap=10 {0} {1}" . format ( scaffoldfasta , gapsplitfasta ) sh ( cmd ) contigsfasta = pf + ".contigs.fasta" format ( [ gapsplitfasta , contigsfasta , "--prefix=contig_" , "--sequential" ] )
%prog build current . fasta Bacteria_Virus . fasta prefix
12,013
def screen ( args ) : from jcvi . apps . align import blast from jcvi . formats . blast import covfilter p = OptionParser ( screen . __doc__ ) p . set_align ( pctid = 95 , pctcov = 50 ) p . add_option ( "--best" , default = 1 , type = "int" , help = "Get the best N hit [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) scaffolds , library = args pctidflag = "--pctid={0}" . format ( opts . pctid ) blastfile = blast ( [ library , scaffolds , pctidflag , "--best={0}" . format ( opts . best ) ] ) idsfile = blastfile . rsplit ( "." , 1 ) [ 0 ] + ".ids" covfilter ( [ blastfile , scaffolds , "--ids=" + idsfile , pctidflag , "--pctcov={0}" . format ( opts . pctcov ) ] ) pf = scaffolds . rsplit ( "." , 1 ) [ 0 ] nf = pf + ".screen.fasta" cmd = "faSomeRecords {0} -exclude {1} {2}" . format ( scaffolds , idsfile , nf ) sh ( cmd ) logging . debug ( "Screened FASTA written to `{0}`." . format ( nf ) ) return nf
%prog screen scaffolds . fasta library . fasta
12,014
def scaffold ( args ) : from jcvi . formats . agp import bed , order_to_agp , build from jcvi . formats . bed import Bed p = OptionParser ( scaffold . __doc__ ) p . add_option ( "--prefix" , default = False , action = "store_true" , help = "Keep IDs with same prefix together [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) ctgfasta , agpfile = args sizes = Sizes ( ctgfasta ) . mapping pf = ctgfasta . rsplit ( "." , 1 ) [ 0 ] phasefile = pf + ".phases" fwphase = open ( phasefile , "w" ) newagpfile = pf + ".new.agp" fwagp = open ( newagpfile , "w" ) scaffoldbuckets = defaultdict ( list ) bedfile = bed ( [ agpfile , "--nogaps" , "--outfile=tmp" ] ) bb = Bed ( bedfile ) for s , partialorder in bb . sub_beds ( ) : name = partialorder [ 0 ] . accn bname = name . rsplit ( "_" , 1 ) [ 0 ] if opts . prefix else s scaffoldbuckets [ bname ] . append ( [ ( b . accn , b . strand ) for b in partialorder ] ) for bname , scaffolds in sorted ( scaffoldbuckets . items ( ) ) : ctgorder = [ ] singletons = set ( ) for scaf in sorted ( scaffolds ) : for node , orientation in scaf : ctgorder . append ( ( node , orientation ) ) if len ( scaf ) == 1 : singletons . add ( node ) nscaffolds = len ( scaffolds ) nsingletons = len ( singletons ) if nsingletons == 1 and nscaffolds == 0 : phase = 3 elif nsingletons == 0 and nscaffolds == 1 : phase = 2 else : phase = 1 msg = "{0}: Scaffolds={1} Singletons={2} Phase={3}" . format ( bname , nscaffolds , nsingletons , phase ) print ( msg , file = sys . stderr ) print ( "\t" . join ( ( bname , str ( phase ) ) ) , file = fwphase ) order_to_agp ( bname , ctgorder , sizes , fwagp ) fwagp . close ( ) os . remove ( bedfile ) fastafile = "final.fasta" build ( [ newagpfile , ctgfasta , fastafile ] ) tidy ( [ fastafile ] )
%prog scaffold ctgfasta agpfile
12,015
def overlapbatch ( args ) : p = OptionParser ( overlap . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) ctgfasta , poolfasta = args f = Fasta ( ctgfasta ) for k , rec in f . iteritems_ordered ( ) : fastafile = k + ".fasta" fw = open ( fastafile , "w" ) SeqIO . write ( [ rec ] , fw , "fasta" ) fw . close ( ) overlap ( [ fastafile , poolfasta ] )
%prog overlapbatch ctgfasta poolfasta
12,016
def array ( args ) : p = OptionParser ( array . __doc__ ) p . set_grid_opts ( array = True ) p . set_params ( prog = "grid" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) cmds , = args fp = open ( cmds ) N = sum ( 1 for x in fp ) fp . close ( ) pf = cmds . rsplit ( "." , 1 ) [ 0 ] runfile = pf + ".sh" assert runfile != cmds , "Commands list file should not have a `.sh` extension" engine = get_grid_engine ( ) threaded = opts . threaded or 1 contents = arraysh . format ( cmds ) if engine == "SGE" else arraysh_ua . format ( N , threaded , cmds ) write_file ( runfile , contents ) if engine == "PBS" : return outfile = "{0}.{1}.out" . format ( pf , "\$TASK_ID" ) errfile = "{0}.{1}.err" . format ( pf , "\$TASK_ID" ) p = GridProcess ( "sh {0}" . format ( runfile ) , outfile = outfile , errfile = errfile , arr = N , extra_opts = opts . extra , grid_opts = opts ) p . start ( )
%prog array commands . list
12,017
def covlen ( args ) : import numpy as np import pandas as pd import seaborn as sns from jcvi . formats . base import DictFile p = OptionParser ( covlen . __doc__ ) p . add_option ( "--maxsize" , default = 1000000 , type = "int" , help = "Max contig size" ) p . add_option ( "--maxcov" , default = 100 , type = "int" , help = "Max contig size" ) p . add_option ( "--color" , default = 'm' , help = "Color of the data points" ) p . add_option ( "--kind" , default = "scatter" , choices = ( "scatter" , "reg" , "resid" , "kde" , "hex" ) , help = "Kind of plot to draw" ) opts , args , iopts = p . set_image_options ( args , figsize = "8x8" ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) covfile , fastafile = args cov = DictFile ( covfile , cast = float ) s = Sizes ( fastafile ) data = [ ] maxsize , maxcov = opts . maxsize , opts . maxcov for ctg , size in s . iter_sizes ( ) : c = cov . get ( ctg , 0 ) if size > maxsize : continue if c > maxcov : continue data . append ( ( size , c ) ) x , y = zip ( * data ) x = np . array ( x ) y = np . array ( y ) logging . debug ( "X size {0}, Y size {1}" . format ( x . size , y . size ) ) df = pd . DataFrame ( ) xlab , ylab = "Length" , "Coverage of depth (X)" df [ xlab ] = x df [ ylab ] = y sns . jointplot ( xlab , ylab , kind = opts . kind , data = df , xlim = ( 0 , maxsize ) , ylim = ( 0 , maxcov ) , stat_func = None , edgecolor = "w" , color = opts . color ) figname = covfile + ".pdf" savefig ( figname , dpi = iopts . dpi , iopts = iopts )
%prog covlen covfile fastafile
12,018
def scaffold ( args ) : from jcvi . utils . iter import grouper p = OptionParser ( scaffold . __doc__ ) p . add_option ( "--cutoff" , type = "int" , default = 1000000 , help = "Plot scaffolds with size larger than [default: %default]" ) p . add_option ( "--highlights" , help = "A set of regions in BED format to highlight [default: %default]" ) opts , args , iopts = p . set_image_options ( args , figsize = "14x8" , dpi = 150 ) if len ( args ) < 4 or len ( args ) % 3 != 1 : sys . exit ( not p . print_help ( ) ) highlights = opts . highlights scafsizes = Sizes ( args [ 0 ] ) trios = list ( grouper ( args [ 1 : ] , 3 ) ) trios = [ ( a , Sizes ( b ) , Bed ( c ) ) for a , b , c in trios ] if highlights : hlbed = Bed ( highlights ) for scaffoldID , scafsize in scafsizes . iter_sizes ( ) : if scafsize < opts . cutoff : continue logging . debug ( "Loading {0} (size={1})" . format ( scaffoldID , thousands ( scafsize ) ) ) tmpname = scaffoldID + ".sizes" tmp = open ( tmpname , "w" ) tmp . write ( "{0}\t{1}" . format ( scaffoldID , scafsize ) ) tmp . close ( ) tmpsizes = Sizes ( tmpname ) tmpsizes . close ( clean = True ) if highlights : subhighlights = list ( hlbed . sub_bed ( scaffoldID ) ) imagename = "." . join ( ( scaffoldID , opts . format ) ) plot_one_scaffold ( scaffoldID , tmpsizes , None , trios , imagename , iopts , highlights = subhighlights )
%prog scaffold scaffold . fasta synteny . blast synteny . sizes synteny . bed physicalmap . blast physicalmap . sizes physicalmap . bed
12,019
def A50 ( args ) : p = OptionParser ( A50 . __doc__ ) p . add_option ( "--overwrite" , default = False , action = "store_true" , help = "overwrite .rplot file if exists [default: %default]" ) p . add_option ( "--cutoff" , default = 0 , type = "int" , dest = "cutoff" , help = "use contigs above certain size [default: %default]" ) p . add_option ( "--stepsize" , default = 10 , type = "int" , dest = "stepsize" , help = "stepsize for the distribution [default: %default]" ) opts , args = p . parse_args ( args ) if not args : sys . exit ( p . print_help ( ) ) import numpy as np from jcvi . utils . table import loadtable stepsize = opts . stepsize rplot = "A50.rplot" if not op . exists ( rplot ) or opts . overwrite : fw = open ( rplot , "w" ) header = "\t" . join ( ( "index" , "cumsize" , "fasta" ) ) statsheader = ( "Fasta" , "L50" , "N50" , "Min" , "Max" , "Average" , "Sum" , "Counts" ) statsrows = [ ] print ( header , file = fw ) for fastafile in args : f = Fasta ( fastafile , index = False ) ctgsizes = [ length for k , length in f . itersizes ( ) ] ctgsizes = np . array ( ctgsizes ) a50 , l50 , n50 = calculate_A50 ( ctgsizes , cutoff = opts . cutoff ) cmin , cmax , cmean = min ( ctgsizes ) , max ( ctgsizes ) , np . mean ( ctgsizes ) csum , counts = np . sum ( ctgsizes ) , len ( ctgsizes ) cmean = int ( round ( cmean ) ) statsrows . append ( ( fastafile , l50 , n50 , cmin , cmax , cmean , csum , counts ) ) logging . debug ( "`{0}` ctgsizes: {1}" . format ( fastafile , ctgsizes ) ) tag = "{0} (L50={1})" . format ( op . basename ( fastafile ) . rsplit ( "." , 1 ) [ 0 ] , l50 ) logging . debug ( tag ) for i , s in zip ( xrange ( 0 , len ( a50 ) , stepsize ) , a50 [ : : stepsize ] ) : print ( "\t" . join ( ( str ( i ) , str ( s / 1000000. ) , tag ) ) , file = fw ) fw . close ( ) table = loadtable ( statsheader , statsrows ) print ( table , file = sys . stderr ) generate_plot ( rplot )
%prog A50 contigs_A . fasta contigs_B . fasta ...
12,020
def fromdelta ( args ) : p = OptionParser ( fromdelta . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) deltafile , = args coordsfile = deltafile . rsplit ( "." , 1 ) [ 0 ] + ".coords" cmd = "show-coords -rclH {0}" . format ( deltafile ) sh ( cmd , outfile = coordsfile ) return coordsfile
%prog fromdelta deltafile
12,021
def sort ( args ) : import jcvi . formats . blast return jcvi . formats . blast . sort ( args + [ "--coords" ] )
%prog sort coordsfile
12,022
def coverage ( args ) : p = OptionParser ( coverage . __doc__ ) p . add_option ( "-c" , dest = "cutoff" , default = 0.5 , type = "float" , help = "only report query with coverage greater than [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) coordsfile , = args fp = open ( coordsfile ) coords = [ ] for row in fp : try : c = CoordsLine ( row ) except AssertionError : continue coords . append ( c ) coords . sort ( key = lambda x : x . query ) coverages = [ ] for query , lines in groupby ( coords , key = lambda x : x . query ) : cumulative_cutoff = sum ( x . querycov for x in lines ) coverages . append ( ( query , cumulative_cutoff ) ) coverages . sort ( key = lambda x : ( - x [ 1 ] , x [ 0 ] ) ) for query , cumulative_cutoff in coverages : if cumulative_cutoff < opts . cutoff : break print ( "{0}\t{1:.2f}" . format ( query , cumulative_cutoff ) )
%prog coverage coordsfile
12,023
def annotate ( args ) : p = OptionParser ( annotate . __doc__ . format ( ", " . join ( Overlap_types ) ) ) p . add_option ( "--maxhang" , default = 100 , type = "int" , help = "Max hang to call dovetail overlap [default: %default]" ) p . add_option ( "--all" , default = False , action = "store_true" , help = "Output all lines [default: terminal/containment]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) coordsfile , = args fp = open ( coordsfile ) for row in fp : try : c = CoordsLine ( row ) except AssertionError : continue ov = c . overlap ( opts . maxhang ) if not opts . all and ov == 0 : continue print ( "{0}\t{1}" . format ( row . strip ( ) , Overlap_types [ ov ] ) )
%prog annotate coordsfile
12,024
def summary ( args ) : from jcvi . formats . blast import AlignStats p = OptionParser ( summary . __doc__ ) p . add_option ( "-s" , dest = "single" , default = False , action = "store_true" , help = "provide stats per reference seq" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( p . print_help ( ) ) coordsfile , = args alignstats = get_stats ( coordsfile ) alignstats . print_stats ( )
%prog summary coordsfile
12,025
def bed ( args ) : p = OptionParser ( bed . __doc__ ) p . add_option ( "--query" , default = False , action = "store_true" , help = "print out query intervals rather than ref [default: %default]" ) p . add_option ( "--pctid" , default = False , action = "store_true" , help = "use pctid in score [default: %default]" ) p . add_option ( "--cutoff" , dest = "cutoff" , default = 0 , type = "float" , help = "get all the alignments with quality above threshold " + "[default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( p . print_help ( ) ) coordsfile , = args query = opts . query pctid = opts . pctid quality_cutoff = opts . cutoff coords = Coords ( coordsfile ) for c in coords : if c . quality < quality_cutoff : continue line = c . qbedline ( pctid = pctid ) if query else c . bedline ( pctid = pctid ) print ( line )
%prog bed coordsfile
12,026
def hits ( self ) : self . quality_sort ( ) hits = dict ( ( query , list ( blines ) ) for ( query , blines ) in groupby ( self , lambda x : x . query ) ) self . ref_sort ( ) return hits
returns a dict with query = > blastline
12,027
def best_hits ( self ) : self . quality_sort ( ) best_hits = dict ( ( query , next ( blines ) ) for ( query , blines ) in groupby ( self , lambda x : x . query ) ) self . ref_sort ( ) return best_hits
returns a dict with query = > best mapped position
12,028
def sh ( cmd , grid = False , infile = None , outfile = None , errfile = None , append = False , background = False , threaded = None , log = True , grid_opts = None , silent = False , shell = "/bin/bash" , check = False ) : if not cmd : return 1 if silent : outfile = errfile = "/dev/null" if grid : from jcvi . apps . grid import GridProcess pr = GridProcess ( cmd , infile = infile , outfile = outfile , errfile = errfile , threaded = threaded , grid_opts = grid_opts ) pr . start ( ) return pr . jobid else : if infile : cat = "cat" if infile . endswith ( ".gz" ) : cat = "zcat" cmd = "{0} {1} |" . format ( cat , infile ) + cmd if outfile and outfile != "stdout" : if outfile . endswith ( ".gz" ) : cmd += " | gzip" tag = ">" if append : tag = ">>" cmd += " {0}{1}" . format ( tag , outfile ) if errfile : if errfile == outfile : errfile = "&1" cmd += " 2>{0}" . format ( errfile ) if background : cmd += " &" if log : logging . debug ( cmd ) call_func = check_call if check else call return call_func ( cmd , shell = True , executable = shell )
simple wrapper for system calls
12,029
def Popen ( cmd , stdin = None , stdout = PIPE , debug = False , shell = "/bin/bash" ) : from subprocess import Popen as P if debug : logging . debug ( cmd ) proc = P ( cmd , bufsize = 1 , stdin = stdin , stdout = stdout , shell = True , executable = shell ) return proc
Capture the cmd stdout output to a file handle .
12,030
def is_newer_file ( a , b ) : if not ( op . exists ( a ) and op . exists ( b ) ) : return False am = os . stat ( a ) . st_mtime bm = os . stat ( b ) . st_mtime return am > bm
Check if the file a is newer than file b
12,031
def need_update ( a , b ) : a = listify ( a ) b = listify ( b ) return any ( ( not op . exists ( x ) ) for x in b ) or all ( ( os . stat ( x ) . st_size == 0 for x in b ) ) or any ( is_newer_file ( x , y ) for x in a for y in b )
Check if file a is newer than file b and decide whether or not to update file b . Can generalize to two lists .
12,032
def debug ( level = logging . DEBUG ) : from jcvi . apps . console import magenta , yellow format = yellow ( "%(asctime)s [%(module)s]" ) format += magenta ( " %(message)s" ) logging . basicConfig ( level = level , format = format , datefmt = "%H:%M:%S" )
Turn on the debugging
12,033
def mdownload ( args ) : from jcvi . apps . grid import Jobs p = OptionParser ( mdownload . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) linksfile , = args links = [ ( x . strip ( ) , ) for x in open ( linksfile ) ] j = Jobs ( download , links ) j . run ( )
%prog mdownload links . txt
12,034
def timestamp ( args ) : p = OptionParser ( timestamp . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) path , = args for root , dirs , files in os . walk ( path ) : for f in files : filename = op . join ( root , f ) atime , mtime = get_times ( filename ) print ( filename , atime , mtime )
%prog timestamp path > timestamp . info
12,035
def touch ( args ) : from time import ctime p = OptionParser ( touch . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) info , = args fp = open ( info ) for row in fp : path , atime , mtime = row . split ( ) atime = float ( atime ) mtime = float ( mtime ) current_atime , current_mtime = get_times ( path ) if int ( atime ) == int ( current_atime ) and int ( mtime ) == int ( current_mtime ) : continue times = [ ctime ( x ) for x in ( current_atime , current_mtime , atime , mtime ) ] msg = "{0} : " . format ( path ) msg += "({0}, {1}) => ({2}, {3})" . format ( * times ) print ( msg , file = sys . stderr ) os . utime ( path , ( atime , mtime ) )
%prog touch timestamp . info
12,036
def less ( args ) : from jcvi . formats . base import must_open p = OptionParser ( less . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) filename , pos = args fsize = getfilesize ( filename ) if pos == "all" : pos = [ x / 10. for x in range ( 0 , 10 ) ] else : pos = [ float ( x ) for x in pos . split ( "," ) ] if pos [ 0 ] > 1 : pos = [ x / fsize for x in pos ] if len ( pos ) > 1 : counts = 20 else : counts = None fp = must_open ( filename ) for p in pos : snapshot ( fp , p , fsize , counts = counts )
%prog less filename position | less
12,037
def pushover ( message , token , user , title = "JCVI: Job Monitor" , priority = 0 , timestamp = None ) : assert - 1 <= priority <= 2 , "Priority should be an int() between -1 and 2" if timestamp == None : from time import time timestamp = int ( time ( ) ) retry , expire = ( 300 , 3600 ) if priority == 2 else ( None , None ) conn = HTTPSConnection ( "api.pushover.net:443" ) conn . request ( "POST" , "/1/messages.json" , urlencode ( { "token" : token , "user" : user , "message" : message , "title" : title , "priority" : priority , "timestamp" : timestamp , "retry" : retry , "expire" : expire , } ) , { "Content-type" : "application/x-www-form-urlencoded" } ) conn . getresponse ( )
pushover . net python API
12,038
def pushnotify ( subject , message , api = "pushover" , priority = 0 , timestamp = None ) : import types assert type ( priority ) is int and - 1 <= priority <= 2 , "Priority should be and int() between -1 and 2" cfgfile = op . join ( op . expanduser ( "~" ) , "pushnotify.ini" ) Config = ConfigParser ( ) if op . exists ( cfgfile ) : Config . read ( cfgfile ) else : sys . exit ( "Push notification config file `{0}`" . format ( cfgfile ) + " does not exist!" ) if api == "pushover" : cfg = ConfigSectionMap ( Config , api ) token , key = cfg [ "token" ] , cfg [ "user" ] pushover ( message , token , key , title = subject , priority = priority , timestamp = timestamp ) elif api == "nma" : cfg = ConfigSectionMap ( Config , api ) apikey = cfg [ "apikey" ] nma ( message , apikey , event = subject , priority = priority ) elif api == "pushbullet" : cfg = ConfigSectionMap ( Config , api ) apikey , iden = cfg [ "apikey" ] , cfg [ 'iden' ] pushbullet ( message , apikey , iden , title = subject , type = "note" )
Send push notifications using pre - existing APIs
12,039
def send_email ( fromaddr , toaddr , subject , message ) : from smtplib import SMTP from email . mime . text import MIMEText SERVER = "localhost" _message = MIMEText ( message ) _message [ 'Subject' ] = subject _message [ 'From' ] = fromaddr _message [ 'To' ] = ", " . join ( toaddr ) server = SMTP ( SERVER ) server . sendmail ( fromaddr , toaddr , _message . as_string ( ) ) server . quit ( )
Send an email message
12,040
def get_email_address ( whoami = "user" ) : if whoami == "user" : username = getusername ( ) domain = getdomainname ( ) myemail = "{0}@{1}" . format ( username , domain ) return myemail else : fromaddr = "notifier-donotreply@{0}" . format ( getdomainname ( ) ) return fromaddr
Auto - generate the FROM and TO email address
12,041
def notify ( args ) : from jcvi . utils . iter import flatten valid_notif_methods . extend ( available_push_api . keys ( ) ) fromaddr = get_email_address ( whoami = "notifier" ) p = OptionParser ( notify . __doc__ ) p . add_option ( "--method" , default = "email" , choices = valid_notif_methods , help = "Specify the mode of notification [default: %default]" ) p . add_option ( "--subject" , default = "JCVI: job monitor" , help = "Specify the subject of the notification message" ) p . set_email ( ) g1 = OptionGroup ( p , "Optional `push` parameters" ) g1 . add_option ( "--api" , default = "pushover" , choices = list ( flatten ( available_push_api . values ( ) ) ) , help = "Specify API used to send the push notification" ) g1 . add_option ( "--priority" , default = 0 , type = "int" , help = "Message priority (-1 <= p <= 2) [default: %default]" ) g1 . add_option ( "--timestamp" , default = None , type = "int" , dest = "timestamp" , help = "Message timestamp in unix format [default: %default]" ) p . add_option_group ( g1 ) opts , args = p . parse_args ( args ) if len ( args ) == 0 : logging . error ( "Please provide a brief message to be sent" ) sys . exit ( not p . print_help ( ) ) subject = opts . subject message = " " . join ( args ) . strip ( ) if opts . method == "email" : toaddr = opts . email . split ( "," ) for addr in toaddr : if not is_valid_email ( addr ) : logging . debug ( "Email address `{0}` is not valid!" . format ( addr ) ) sys . exit ( ) send_email ( fromaddr , toaddr , subject , message ) else : pushnotify ( subject , message , api = opts . api , priority = opts . priority , timestamp = opts . timestamp )
%prog notify Message to be sent
12,042
def set_db_opts ( self , dbname = "mta4" , credentials = True ) : from jcvi . utils . db import valid_dbconn , get_profile self . add_option ( "--db" , default = dbname , dest = "dbname" , help = "Specify name of database to query [default: %default]" ) self . add_option ( "--connector" , default = "Sybase" , dest = "dbconn" , choices = valid_dbconn . keys ( ) , help = "Specify database connector [default: %default]" ) hostname , username , password = get_profile ( ) if credentials : self . add_option ( "--hostname" , default = hostname , help = "Specify hostname [default: %default]" ) self . add_option ( "--username" , default = username , help = "Username to connect to database [default: %default]" ) self . add_option ( "--password" , default = password , help = "Password to connect to database [default: %default]" ) self . add_option ( "--port" , type = "int" , help = "Specify port number [default: %default]" )
Add db connection specific attributes
12,043
def set_image_options ( self , args = None , figsize = "6x6" , dpi = 300 , format = "pdf" , font = "Helvetica" , palette = "deep" , style = "darkgrid" , cmap = "jet" ) : from jcvi . graphics . base import ImageOptions , setup_theme allowed_format = ( "emf" , "eps" , "pdf" , "png" , "ps" , "raw" , "rgba" , "svg" , "svgz" ) allowed_fonts = ( "Helvetica" , "Palatino" , "Schoolbook" , "Arial" ) allowed_styles = ( "darkgrid" , "whitegrid" , "dark" , "white" , "ticks" ) allowed_diverge = ( "BrBG" , "PiYG" , "PRGn" , "PuOr" , "RdBu" , "RdGy" , "RdYlBu" , "RdYlGn" , "Spectral" ) group = OptionGroup ( self , "Image options" ) self . add_option_group ( group ) group . add_option ( "--figsize" , default = figsize , help = "Figure size `width`x`height` in inches [default: %default]" ) group . add_option ( "--dpi" , default = dpi , type = "int" , help = "Physical dot density (dots per inch) [default: %default]" ) group . add_option ( "--format" , default = format , choices = allowed_format , help = "Generate image of format [default: %default]" ) group . add_option ( "--font" , default = font , choices = allowed_fonts , help = "Font name" ) group . add_option ( "--style" , default = style , choices = allowed_styles , help = "Axes background" ) group . add_option ( "--diverge" , default = "PiYG" , choices = allowed_diverge , help = "Contrasting color scheme" ) group . add_option ( "--cmap" , default = cmap , help = "Use this color map" ) group . add_option ( "--notex" , default = False , action = "store_true" , help = "Do not use tex" ) if args is None : args = sys . argv [ 1 : ] opts , args = self . parse_args ( args ) assert opts . dpi > 0 assert "x" in opts . figsize setup_theme ( style = opts . style , font = opts . font , usetex = ( not opts . notex ) ) return opts , args , ImageOptions ( opts )
Add image format options for given command line programs .
12,044
def dedup ( args ) : from jcvi . formats . fasta import gaps from jcvi . apps . cdhit import deduplicate , ids p = OptionParser ( dedup . __doc__ ) p . set_align ( pctid = GoodPct ) p . set_mingap ( default = 10 ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) scaffolds , = args mingap = opts . mingap splitfile , oagpfile , cagpfile = gaps ( [ scaffolds , "--split" , "--mingap={0}" . format ( mingap ) ] ) dd = splitfile + ".cdhit" clstrfile = dd + ".clstr" idsfile = dd + ".ids" if need_update ( splitfile , clstrfile ) : deduplicate ( [ splitfile , "--pctid={0}" . format ( opts . pctid ) ] ) if need_update ( clstrfile , idsfile ) : ids ( [ clstrfile ] ) agp = AGP ( cagpfile ) reps = set ( x . split ( ) [ - 1 ] for x in open ( idsfile ) ) pf = scaffolds . rsplit ( "." , 1 ) [ 0 ] dedupagp = pf + ".dedup.agp" fw = open ( dedupagp , "w" ) ndropped = ndroppedbases = 0 for a in agp : if not a . is_gap and a . component_id not in reps : span = a . component_span logging . debug ( "Drop component {0} ({1})" . format ( a . component_id , span ) ) ndropped += 1 ndroppedbases += span continue print ( a , file = fw ) fw . close ( ) logging . debug ( "Dropped components: {0}, Dropped bases: {1}" . format ( ndropped , ndroppedbases ) ) logging . debug ( "Deduplicated file written to `{0}`." . format ( dedupagp ) ) tidyagp = tidy ( [ dedupagp , splitfile ] ) dedupfasta = pf + ".dedup.fasta" build ( [ tidyagp , dd , dedupfasta ] ) return dedupfasta
%prog dedup scaffolds . fasta
12,045
def blast ( args ) : from jcvi . apps . align import run_megablast p = OptionParser ( blast . __doc__ ) p . add_option ( "-n" , type = "int" , default = 2 , help = "Take best N hits [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) allfasta , clonename = args fastadir = "fasta" infile = op . join ( fastadir , clonename + ".fasta" ) if not op . exists ( infile ) : entrez ( [ clonename , "--skipcheck" , "--outdir=" + fastadir ] ) outfile = "{0}.{1}.blast" . format ( clonename , allfasta . split ( "." ) [ 0 ] ) run_megablast ( infile = infile , outfile = outfile , db = allfasta , pctid = GoodPct , hitlen = GoodOverlap ) blasts = [ BlastLine ( x ) for x in open ( outfile ) ] besthits = [ ] for b in blasts : if b . query . count ( "|" ) >= 3 : b . query = b . query . split ( "|" ) [ 3 ] if b . subject . count ( "|" ) >= 3 : b . subject = b . subject . split ( "|" ) [ 3 ] b . query = b . query . rsplit ( "." , 1 ) [ 0 ] b . subject = b . subject . rsplit ( "." , 1 ) [ 0 ] if b . query == b . subject : continue if b . subject not in besthits : besthits . append ( b . subject ) if len ( besthits ) == opts . n : break for b in besthits : overlap ( [ clonename , b , "--dir=" + fastadir ] )
%prog blast allfasta clonename
12,046
def bes ( args ) : from jcvi . apps . align import run_blat p = OptionParser ( bes . __doc__ ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) bacfasta , clonename = args entrez ( [ clonename , "--database=nucgss" , "--skipcheck" ] ) besfasta = clonename + ".fasta" blatfile = clonename + ".bes.blat" run_blat ( infile = besfasta , outfile = blatfile , db = bacfasta , pctid = 95 , hitlen = 100 , cpus = opts . cpus ) aid , asize = next ( Fasta ( bacfasta ) . itersizes ( ) ) width = 50 msg = "=" * width msg += " " + aid print ( msg , file = sys . stderr ) ratio = width * 1. / asize _ = lambda x : int ( round ( x * ratio , 0 ) ) blasts = [ BlastLine ( x ) for x in open ( blatfile ) ] for b in blasts : if b . orientation == '+' : msg = " " * _ ( b . sstart ) + "->" else : msg = " " * ( _ ( b . sstop ) - 2 ) + "<-" msg += " " * ( width - len ( msg ) + 2 ) msg += b . query if b . orientation == '+' : msg += " (hang={0})" . format ( b . sstart - 1 ) else : msg += " (hang={0})" . format ( asize - b . sstop ) print ( msg , file = sys . stderr )
%prog bes bacfasta clonename
12,047
def flip ( args ) : p = OptionParser ( flip . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) fastafile , = args outfastafile = fastafile . rsplit ( "." , 1 ) [ 0 ] + ".flipped.fasta" fo = open ( outfastafile , "w" ) f = Fasta ( fastafile , lazy = True ) for name , rec in f . iteritems_ordered ( ) : tmpfasta = "a.fasta" fw = open ( tmpfasta , "w" ) SeqIO . write ( [ rec ] , fw , "fasta" ) fw . close ( ) o = overlap ( [ tmpfasta , name ] ) if o . orientation == '-' : rec . seq = rec . seq . reverse_complement ( ) SeqIO . write ( [ rec ] , fo , "fasta" ) os . remove ( tmpfasta )
%prog flip fastafile
12,048
def batchoverlap ( args ) : p = OptionParser ( batchoverlap . __doc__ ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) pairsfile , outdir = args fp = open ( pairsfile ) cmds = [ ] mkdir ( "overlaps" ) for row in fp : a , b = row . split ( ) [ : 2 ] oa = op . join ( outdir , a + ".fa" ) ob = op . join ( outdir , b + ".fa" ) cmd = "python -m jcvi.assembly.goldenpath overlap {0} {1}" . format ( oa , ob ) cmd += " -o overlaps/{0}_{1}.ov" . format ( a , b ) cmds . append ( cmd ) print ( "\n" . join ( cmds ) )
%prog batchoverlap pairs . txt outdir
12,049
def certificate ( args ) : p = OptionParser ( certificate . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) tpffile , certificatefile = args fastadir = "fasta" tpf = TPF ( tpffile ) data = check_certificate ( certificatefile ) fw = must_open ( certificatefile , "w" ) for i , a in enumerate ( tpf ) : if a . is_gap : continue aid = a . component_id af = op . join ( fastadir , aid + ".fasta" ) if not op . exists ( af ) : entrez ( [ aid , "--skipcheck" , "--outdir=" + fastadir ] ) north , south = tpf . getNorthSouthClone ( i ) aphase , asize = phase ( aid ) for tag , p in ( ( "North" , north ) , ( "South" , south ) ) : if not p : ov = "telomere\t{0}" . format ( asize ) elif p . isCloneGap : bphase = "0" ov = "{0}\t{1}" . format ( p . gap_type , asize ) else : bid = p . component_id bphase , bsize = phase ( bid ) key = ( tag , aid , bid ) if key in data : print ( data [ key ] , file = fw ) continue ar = [ aid , bid , "--dir=" + fastadir ] o = overlap ( ar ) ov = o . certificateline if o else "{0}\t{1}\tNone" . format ( bid , asize ) print ( "\t" . join ( str ( x ) for x in ( tag , a . object , aphase , bphase , aid , ov ) ) , file = fw ) fw . flush ( )
%prog certificate tpffile certificatefile
12,050
def neighbor ( args ) : p = OptionParser ( neighbor . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) agpfile , componentID = args fastadir = "fasta" cmd = "grep" cmd += " --color -C2 {0} {1}" . format ( componentID , agpfile ) sh ( cmd ) agp = AGP ( agpfile ) aorder = agp . order if not componentID in aorder : print ( "Record {0} not present in `{1}`." . format ( componentID , agpfile ) , file = sys . stderr ) return i , c = aorder [ componentID ] north , south = agp . getNorthSouthClone ( i ) if not north . isCloneGap : ar = [ north . component_id , componentID , "--dir=" + fastadir ] if north . orientation == '-' : ar += [ "--qreverse" ] overlap ( ar ) if not south . isCloneGap : ar = [ componentID , south . component_id , "--dir=" + fastadir ] if c . orientation == '-' : ar += [ "--qreverse" ] overlap ( ar )
%prog neighbor agpfile componentID
12,051
def agp ( args ) : from jcvi . formats . base import DictFile p = OptionParser ( agp . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) tpffile , certificatefile , agpfile = args orientationguide = DictFile ( tpffile , valuepos = 2 ) cert = Certificate ( certificatefile ) cert . write_AGP ( agpfile , orientationguide = orientationguide )
%prog agp tpffile certificatefile agpfile
12,052
def update_clr ( self , aclr , bclr ) : print ( aclr , bclr , file = sys . stderr ) otype = self . otype if otype == 1 : if aclr . orientation == '+' : aclr . end = self . qstop else : aclr . start = self . qstart if bclr . orientation == '+' : bclr . start = self . sstop + 1 else : bclr . end = self . sstart - 1 elif otype == 3 : aclr . start = aclr . end elif otype == 4 : bclr . start = bclr . end print ( aclr , bclr , file = sys . stderr )
Zip the two sequences together using left - greedy rule
12,053
def gcdepth ( args ) : import hashlib from jcvi . algorithms . formula import MAD_interval as confidence_interval from jcvi . graphics . base import latex , plt , savefig , set2 p = OptionParser ( gcdepth . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) sample_name , tag = args coloridx = int ( hashlib . sha1 ( tag ) . hexdigest ( ) , 16 ) % len ( set2 ) color = set2 [ coloridx ] gcbedgz = sample_name + ".regions.gc.bed.gz" df = pd . read_csv ( gcbedgz , delimiter = "\t" ) mf = df . loc [ : , ( "4_usercol" , "6_pct_gc" ) ] mf . columns = [ "depth" , "gc" ] mf = mf [ ( mf [ "depth" ] > .001 ) | ( mf [ "gc" ] > .001 ) ] gcbins = defaultdict ( list ) for i , row in mf . iterrows ( ) : gcp = int ( round ( row [ "gc" ] * 100 ) ) gcbins [ gcp ] . append ( row [ "depth" ] ) gcd = sorted ( ( k * .01 , confidence_interval ( v ) ) for ( k , v ) in gcbins . items ( ) ) gcd_x , gcd_y = zip ( * gcd ) m , lo , hi = zip ( * gcd_y ) plt . plot ( mf [ "gc" ] , mf [ "depth" ] , "." , color = "lightslategray" , ms = 2 , mec = "lightslategray" , alpha = .1 ) patch = plt . fill_between ( gcd_x , lo , hi , facecolor = color , alpha = .25 , zorder = 10 , linewidth = 0.0 , label = "Median +/- MAD band" ) plt . plot ( gcd_x , m , "-" , color = color , lw = 2 , zorder = 20 ) ax = plt . gca ( ) ax . legend ( handles = [ patch ] , loc = "best" ) ax . set_xlim ( 0 , 1 ) ax . set_ylim ( 0 , 100 ) ax . set_title ( "{} ({})" . format ( latex ( sample_name ) , tag ) ) ax . set_xlabel ( "GC content" ) ax . set_ylabel ( "Depth" ) savefig ( sample_name + ".gcdepth.png" )
%prog gcdepth sample_name tag
12,054
def exonunion ( args ) : p = OptionParser ( exonunion . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) gencodebed , = args beds = BedTool ( gencodebed ) for g , gb in groupby ( beds , key = lambda x : x . fields [ 3 ] ) : gb = BedTool ( gb ) sys . stdout . write ( str ( gb . sort ( ) . merge ( c = "4,5,6,7" , o = ',' . join ( [ 'first' ] * 4 ) ) ) )
%prog exonunion gencode . v26 . annotation . exon . bed
12,055
def summarycanvas ( args ) : p = OptionParser ( summarycanvas . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) < 1 : sys . exit ( not p . print_help ( ) ) for vcffile in args : counter = get_gain_loss_summary ( vcffile ) pf = op . basename ( vcffile ) . split ( "." ) [ 0 ] print ( pf + " " + " " . join ( "{}:{}" . format ( k , v ) for k , v in sorted ( counter . items ( ) ) ) )
%prog summarycanvas output . vcf . gz
12,056
def parse_segments ( vcffile ) : from cStringIO import StringIO from cyvcf2 import VCF output = StringIO ( ) for v in VCF ( vcffile ) : chrom = v . CHROM start = v . start end = v . INFO . get ( 'END' ) - 1 cn , = v . format ( 'CN' ) [ 0 ] print ( "\t" . join ( str ( x ) for x in ( chrom , start , end , cn ) ) , file = output ) beds = BedTool ( output . getvalue ( ) , from_string = True ) return beds
Extract all copy number segments from a CANVAS file
12,057
def counter_mean_and_median ( counter ) : if not counter : return np . nan , np . nan total = sum ( v for k , v in counter . items ( ) ) mid = total / 2 weighted_sum = 0 items_seen = 0 median_found = False for k , v in sorted ( counter . items ( ) ) : weighted_sum += k * v items_seen += v if not median_found and items_seen >= mid : median = k median_found = True mean = weighted_sum * 1. / total return mean , median
Calculate the mean and median value of a counter
12,058
def vcf_to_df_worker ( arg ) : canvasvcf , exonbed , i = arg logging . debug ( "Working on job {}: {}" . format ( i , canvasvcf ) ) samplekey = op . basename ( canvasvcf ) . split ( "." ) [ 0 ] . rsplit ( '_' , 1 ) [ 0 ] d = { 'SampleKey' : samplekey } exons = BedTool ( exonbed ) cn = parse_segments ( canvasvcf ) overlaps = exons . intersect ( cn , wao = True ) gcn_store = { } for ov in overlaps : gene_name = "|" . join ( ( ov . fields [ 6 ] , ov . fields [ 3 ] , ov . fields [ 5 ] ) ) if gene_name not in gcn_store : gcn_store [ gene_name ] = defaultdict ( int ) cn = ov . fields [ - 2 ] if cn == "." : continue cn = int ( cn ) if cn > 10 : cn = 10 amt = int ( ov . fields [ - 1 ] ) gcn_store [ gene_name ] [ cn ] += amt for k , v in sorted ( gcn_store . items ( ) ) : v_mean , v_median = counter_mean_and_median ( v ) d [ k + ".avgcn" ] = v_mean d [ k + ".medcn" ] = v_median cleanup ( ) return d
Convert CANVAS vcf to a dict single thread
12,059
def vcf_to_df ( canvasvcfs , exonbed , cpus ) : df = pd . DataFrame ( ) p = Pool ( processes = cpus ) results = [ ] args = [ ( x , exonbed , i ) for ( i , x ) in enumerate ( canvasvcfs ) ] r = p . map_async ( vcf_to_df_worker , args , callback = results . append ) r . wait ( ) for res in results : df = df . append ( res , ignore_index = True ) return df
Compile a number of vcf files into tsv file for easy manipulation
12,060
def df_to_tsv ( df , tsvfile , suffix ) : tsvfile += suffix columns = [ "SampleKey" ] + sorted ( x for x in df . columns if x . endswith ( suffix ) ) tf = df . reindex_axis ( columns , axis = 'columns' ) tf . sort_values ( "SampleKey" ) tf . to_csv ( tsvfile , sep = '\t' , index = False , float_format = '%.4g' , na_rep = "na" ) print ( "TSV output written to `{}` (# samples={})" . format ( tsvfile , tf . shape [ 0 ] ) , file = sys . stderr )
Serialize the dataframe as a tsv
12,061
def plot ( args ) : from jcvi . graphics . base import savefig p = OptionParser ( plot . __doc__ ) opts , args , iopts = p . set_image_options ( args , figsize = "8x7" , format = "png" ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) workdir , sample_key , chrs = args chrs = chrs . split ( "," ) hmm = CopyNumberHMM ( workdir = workdir ) hmm . plot ( sample_key , chrs = chrs ) image_name = sample_key + "_cn." + iopts . format savefig ( image_name , dpi = iopts . dpi , iopts = iopts )
%prog plot workdir sample chr1 chr2
12,062
def sweep ( args ) : p = OptionParser ( sweep . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) workdir , sample_key = args golden_ratio = ( 1 + 5 ** .5 ) / 2 cmd = "python -m jcvi.variation.cnv hmm {} {}" . format ( workdir , sample_key ) cmd += " --mu {:.5f} --sigma {:.3f} --threshold {:.3f}" mus = [ .00012 * golden_ratio ** x for x in range ( 10 ) ] sigmas = [ .0012 * golden_ratio ** x for x in range ( 20 ) ] thresholds = [ .1 * golden_ratio ** x for x in range ( 10 ) ] print ( mus , file = sys . stderr ) print ( sigmas , file = sys . stderr ) print ( thresholds , file = sys . stderr ) for mu in mus : for sigma in sigmas : for threshold in thresholds : tcmd = cmd . format ( mu , sigma , threshold ) print ( tcmd )
%prog sweep workdir 102340_NA12878
12,063
def cib ( args ) : p = OptionParser ( cib . __doc__ ) p . add_option ( "--prefix" , help = "Report seqids with this prefix only" ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) bamfile , samplekey = args mkdir ( samplekey ) bam = pysam . AlignmentFile ( bamfile , "rb" ) refs = [ x for x in bam . header [ "SQ" ] ] prefix = opts . prefix if prefix : refs = [ x for x in refs if x [ "SN" ] . startswith ( prefix ) ] task_args = [ ] for r in refs : task_args . append ( ( bamfile , r , samplekey ) ) cpus = min ( opts . cpus , len ( task_args ) ) logging . debug ( "Use {} cpus" . format ( cpus ) ) p = Pool ( processes = cpus ) for res in p . imap ( bam_to_cib , task_args ) : continue
%prog cib bamfile samplekey
12,064
def batchcn ( args ) : p = OptionParser ( batchcn . __doc__ ) p . add_option ( "--upload" , default = "s3://hli-mv-data-science/htang/ccn" , help = "Upload cn and seg results to s3" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) workdir , samples = args upload = opts . upload store = upload + "/{}/*.seg" . format ( workdir ) computed = [ op . basename ( x ) . split ( "." ) [ 0 ] for x in glob_s3 ( store ) ] computed = set ( computed ) fp = open ( samples ) nskipped = ntotal = 0 cmd = "python -m jcvi.variation.cnv cn --hmm --cleanup {}" . format ( workdir ) for row in fp : samplekey , path = row . strip ( ) . split ( "," ) ntotal += 1 if samplekey in computed : nskipped += 1 continue print ( " " . join ( ( cmd , samplekey , path ) ) ) logging . debug ( "Skipped: {}" . format ( percentage ( nskipped , ntotal ) ) )
%prog batchcn workdir samples . csv
12,065
def hmm ( args ) : p = OptionParser ( hmm . __doc__ ) p . add_option ( "--mu" , default = .003 , type = "float" , help = "Transition probability" ) p . add_option ( "--sigma" , default = .1 , type = "float" , help = "Standard deviation of Gaussian emission distribution" ) p . add_option ( "--threshold" , default = 1 , type = "float" , help = "Standard deviation must be < this " "in the baseline population" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) workdir , sample_key = args model = CopyNumberHMM ( workdir = workdir , mu = opts . mu , sigma = opts . sigma , threshold = opts . threshold ) events = model . run ( sample_key ) params = ".mu-{}.sigma-{}.threshold-{}" . format ( opts . mu , opts . sigma , opts . threshold ) hmmfile = op . join ( workdir , sample_key + params + ".seg" ) fw = open ( hmmfile , "w" ) nevents = 0 for mean_cn , rr , event in events : if event is None : continue print ( " " . join ( ( event . bedline , sample_key ) ) , file = fw ) nevents += 1 fw . close ( ) logging . debug ( "A total of {} aberrant events written to `{}`" . format ( nevents , hmmfile ) ) return hmmfile
%prog hmm workdir sample_key
12,066
def batchccn ( args ) : p = OptionParser ( batchccn . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) csvfile , = args mm = MakeManager ( ) pf = op . basename ( csvfile ) . split ( "." ) [ 0 ] mkdir ( pf ) header = next ( open ( csvfile ) ) header = None if header . strip ( ) . endswith ( ".bam" ) else "infer" logging . debug ( "Header={}" . format ( header ) ) df = pd . read_csv ( csvfile , header = header ) cmd = "perl /mnt/software/ccn_gcn_hg38_script/ccn_gcn_hg38.pl" cmd += " -n {} -b {}" cmd += " -o {} -r hg38" . format ( pf ) for i , ( sample_key , bam ) in df . iterrows ( ) : cmdi = cmd . format ( sample_key , bam ) outfile = "{}/{}/{}.ccn" . format ( pf , sample_key , sample_key ) mm . add ( csvfile , outfile , cmdi ) mm . write ( )
%prog batchccn test . csv
12,067
def mergecn ( args ) : p = OptionParser ( mergecn . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) csvfile , = args samples = [ x . replace ( "-cn" , "" ) . strip ( ) . strip ( "/" ) for x in open ( csvfile ) ] betadir = "beta" mkdir ( betadir ) for seqid in allsomes : names = [ op . join ( s + "-cn" , "{}.{}.cn" . format ( op . basename ( s ) , seqid ) ) for s in samples ] arrays = [ np . fromfile ( name , dtype = np . float ) for name in names ] shapes = [ x . shape [ 0 ] for x in arrays ] med_shape = np . median ( shapes ) arrays = [ x for x in arrays if x . shape [ 0 ] == med_shape ] ploidy = 2 if seqid not in ( "chrY" , "chrM" ) else 1 if seqid in sexsomes : chr_med = [ np . median ( [ x for x in a if x > 0 ] ) for a in arrays ] chr_med = np . array ( chr_med ) idx = get_kmeans ( chr_med , k = 2 ) zero_med = np . median ( chr_med [ idx == 0 ] ) one_med = np . median ( chr_med [ idx == 1 ] ) logging . debug ( "K-means with {} c0:{} c1:{}" . format ( seqid , zero_med , one_med ) ) higher_idx = 1 if one_med > zero_med else 0 arrays = np . array ( arrays ) [ idx == higher_idx ] arrays = [ [ x ] for x in arrays ] ar = np . concatenate ( arrays ) print ( seqid , ar . shape ) rows , columns = ar . shape beta = [ ] std = [ ] for j in xrange ( columns ) : a = ar [ : , j ] beta . append ( np . median ( a ) ) std . append ( np . std ( a ) / np . mean ( a ) ) beta = np . array ( beta ) / ploidy betafile = op . join ( betadir , "{}.beta" . format ( seqid ) ) beta . tofile ( betafile ) stdfile = op . join ( betadir , "{}.std" . format ( seqid ) ) std = np . array ( std ) std . tofile ( stdfile ) logging . debug ( "Written to `{}`" . format ( betafile ) ) ar . tofile ( "{}.bin" . format ( seqid ) )
%prog mergecn FACE . csv
12,068
def annotate_segments ( self , Z ) : P = Z . copy ( ) P [ ~ np . isfinite ( P ) ] = - 1 _ , mapping = np . unique ( np . cumsum ( P >= 0 ) , return_index = True ) dZ = Z . compressed ( ) uniq , idx = np . unique ( dZ , return_inverse = True ) segments = [ ] for i , mean_cn in enumerate ( uniq ) : if not np . isfinite ( mean_cn ) : continue for rr in contiguous_regions ( idx == i ) : segments . append ( ( mean_cn , mapping [ rr ] ) ) return segments
Report the copy number and start - end segment
12,069
def role ( args ) : src_acct , src_username , dst_acct , dst_role = "205134639408 htang 114692162163 mvrad-datasci-role" . split ( ) p = OptionParser ( role . __doc__ ) p . add_option ( "--profile" , default = "mvrad-datasci-role" , help = "Profile name" ) p . add_option ( '--device' , default = "arn:aws:iam::" + src_acct + ":mfa/" + src_username , metavar = 'arn:aws:iam::123456788990:mfa/dudeman' , help = "The MFA Device ARN. This value can also be " "provided via the environment variable 'MFA_DEVICE' or" " the ~/.aws/credentials variable 'aws_mfa_device'." ) p . add_option ( '--duration' , type = int , default = 3600 , help = "The duration, in seconds, that the temporary " "credentials should remain valid. Minimum value: " "900 (15 minutes). Maximum: 129600 (36 hours). " "Defaults to 43200 (12 hours), or 3600 (one " "hour) when using '--assume-role'. This value " "can also be provided via the environment " "variable 'MFA_STS_DURATION'. " ) p . add_option ( '--assume-role' , '--assume' , default = "arn:aws:iam::" + dst_acct + ":role/" + dst_role , metavar = 'arn:aws:iam::123456788990:role/RoleName' , help = "The ARN of the AWS IAM Role you would like to " "assume, if specified. This value can also be provided" " via the environment variable 'MFA_ASSUME_ROLE'" ) p . add_option ( '--role-session-name' , help = "Friendly session name required when using " "--assume-role" , default = getpass . getuser ( ) ) p . add_option ( '--force' , help = "Refresh credentials even if currently valid." , action = "store_true" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) config = get_config ( AWS_CREDS_PATH ) validate ( opts , config )
%prog role htang
12,070
def query ( args ) : p = OptionParser ( query . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) locifile , contig = args idx = build_index ( locifile ) pos = idx [ contig ] logging . debug ( "Contig {0} found at pos {1}" . format ( contig , pos ) ) fp = open ( locifile ) fp . seek ( pos ) section = [ ] while True : row = fp . readline ( ) if row . startswith ( "//" ) and row . split ( ) [ 1 ] != contig : break section . append ( row ) print ( "" . join ( section ) )
%prog query out . loci contig
12,071
def synteny ( args ) : from jcvi . assembly . geneticmap import bed as geneticmap_bed from jcvi . apps . align import blat from jcvi . formats . blast import bed as blast_bed , best p = OptionParser ( synteny . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) mstmapout , novo , ref = args pf = mstmapout . split ( "." ) [ 0 ] rf = ref . split ( "." ) [ 0 ] mstmapbed = geneticmap_bed ( [ mstmapout ] ) cmd = "cut -d. -f1 {0}" . format ( mstmapbed ) tmpbed = mstmapbed + ".tmp" sh ( cmd , outfile = tmpbed ) os . rename ( tmpbed , pf + ".bed" ) cmd = "cut -f4 {0} | cut -d. -f1 | sort -u" . format ( mstmapbed ) idsfile = pf + ".ids" sh ( cmd , outfile = idsfile ) fastafile = pf + ".fasta" cmd = "faSomeRecords {0} {1} {2}" . format ( novo , idsfile , fastafile ) sh ( cmd ) blastfile = blat ( [ ref , fastafile ] ) bestblastfile = best ( [ blastfile ] ) blastbed = blast_bed ( [ bestblastfile ] ) os . rename ( blastbed , rf + ".bed" ) anchorsfile = "{0}.{1}.anchors" . format ( pf , rf ) cmd = "paste {0} {0}" . format ( idsfile ) sh ( cmd , outfile = anchorsfile )
%prog synteny mstmap . out novo . final . fasta reference . fasta
12,072
def mstmap ( args ) : from jcvi . assembly . geneticmap import MSTMatrix p = OptionParser ( mstmap . __doc__ ) p . add_option ( "--population_type" , default = "RIL6" , help = "Type of population, possible values are DH and RILd" ) p . add_option ( "--missing_threshold" , default = .5 , help = "Missing threshold, .25 excludes any marker with >25% missing" ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) lmd , = args fp = open ( lmd ) next ( fp ) table = { "0" : "-" , "1" : "A" , "2" : "B" , "3" : "X" } mh = [ "locus_name" ] + fp . next ( ) . split ( ) [ 4 : ] genotypes = [ ] for row in fp : atoms = row . split ( ) chr , pos , ref , alt = atoms [ : 4 ] locus_name = "." . join ( ( chr , pos ) ) codes = [ table [ x ] for x in atoms [ 4 : ] ] genotypes . append ( [ locus_name ] + codes ) mm = MSTMatrix ( genotypes , mh , opts . population_type , opts . missing_threshold ) mm . write ( opts . outfile , header = True )
%prog mstmap LMD50 . snps . genotype . txt
12,073
def count ( args ) : from jcvi . graphics . histogram import stem_leaf_plot from jcvi . utils . cbook import SummaryStats p = OptionParser ( count . __doc__ ) p . add_option ( "--csv" , help = "Write depth per contig to file" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) fastafile , = args csv = open ( opts . csv , "w" ) if opts . csv else None f = Fasta ( fastafile , lazy = True ) sizes = [ ] for desc , rec in f . iterdescriptions_ordered ( ) : if desc . startswith ( "singleton" ) : sizes . append ( 1 ) continue if "with" in desc : name , w , size , seqs = desc . split ( ) if csv : print ( "\t" . join ( str ( x ) for x in ( name , size , len ( rec ) ) ) , file = csv ) assert w == "with" sizes . append ( int ( size ) ) else : name , size , tail = desc . split ( ";" ) sizes . append ( int ( size . replace ( "size=" , "" ) ) ) if csv : csv . close ( ) logging . debug ( "File written to `{0}`" . format ( opts . csv ) ) s = SummaryStats ( sizes ) print ( s , file = sys . stderr ) stem_leaf_plot ( s . data , 0 , 100 , 20 , title = "Cluster size" )
%prog count cdhit . consensus . fasta
12,074
def novo ( args ) : from jcvi . assembly . kmer import jellyfish , histogram from jcvi . assembly . preprocess import diginorm from jcvi . formats . fasta import filter as fasta_filter , format from jcvi . apps . cdhit import filter as cdhit_filter p = OptionParser ( novo . __doc__ ) p . add_option ( "--technology" , choices = ( "illumina" , "454" , "iontorrent" ) , default = "iontorrent" , help = "Sequencing platform" ) p . set_depth ( depth = 50 ) p . set_align ( pctid = 96 ) p . set_home ( "cdhit" , default = "/usr/local/bin/" ) p . set_home ( "fiona" , default = "/usr/local/bin/" ) p . set_home ( "jellyfish" , default = "/usr/local/bin/" ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) fastqfile , = args cpus = opts . cpus depth = opts . depth pf , sf = fastqfile . rsplit ( "." , 1 ) diginormfile = pf + ".diginorm." + sf if need_update ( fastqfile , diginormfile ) : diginorm ( [ fastqfile , "--single" , "--depth={0}" . format ( depth ) ] ) keepabund = fastqfile + ".keep.abundfilt" sh ( "cp -s {0} {1}" . format ( keepabund , diginormfile ) ) jf = pf + "-K23.histogram" if need_update ( diginormfile , jf ) : jellyfish ( [ diginormfile , "--prefix={0}" . format ( pf ) , "--cpus={0}" . format ( cpus ) , "--jellyfish_home={0}" . format ( opts . jellyfish_home ) ] ) genomesize = histogram ( [ jf , pf , "23" ] ) fiona = pf + ".fiona.fa" if need_update ( diginormfile , fiona ) : cmd = op . join ( opts . fiona_home , "fiona" ) cmd += " -g {0} -nt {1} --sequencing-technology {2}" . format ( genomesize , cpus , opts . technology ) cmd += " -vv {0} {1}" . format ( diginormfile , fiona ) logfile = pf + ".fiona.log" sh ( cmd , outfile = logfile , errfile = logfile ) dedup = "cdhit" pctid = opts . pctid cons = fiona + ".P{0}.{1}.consensus.fasta" . format ( pctid , dedup ) if need_update ( fiona , cons ) : deduplicate ( [ fiona , "--consensus" , "--reads" , "--pctid={0}" . format ( pctid ) , "--cdhit_home={0}" . format ( opts . cdhit_home ) ] ) filteredfile = pf + ".filtered.fasta" if need_update ( cons , filteredfile ) : covfile = pf + ".cov.fasta" cdhit_filter ( [ cons , "--outfile={0}" . format ( covfile ) , "--minsize={0}" . format ( depth / 5 ) ] ) fasta_filter ( [ covfile , "50" , "--outfile={0}" . format ( filteredfile ) ] ) finalfile = pf + ".final.fasta" if need_update ( filteredfile , finalfile ) : format ( [ filteredfile , finalfile , "--sequential=replace" , "--prefix={0}_" . format ( pf ) ] )
%prog novo reads . fastq
12,075
def novo2 ( args ) : p = OptionParser ( novo2 . __doc__ ) p . set_fastq_names ( ) p . set_align ( pctid = 95 ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) trimmed , pf = args pctid = opts . pctid reads , samples = scan_read_files ( trimmed , opts . names ) clustdir = "uclust" acdir = "allele_counts" for d in ( clustdir , acdir ) : mkdir ( d ) mm = MakeManager ( ) clustfiles = [ ] for s in samples : flist = [ x for x in reads if op . basename ( x ) . split ( "." ) [ 0 ] == s ] outfile = s + ".P{0}.clustS" . format ( pctid ) outfile = op . join ( clustdir , outfile ) cmd = "python -m jcvi.apps.uclust cluster --cpus=8" cmd += " {0} {1}" . format ( s , " " . join ( flist ) ) cmd += " --outdir={0}" . format ( clustdir ) cmd += " --pctid={0}" . format ( pctid ) mm . add ( flist , outfile , cmd ) clustfiles . append ( outfile ) allcons = [ ] for s , clustfile in zip ( samples , clustfiles ) : outfile = s + ".P{0}.consensus" . format ( pctid ) outfile = op . join ( clustdir , outfile ) cmd = "python -m jcvi.apps.uclust consensus" cmd += " {0}" . format ( clustfile ) mm . add ( clustfile , outfile , cmd ) allcons . append ( outfile ) clustSfile = pf + ".P{0}.clustS" . format ( pctid ) cmd = "python -m jcvi.apps.uclust mcluster {0}" . format ( " " . join ( allcons ) ) cmd += " --prefix={0}" . format ( pf ) mm . add ( allcons , clustSfile , cmd ) locifile = pf + ".P{0}.loci" . format ( pctid ) cmd = "python -m jcvi.apps.uclust mconsensus {0}" . format ( " " . join ( allcons ) ) cmd += " --prefix={0}" . format ( pf ) mm . add ( allcons + [ clustSfile ] , locifile , cmd ) mm . write ( )
%prog novo2 trimmed projectname
12,076
def snpplot ( args ) : p = OptionParser ( snpplot . __doc__ ) opts , args , iopts = p . set_image_options ( args , format = "png" ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) datafile , = args fp = open ( datafile ) next ( fp ) next ( fp ) data = [ ] for row in fp : atoms = row . split ( ) [ 4 : ] nval = len ( atoms ) values = [ float ( x ) for x in atoms ] values = [ x * 1. / sum ( values ) for x in values ] data . append ( values ) pf = datafile . rsplit ( "." , 1 ) [ 0 ] fig = plt . figure ( 1 , ( iopts . w , iopts . h ) ) root = fig . add_axes ( [ 0 , 0 , 1 , 1 ] ) xmin , xmax = .1 , .9 ymin , ymax = .1 , .9 yinterval = ( ymax - ymin ) / len ( data ) colors = "rbg" if nval == 3 else [ "lightgray" ] + list ( "rbg" ) ystart = ymax for d in data : xstart = xmin for dd , c in zip ( d , colors ) : xend = xstart + ( xmax - xmin ) * dd root . plot ( ( xstart , xend ) , ( ystart , ystart ) , "-" , color = c ) xstart = xend ystart -= yinterval root . text ( .05 , .5 , "{0} LMD50 SNPs" . format ( len ( data ) ) , ha = "center" , va = "center" , rotation = 90 , color = "lightslategray" ) for x , t , c in zip ( ( .3 , .5 , .7 ) , ( "REF" , "ALT" , "HET" ) , "rbg" ) : root . text ( x , .95 , t , color = c , ha = "center" , va = "center" ) normalize_axes ( root ) image_name = pf + "." + iopts . format savefig ( image_name , dpi = iopts . dpi , iopts = iopts )
%prog counts . cdt
12,077
def filterm4 ( args ) : p = OptionParser ( filterm4 . __doc__ ) p . add_option ( "--best" , default = 1 , type = "int" , help = "Only retain best N hits" ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) m4file , = args best = opts . best fp = open ( m4file ) fw = must_open ( opts . outfile , "w" ) seen = defaultdict ( int ) retained = total = 0 for row in fp : r = M4Line ( row ) total += 1 if total % 100000 == 0 : logging . debug ( "Retained {0} lines" . format ( percentage ( retained , total ) ) ) if seen . get ( r . query , 0 ) < best : fw . write ( row ) seen [ r . query ] += 1 retained += 1 fw . close ( )
%prog filterm4 sample . m4 > filtered . m4
12,078
def spancount ( args ) : import json p = OptionParser ( spancount . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) fof , = args fp = open ( fof ) flist = [ row . strip ( ) for row in fp ] spanCount = "spanCount" avgSpanBases = "avgSpanBases" fw = open ( spanCount , "w" ) for f in flist : fp = open ( f ) j = json . load ( fp ) sc = j . get ( spanCount , None ) asb = j . get ( avgSpanBases , None ) print ( f , asb , sc , file = fw ) fw . flush ( ) fw . close ( )
%prog spancount list_of_fillingMetrics
12,079
def patch ( args ) : from jcvi . formats . base import write_file from jcvi . formats . fasta import format p = OptionParser ( patch . __doc__ ) p . add_option ( "--cleanfasta" , default = False , action = "store_true" , help = "Clean FASTA to remove description [default: %default]" ) p . add_option ( "--highqual" , default = False , action = "store_true" , help = "Reads are of high quality [default: %default]" ) p . set_home ( "pbjelly" ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) ref , reads = args cpus = opts . cpus cmd = op . join ( opts . pbjelly_home , "setup.sh" ) setup = "source {0}" . format ( cmd ) if not which ( "fakeQuals.py" ) : sh ( setup ) pf = ref . rsplit ( "." , 1 ) [ 0 ] pr , px = reads . rsplit ( "." , 1 ) if opts . cleanfasta : oref = pf + ".f.fasta" oreads = pr + ".f.fasta" format ( [ ref , oref ] ) format ( [ reads , oreads ] ) ref , reads = oref , oreads ref , refq = fake_quals ( ref ) convert_reads = not px in ( "fq" , "fastq" , "txt" ) if convert_reads : reads , readsq = fake_quals ( reads ) readsfiles = " " . join ( ( reads , readsq ) ) else : readsfiles = reads dref , dreads = "data/reference" , "data/reads" cwd = os . getcwd ( ) reference = op . join ( cwd , "{0}/{1}" . format ( dref , ref ) ) reads = op . join ( cwd , "{0}/{1}" . format ( dreads , reads ) ) if not op . exists ( reference ) : sh ( "mkdir -p {0}" . format ( dref ) ) sh ( "cp {0} {1}/" . format ( " " . join ( ( ref , refq ) ) , dref ) ) if not op . exists ( reads ) : sh ( "mkdir -p {0}" . format ( dreads ) ) sh ( "cp {0} {1}/" . format ( readsfiles , dreads ) ) outputDir = cwd p = Protocol ( outputDir , reference , reads , highqual = opts . highqual ) p . write_xml ( ) runsh = [ setup ] for action in "setup|mapping|support|extraction" . split ( "|" ) : runsh . append ( "Jelly.py {0} Protocol.xml" . format ( action ) ) runsh . append ( 'Jelly.py assembly Protocol.xml -x "--nproc={0}"' . format ( cpus ) ) runsh . append ( "Jelly.py output Protocol.xml" ) runfile = "run.sh" contents = "\n" . join ( runsh ) write_file ( runfile , contents )
%prog patch reference . fasta reads . fasta
12,080
def isPlantOrigin ( taxid ) : assert isinstance ( taxid , int ) t = TaxIDTree ( taxid ) try : return "Viridiplantae" in str ( t ) except AttributeError : raise ValueError ( "{0} is not a valid ID" . format ( taxid ) )
Given a taxid this gets the expanded tree which can then be checked to see if the organism is a plant or not
12,081
def newick ( args ) : p = OptionParser ( newick . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) idsfile , = args mylist = [ x . strip ( ) for x in open ( idsfile ) if x . strip ( ) ] print ( get_taxids ( mylist ) ) t = TaxIDTree ( mylist ) print ( t )
%prog newick idslist
12,082
def fastq ( args ) : p = OptionParser ( fastq . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) bamfile , pf = args singletons = pf + ".se.fastq" a = pf + ".read1.fastq" b = pf + ".read2.fastq" cmd = "samtools collate -uOn 128 {} tmp-prefix" . format ( bamfile ) cmd += " | samtools fastq -s {} -1 {} -2 {} -" . format ( singletons , a , b ) sh ( cmd ) if os . stat ( singletons ) . st_size == 0 : os . remove ( singletons ) return a , b
%prog fastq bamfile prefix
12,083
def mini ( args ) : p = OptionParser ( mini . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) bamfile , region = args get_minibam ( bamfile , region )
%prog mini bamfile region
12,084
def noclip ( args ) : p = OptionParser ( noclip . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) bamfile , = args noclipbam = bamfile . replace ( ".bam" , ".noclip.bam" ) cmd = "samtools view -h {} | awk -F '\t' '($6 !~ /H|S/)'" . format ( bamfile ) cmd += " | samtools view -@ 4 -b -o {}" . format ( noclipbam ) sh ( cmd ) sh ( "samtools index {}" . format ( noclipbam ) )
%prog noclip bamfile
12,085
def append ( args ) : p = OptionParser ( append . __doc__ ) p . add_option ( "--prepend" , help = "Prepend string to read names" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) bamfile , = args prepend = opts . prepend icmd = "samtools view -h {0}" . format ( bamfile ) bamfile = bamfile . rsplit ( "." , 1 ) [ 0 ] + ".append.bam" ocmd = "samtools view -b -@ 64 - -o {0}" . format ( bamfile ) p = Popen ( ocmd , stdin = PIPE ) for row in popen ( icmd ) : if row [ 0 ] == '@' : print ( row . strip ( ) , file = p . stdin ) else : s = SamLine ( row ) if prepend : s . qname = prepend + "_" + s . qname else : s . update_readname ( ) print ( s , file = p . stdin )
%prog append bamfile
12,086
def bed ( args ) : p = OptionParser ( bed . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) < 2 : sys . exit ( not p . print_help ( ) ) bedfile = args [ 0 ] bamfiles = args [ 1 : ] for bamfile in bamfiles : cmd = "bamToBed -i {0}" . format ( bamfile ) sh ( cmd , outfile = bedfile , append = True )
%prog bed bedfile bamfiles
12,087
def merge ( args ) : from jcvi . apps . grid import MakeManager p = OptionParser ( merge . __doc__ ) p . set_sep ( sep = "_" , help = "Separator to group per prefix" ) opts , args = p . parse_args ( args ) if len ( args ) < 2 : sys . exit ( not p . print_help ( ) ) merged_bams = args [ 0 ] bamdirs = args [ 1 : ] mkdir ( merged_bams ) bams = [ ] for x in bamdirs : bams += glob ( op . join ( x , "*.bam" ) ) bams = [ x for x in bams if "nsorted" not in x ] logging . debug ( "Found a total of {0} BAM files." . format ( len ( bams ) ) ) sep = opts . sep key = lambda x : op . basename ( x ) . split ( sep ) [ 0 ] bams . sort ( key = key ) mm = MakeManager ( ) for prefix , files in groupby ( bams , key = key ) : files = sorted ( list ( files ) ) nfiles = len ( files ) source = " " . join ( files ) target = op . join ( merged_bams , op . basename ( files [ 0 ] ) ) if nfiles == 1 : source = get_abs_path ( source ) cmd = "ln -s {0} {1}" . format ( source , target ) mm . add ( "" , target , cmd ) else : cmd = "samtools merge -@ 8 {0} {1}" . format ( target , source ) mm . add ( files , target , cmd , remove = True ) mm . write ( )
%prog merge merged_bams bams1_dir bams2_dir ...
12,088
def count ( args ) : p = OptionParser ( count . __doc__ ) p . add_option ( "--type" , default = "exon" , help = "Only count feature type" ) p . set_cpus ( cpus = 8 ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) bamfile , gtf = args cpus = opts . cpus pf = bamfile . split ( "." ) [ 0 ] countfile = pf + ".count" if not need_update ( bamfile , countfile ) : return nsorted = pf + "_nsorted" nsortedbam , nsortedsam = nsorted + ".bam" , nsorted + ".sam" if need_update ( bamfile , nsortedsam ) : cmd = "samtools sort -@ {0} -n {1} {2}" . format ( cpus , bamfile , nsorted ) sh ( cmd ) cmd = "samtools view -@ {0} -h {1}" . format ( cpus , nsortedbam ) sh ( cmd , outfile = nsortedsam ) if need_update ( nsortedsam , countfile ) : cmd = "htseq-count --stranded=no --minaqual=10" cmd += " -t {0}" . format ( opts . type ) cmd += " {0} {1}" . format ( nsortedsam , gtf ) sh ( cmd , outfile = countfile )
%prog count bamfile gtf
12,089
def coverage ( args ) : p = OptionParser ( coverage . __doc__ ) p . add_option ( "--format" , default = "bigwig" , choices = ( "bedgraph" , "bigwig" , "coverage" ) , help = "Output format" ) p . add_option ( "--nosort" , default = False , action = "store_true" , help = "Do not sort BAM" ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) fastafile , bamfile = args format = opts . format if opts . nosort : logging . debug ( "BAM sorting skipped" ) else : bamfile = index ( [ bamfile , "--fasta={0}" . format ( fastafile ) ] ) pf = bamfile . rsplit ( "." , 2 ) [ 0 ] sizesfile = Sizes ( fastafile ) . filename cmd = "genomeCoverageBed -ibam {0} -g {1}" . format ( bamfile , sizesfile ) if format in ( "bedgraph" , "bigwig" ) : cmd += " -bg" bedgraphfile = pf + ".bedgraph" sh ( cmd , outfile = bedgraphfile ) if format == "bedgraph" : return bedgraphfile bigwigfile = pf + ".bigwig" cmd = "bedGraphToBigWig {0} {1} {2}" . format ( bedgraphfile , sizesfile , bigwigfile ) sh ( cmd ) return bigwigfile coveragefile = pf + ".coverage" if need_update ( fastafile , coveragefile ) : sh ( cmd , outfile = coveragefile ) gcf = GenomeCoverageFile ( coveragefile ) fw = must_open ( opts . outfile , "w" ) for seqid , cov in gcf . iter_coverage_seqid ( ) : print ( "\t" . join ( ( seqid , "{0:.1f}" . format ( cov ) ) ) , file = fw ) fw . close ( )
%prog coverage fastafile bamfile
12,090
def consensus ( args ) : p = OptionParser ( consensus . __doc__ ) p . add_option ( "--fasta" , default = False , action = "store_true" , help = "Generate consensus FASTA sequences [default: %default]" ) p . add_option ( "--mask" , default = 0 , type = "int" , help = "Mask bases with quality lower than" ) opts , args = p . parse_args ( args ) if len ( args ) < 2 : sys . exit ( not p . print_help ( ) ) fastafile , bamfile = args fasta = opts . fasta suffix = "fasta" if fasta else "fastq" pf = bamfile . rsplit ( "." , 1 ) [ 0 ] cnsfile = pf + ".cns.{0}" . format ( suffix ) vcfgzfile = pf + ".vcf.gz" vcf ( [ fastafile , bamfile , "-o" , vcfgzfile ] ) cmd += "zcat {0} | vcfutils.pl vcf2fq" . format ( vcfgzfile ) if fasta : cmd += " | seqtk seq -q {0} -A -" . format ( opts . mask ) sh ( cmd , outfile = cnsfile )
%prog consensus fastafile bamfile
12,091
def vcf ( args ) : from jcvi . apps . grid import Jobs valid_callers = ( "mpileup" , "freebayes" ) p = OptionParser ( vcf . __doc__ ) p . set_outfile ( outfile = "out.vcf.gz" ) p . add_option ( "--nosort" , default = False , action = "store_true" , help = "Do not sort the BAM files" ) p . add_option ( "--caller" , default = "mpileup" , choices = valid_callers , help = "Use variant caller [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) < 2 : sys . exit ( not p . print_help ( ) ) fastafile = args [ 0 ] bamfiles = args [ 1 : ] caller = opts . caller unsorted = [ x for x in bamfiles if ".sorted." not in x ] if opts . nosort : bamfiles = unsorted else : jargs = [ [ [ x , "--unique" ] ] for x in unsorted ] jobs = Jobs ( index , args = jargs ) jobs . run ( ) bamfiles = [ x . replace ( ".sorted.bam" , ".bam" ) for x in bamfiles ] bamfiles = [ x . replace ( ".bam" , ".sorted.bam" ) for x in bamfiles ] if caller == "mpileup" : cmd = "samtools mpileup -E -uf" cmd += " {0} {1}" . format ( fastafile , " " . join ( bamfiles ) ) cmd += " | bcftools call -vmO v" elif caller == "freebayes" : cmd = "freebayes -f" cmd += " {0} {1}" . format ( fastafile , " " . join ( bamfiles ) ) sh ( cmd , outfile = opts . outfile )
%prog vcf fastafile bamfiles > out . vcf . gz
12,092
def chimera ( args ) : import pysam from jcvi . utils . natsort import natsorted p = OptionParser ( chimera . __doc__ ) p . set_verbose ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) samfile , = args samfile = pysam . AlignmentFile ( samfile ) rstore = defaultdict ( list ) hstore = defaultdict ( int ) for r in samfile . fetch ( ) : rstore [ r . query_name ] += list ( breakpoint ( r ) ) hstore [ r . query_name ] += 1 if opts . verbose : print ( r . query_name , "+-" [ r . is_reverse ] , sum ( l for o , l in r . cigartuples ) , r . cigarstring , list ( breakpoint ( r ) ) , file = sys . stderr ) for rn , bps in natsorted ( rstore . items ( ) ) : bps = "|" . join ( str ( x ) for x in sorted ( bps ) ) if bps else "na" print ( "\t" . join ( ( rn , str ( hstore [ rn ] ) , bps ) ) )
%prog chimera bamfile
12,093
def pair ( args ) : p = OptionParser ( pair . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( p . print_help ( ) ) def callback ( s ) : print ( s . pairline ) Sam ( args [ 0 ] , callback = callback )
%prog pair samfile
12,094
def cigar_to_seq ( a , gap = '*' ) : seq , cigar = a . seq , a . cigar start = 0 subseqs = [ ] npadded = 0 if cigar is None : return None , npadded for operation , length in cigar : end = start if operation == 2 else start + length if operation == 0 : subseq = seq [ start : end ] elif operation == 1 : subseq = "" elif operation == 2 : subseq = gap * length npadded += length elif operation == 3 : subseq = 'N' * length elif operation in ( 4 , 5 ) : subseq = "" else : raise NotImplementedError subseqs . append ( subseq ) start = end return "" . join ( subseqs ) , npadded
Accepts a pysam row .
12,095
def dump ( args ) : p = OptionParser ( dump . __doc__ ) p . add_option ( "--dir" , help = "Working directory [default: %default]" ) p . add_option ( "--nosim" , default = False , action = "store_true" , help = "Do not simulate qual to 50 [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) fastbfile , = args d = opts . dir if d : from jcvi . assembly . preprocess import export_fastq rc = "jump" in fastbfile export_fastq ( d , fastbfile , rc = rc ) return sim = not opts . nosim pf = "j" if "jump" in fastbfile else "f" statsfile = "{0}.lib_stats" . format ( pf ) if op . exists ( statsfile ) : os . remove ( statsfile ) cmd = "SplitReadsByLibrary READS_IN={0}" . format ( fastbfile ) cmd += " READS_OUT={0} QUALS=True" . format ( pf ) sh ( cmd ) libs = [ ] fp = open ( statsfile ) next ( fp ) next ( fp ) for row in fp : if row . strip ( ) == "" : continue libname = row . split ( ) [ 0 ] if libname == "Unpaired" : continue libs . append ( libname ) logging . debug ( "Found libraries: {0}" . format ( "," . join ( libs ) ) ) cmds = [ ] for libname in libs : cmd = "FastbQualbToFastq" cmd += " HEAD_IN={0}.{1}.AB HEAD_OUT={1}" . format ( pf , libname ) cmd += " PAIRED=True PHRED_OFFSET=33" if sim : cmd += " SIMULATE_QUALS=True" if pf == 'j' : cmd += " FLIP=True" cmds . append ( ( cmd , ) ) m = Jobs ( target = sh , args = cmds ) m . run ( ) for libname in libs : cmd = "mv {0}.A.fastq {0}.1.fastq" . format ( libname ) sh ( cmd ) cmd = "mv {0}.B.fastq {0}.2.fastq" . format ( libname ) sh ( cmd )
%prog dump fastbfile
12,096
def fixpairs ( args ) : p = OptionParser ( fixpairs . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) pairsfile , sep , sd = args newpairsfile = pairsfile . rsplit ( "." , 1 ) [ 0 ] + ".new.pairs" sep = int ( sep ) sd = int ( sd ) p = PairsFile ( pairsfile ) p . fixLibraryStats ( sep , sd ) p . write ( newpairsfile )
%prog fixpairs pairsfile sep sd
12,097
def fill ( args ) : p = OptionParser ( fill . __doc__ ) p . add_option ( "--stretch" , default = 3 , type = "int" , help = "MAX_STRETCH to pass to FillFragments [default: %default]" ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) fastb , = args assert fastb == "frag_reads_corr.fastb" pcfile = "frag_reads_corr.k28.pc.info" nthreads = " NUM_THREADS={0}" . format ( opts . cpus ) maxstretch = " MAX_STRETCH={0}" . format ( opts . stretch ) if need_update ( fastb , pcfile ) : cmd = "PathReads READS_IN=frag_reads_corr" cmd += nthreads sh ( cmd ) filledfastb = "filled_reads.fastb" if need_update ( pcfile , filledfastb ) : cmd = "FillFragments PAIRS_OUT=frag_reads_corr_cpd" cmd += " PRECORRECT_LIBSTATS=True" cmd += maxstretch cmd += nthreads sh ( cmd ) filledfasta = "filled_reads.fasta" if need_update ( filledfastb , filledfasta ) : cmd = "Fastb2Fasta IN=filled_reads.fastb OUT=filled_reads.fasta" sh ( cmd )
%prog fill frag_reads_corr . fastb
12,098
def extract_pairs ( fastqfile , p1fw , p2fw , fragsfw , p , suffix = False ) : fp = open ( fastqfile ) currentID = 0 npairs = nfrags = 0 for x , lib in izip ( p . r1 , p . libs ) : while currentID != x : fragsfw . writelines ( islice ( fp , 4 ) ) currentID += 1 nfrags += 1 a = list ( islice ( fp , 4 ) ) b = list ( islice ( fp , 4 ) ) if suffix : name = a [ 0 ] . rstrip ( ) a [ 0 ] = name + "/1\n" b [ 0 ] = name + "/2\n" else : b [ 0 ] = a [ 0 ] p1fw [ lib ] . writelines ( a ) p2fw [ lib ] . writelines ( b ) currentID += 2 npairs += 2 while True : contents = list ( islice ( fp , 4 ) ) if not contents : break fragsfw . writelines ( contents ) nfrags += 1 logging . debug ( "A total of {0} paired reads written to `{1}`." . format ( npairs , "," . join ( x . name for x in p1fw + p2fw ) ) ) logging . debug ( "A total of {0} single reads written to `{1}`." . format ( nfrags , fragsfw . name ) ) expected_pairs = 2 * p . npairs expected_frags = p . nreads - 2 * p . npairs assert npairs == expected_pairs , "Expect {0} paired reads, got {1} instead" . format ( expected_pairs , npairs ) assert nfrags == expected_frags , "Expect {0} single reads, got {1} instead" . format ( expected_frags , nfrags )
Take fastqfile and array of pair ID extract adjacent pairs to outfile . Perform check on numbers when done . p1fw p2fw is a list of file handles each for one end . p is a Pairs instance .
12,099
def log ( args ) : from jcvi . algorithms . graph import nx , topological_sort p = OptionParser ( log . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) g = nx . DiGraph ( ) logfile , = args fp = open ( logfile ) row = fp . readline ( ) incalling = False basedb = { } while row : atoms = row . split ( ) if len ( atoms ) < 3 : row = fp . readline ( ) continue tag , token , trailing = atoms [ 0 ] , atoms [ 1 ] , atoms [ - 1 ] if trailing == 'file(s):' : numfiles = int ( atoms [ - 2 ] ) row = fp . readline ( ) assert row . strip ( ) == tag if token == "Calling" and not incalling : createfiles = [ ] for i in xrange ( numfiles ) : row = fp . readline ( ) createfiles . append ( row . split ( ) [ - 1 ] ) incalling = True if token == "from" and incalling : fromfiles = [ ] for i in xrange ( numfiles ) : row = fp . readline ( ) fromfiles . append ( row . split ( ) [ - 1 ] ) for a in fromfiles : for b in createfiles : ba , bb = op . basename ( a ) , op . basename ( b ) basedb [ ba ] = a basedb [ bb ] = b g . add_edge ( ba , bb ) incalling = False if token == "ln" : fromfile , createfile = atoms [ - 2 : ] ba , bb = op . basename ( fromfile ) , op . basename ( createfile ) if ba != bb : g . add_edge ( ba , bb ) row = fp . readline ( ) ts = [ basedb [ x ] for x in topological_sort ( g ) if x in basedb ] print ( "\n" . join ( ts ) )
%prog log logfile