idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
11,600
def score_evaluate ( tour , tour_sizes = None , tour_M = None ) : sizes_oo = np . array ( [ tour_sizes [ x ] for x in tour ] ) sizes_cum = np . cumsum ( sizes_oo ) - sizes_oo / 2 s = 0 size = len ( tour ) for ia in xrange ( size ) : a = tour [ ia ] for ib in xrange ( ia + 1 , size ) : b = tour [ ib ] links = tour_M [ a , b ] dist = sizes_cum [ ib ] - sizes_cum [ ia ] if dist > 1e7 : break s += links * 1. / dist return s ,
SLOW python version of the evaluation function . For benchmarking purposes only . Do not use in production .
11,601
def movieframe ( args ) : p = OptionParser ( movieframe . __doc__ ) p . add_option ( "--label" , help = "Figure title" ) p . set_beds ( ) p . set_outfile ( outfile = None ) opts , args , iopts = p . set_image_options ( args , figsize = "16x8" , style = "white" , cmap = "coolwarm" , format = "png" , dpi = 120 ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) tour , clmfile , anchorsfile = args tour = tour . split ( "," ) image_name = opts . outfile or ( "movieframe." + iopts . format ) label = opts . label or op . basename ( image_name ) . rsplit ( "." , 1 ) [ 0 ] clm = CLMFile ( clmfile ) totalbins , bins , breaks = make_bins ( tour , clm . tig_to_size ) M = read_clm ( clm , totalbins , bins ) fig = plt . figure ( 1 , ( iopts . w , iopts . h ) ) root = fig . add_axes ( [ 0 , 0 , 1 , 1 ] ) ax1 = fig . add_axes ( [ .05 , .1 , .4 , .8 ] ) ax2 = fig . add_axes ( [ .55 , .1 , .4 , .8 ] ) ax2_root = fig . add_axes ( [ .5 , 0 , .5 , 1 ] ) plot_heatmap ( ax1 , M , breaks , iopts ) qbed , sbed , qorder , sorder , is_self = check_beds ( anchorsfile , p , opts , sorted = False ) dotplot ( anchorsfile , qbed , sbed , fig , ax2_root , ax2 , sep = False , title = "" ) root . text ( .5 , .98 , clm . name , color = "g" , ha = "center" , va = "center" ) root . text ( .5 , .95 , label , color = "darkslategray" , ha = "center" , va = "center" ) normalize_axes ( root ) savefig ( image_name , dpi = iopts . dpi , iopts = iopts )
%prog movieframe tour test . clm contigs . ref . anchors
11,602
def write_agp ( self , obj , sizes , fw = sys . stdout , gapsize = 100 , gaptype = "contig" , evidence = "map" ) : contigorder = [ ( x . contig_name , x . strand ) for x in self ] order_to_agp ( obj , contigorder , sizes , fw , gapsize = gapsize , gaptype = gaptype , evidence = evidence )
Converts the ContigOrdering file into AGP format
11,603
def parse_ids ( self , skiprecover ) : idsfile = self . idsfile logging . debug ( "Parse idsfile `{}`" . format ( idsfile ) ) fp = open ( idsfile ) tigs = [ ] for row in fp : if row [ 0 ] == '#' : continue atoms = row . split ( ) tig , size = atoms [ : 2 ] size = int ( size ) if skiprecover and len ( atoms ) == 3 and atoms [ 2 ] == 'recover' : continue tigs . append ( ( tig , size ) ) _tigs , _sizes = zip ( * tigs ) self . contigs = set ( _tigs ) self . sizes = np . array ( _sizes ) self . tig_to_size = dict ( tigs ) self . active = set ( _tigs )
IDS file has a list of contigs that need to be ordered . recover keyword if available in the third column is less confident .
11,604
def calculate_densities ( self ) : active = self . active densities = defaultdict ( int ) for ( at , bt ) , links in self . contacts . items ( ) : if not ( at in active and bt in active ) : continue densities [ at ] += links densities [ bt ] += links logdensities = { } for x , d in densities . items ( ) : s = self . tig_to_size [ x ] logd = np . log10 ( d * 1. / min ( s , 500000 ) ) logdensities [ x ] = logd return logdensities
Calculate the density of inter - contig links per base . Strong contigs considered to have high level of inter - contig links in the current partition .
11,605
def evaluate_tour_M ( self , tour ) : from . chic import score_evaluate_M return score_evaluate_M ( tour , self . active_sizes , self . M )
Use Cythonized version to evaluate the score of a current tour
11,606
def evaluate_tour_P ( self , tour ) : from . chic import score_evaluate_P return score_evaluate_P ( tour , self . active_sizes , self . P )
Use Cythonized version to evaluate the score of a current tour with better precision on the distance of the contigs .
11,607
def evaluate_tour_Q ( self , tour ) : from . chic import score_evaluate_Q return score_evaluate_Q ( tour , self . active_sizes , self . Q )
Use Cythonized version to evaluate the score of a current tour taking orientation into consideration . This may be the most accurate evaluation under the right condition .
11,608
def flip_all ( self , tour ) : if self . signs is None : score = 0 else : old_signs = self . signs [ : self . N ] score , = self . evaluate_tour_Q ( tour ) self . signs = get_signs ( self . O , validate = False , ambiguous = False ) score_flipped , = self . evaluate_tour_Q ( tour ) if score_flipped >= score : tag = ACCEPT else : self . signs = old_signs [ : ] tag = REJECT self . flip_log ( "FLIPALL" , score , score_flipped , tag ) return tag
Initialize the orientations based on pairwise O matrix .
11,609
def flip_whole ( self , tour ) : score , = self . evaluate_tour_Q ( tour ) self . signs = - self . signs score_flipped , = self . evaluate_tour_Q ( tour ) if score_flipped > score : tag = ACCEPT else : self . signs = - self . signs tag = REJECT self . flip_log ( "FLIPWHOLE" , score , score_flipped , tag ) return tag
Test flipping all contigs at the same time to see if score improves .
11,610
def flip_one ( self , tour ) : n_accepts = n_rejects = 0 any_tag_ACCEPT = False for i , t in enumerate ( tour ) : if i == 0 : score , = self . evaluate_tour_Q ( tour ) self . signs [ t ] = - self . signs [ t ] score_flipped , = self . evaluate_tour_Q ( tour ) if score_flipped > score : n_accepts += 1 tag = ACCEPT else : self . signs [ t ] = - self . signs [ t ] n_rejects += 1 tag = REJECT self . flip_log ( "FLIPONE ({}/{})" . format ( i + 1 , len ( self . signs ) ) , score , score_flipped , tag ) if tag == ACCEPT : any_tag_ACCEPT = True score = score_flipped logging . debug ( "FLIPONE: N_accepts={} N_rejects={}" . format ( n_accepts , n_rejects ) ) return ACCEPT if any_tag_ACCEPT else REJECT
Test flipping every single contig sequentially to see if score improves .
11,611
def prune_tour ( self , tour , cpus ) : while True : tour_score , = self . evaluate_tour_M ( tour ) logging . debug ( "Starting score: {}" . format ( tour_score ) ) active_sizes = self . active_sizes M = self . M args = [ ] for i , t in enumerate ( tour ) : stour = tour [ : i ] + tour [ i + 1 : ] args . append ( ( t , stour , tour_score , active_sizes , M ) ) p = Pool ( processes = cpus ) results = list ( p . imap ( prune_tour_worker , args ) ) assert len ( tour ) == len ( results ) , "Array size mismatch, tour({}) != results({})" . format ( len ( tour ) , len ( results ) ) active_contigs = self . active_contigs idx , log10deltas = zip ( * results ) lb , ub = outlier_cutoff ( log10deltas ) logging . debug ( "Log10(delta_score) ~ [{}, {}]" . format ( lb , ub ) ) remove = set ( active_contigs [ x ] for ( x , d ) in results if d < lb ) self . active -= remove self . report_active ( ) tig_to_idx = self . tig_to_idx tour = [ active_contigs [ x ] for x in tour ] tour = array . array ( 'i' , [ tig_to_idx [ x ] for x in tour if x not in remove ] ) if not remove : break self . tour = tour self . flip_all ( tour ) return tour
Test deleting each contig and check the delta_score ; tour here must be an array of ints .
11,612
def M ( self ) : N = self . N tig_to_idx = self . tig_to_idx M = np . zeros ( ( N , N ) , dtype = int ) for ( at , bt ) , links in self . contacts . items ( ) : if not ( at in tig_to_idx and bt in tig_to_idx ) : continue ai = tig_to_idx [ at ] bi = tig_to_idx [ bt ] M [ ai , bi ] = M [ bi , ai ] = links return M
Contact frequency matrix . Each cell contains how many inter - contig links between i - th and j - th contigs .
11,613
def O ( self ) : N = self . N tig_to_idx = self . tig_to_idx O = np . zeros ( ( N , N ) , dtype = int ) for ( at , bt ) , ( strandedness , md , mh ) in self . orientations . items ( ) : if not ( at in tig_to_idx and bt in tig_to_idx ) : continue ai = tig_to_idx [ at ] bi = tig_to_idx [ bt ] score = strandedness * md O [ ai , bi ] = O [ bi , ai ] = score return O
Pairwise strandedness matrix . Each cell contains whether i - th and j - th contig are the same orientation + 1 or opposite orientation - 1 .
11,614
def P ( self ) : N = self . N tig_to_idx = self . tig_to_idx P = np . zeros ( ( N , N , 2 ) , dtype = int ) for ( at , bt ) , ( strandedness , md , mh ) in self . orientations . items ( ) : if not ( at in tig_to_idx and bt in tig_to_idx ) : continue ai = tig_to_idx [ at ] bi = tig_to_idx [ bt ] P [ ai , bi , 0 ] = P [ bi , ai , 0 ] = md P [ ai , bi , 1 ] = P [ bi , ai , 1 ] = mh return P
Contact frequency matrix with better precision on distance between contigs . In the matrix M the distance is assumed to be the distance between mid - points of two contigs . In matrix Q however we compute harmonic mean of the links for the orientation configuration that is shortest . This offers better precision for the distance between big contigs .
11,615
def Q ( self ) : N = self . N tig_to_idx = self . tig_to_idx signs = self . signs Q = np . ones ( ( N , N , BB ) , dtype = int ) * - 1 for ( at , bt ) , k in self . contacts_oriented . items ( ) : if not ( at in tig_to_idx and bt in tig_to_idx ) : continue ai = tig_to_idx [ at ] bi = tig_to_idx [ bt ] ao = signs [ ai ] bo = signs [ bi ] Q [ ai , bi ] = k [ ( ao , bo ) ] return Q
Contact frequency matrix when contigs are already oriented . This is s a similar matrix as M but rather than having the number of links in the cell it points to an array that has the actual distances .
11,616
def insertionpairs ( args ) : p = OptionParser ( insertionpairs . __doc__ ) p . add_option ( "--extend" , default = 10 , type = "int" , help = "Allow insertion sites to match up within distance" ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) bedfile , = args mergedbedfile = mergeBed ( bedfile , d = opts . extend , nms = True ) bed = Bed ( mergedbedfile ) fw = must_open ( opts . outfile , "w" ) support = lambda x : - x . reads for b in bed : names = b . accn . split ( "," ) ends = [ EndPoint ( x ) for x in names ] REs = sorted ( [ x for x in ends if x . leftright == "RE" ] , key = support ) LEs = sorted ( [ x for x in ends if x . leftright == "LE" ] , key = support ) if not ( REs and LEs ) : continue mRE , mLE = REs [ 0 ] , LEs [ 0 ] pRE , pLE = mRE . position , mLE . position if pLE < pRE : b . start , b . end = pLE - 1 , pRE else : b . start , b . end = pRE - 1 , pLE b . accn = "{0}|{1}" . format ( mRE . label , mLE . label ) b . score = pLE - pRE - 1 print ( b , file = fw )
%prog insertionpairs endpoints . bed
11,617
def insertion ( args ) : p = OptionParser ( insertion . __doc__ ) p . add_option ( "--mindepth" , default = 6 , type = "int" , help = "Minimum depth to call an insertion" ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) bedfile , = args mindepth = opts . mindepth bed = Bed ( bedfile ) fw = must_open ( opts . outfile , "w" ) for seqid , feats in bed . sub_beds ( ) : left_ends = Counter ( [ x . start for x in feats ] ) right_ends = Counter ( [ x . end for x in feats ] ) selected = [ ] for le , count in left_ends . items ( ) : if count >= mindepth : selected . append ( ( seqid , le , "LE-{0}" . format ( le ) , count ) ) for re , count in right_ends . items ( ) : if count >= mindepth : selected . append ( ( seqid , re , "RE-{0}" . format ( re ) , count ) ) selected . sort ( ) for seqid , pos , label , count in selected : label = "{0}-r{1}" . format ( label , count ) print ( "\t" . join ( ( seqid , str ( pos - 1 ) , str ( pos ) , label ) ) , file = fw )
%prog insertion mic . mac . bed
11,618
def add_sim_options ( p ) : p . add_option ( "--distance" , default = 500 , type = "int" , help = "Outer distance between the two ends [default: %default]" ) p . add_option ( "--readlen" , default = 150 , type = "int" , help = "Length of the read" ) p . set_depth ( depth = 10 ) p . set_outfile ( outfile = None )
Add options shared by eagle or wgsim .
11,619
def wgsim ( args ) : p = OptionParser ( wgsim . __doc__ ) p . add_option ( "--erate" , default = .01 , type = "float" , help = "Base error rate of the read [default: %default]" ) p . add_option ( "--noerrors" , default = False , action = "store_true" , help = "Simulate reads with no errors [default: %default]" ) p . add_option ( "--genomesize" , type = "int" , help = "Genome size in Mb [default: estimate from data]" ) add_sim_options ( p ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) fastafile , = args pf = op . basename ( fastafile ) . split ( "." ) [ 0 ] genomesize = opts . genomesize size = genomesize * 1000000 if genomesize else Fasta ( fastafile ) . totalsize depth = opts . depth readlen = opts . readlen readnum = int ( math . ceil ( size * depth / ( 2 * readlen ) ) ) distance = opts . distance stdev = distance / 10 outpf = opts . outfile or "{0}.{1}bp.{2}x" . format ( pf , distance , depth ) logging . debug ( "Total genome size: {0} bp" . format ( size ) ) logging . debug ( "Target depth: {0}x" . format ( depth ) ) logging . debug ( "Number of read pairs (2x{0}): {1}" . format ( readlen , readnum ) ) if opts . noerrors : opts . erate = 0 cmd = "dwgsim -e {0} -E {0}" . format ( opts . erate ) if opts . noerrors : cmd += " -r 0 -R 0 -X 0 -y 0" cmd += " -d {0} -s {1}" . format ( distance , stdev ) cmd += " -N {0} -1 {1} -2 {1}" . format ( readnum , readlen ) cmd += " {0} {1}" . format ( fastafile , outpf ) sh ( cmd )
%prog wgsim fastafile
11,620
def fig4 ( args ) : p = OptionParser ( fig4 . __doc__ ) p . add_option ( "--gauge_step" , default = 200000 , type = "int" , help = "Step size for the base scale" ) opts , args , iopts = p . set_image_options ( args , figsize = "9x7" ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) layout , datadir = args layout = F4ALayout ( layout , datadir = datadir ) gs = opts . gauge_step fig = plt . figure ( 1 , ( iopts . w , iopts . h ) ) root = fig . add_axes ( [ 0 , 0 , 1 , 1 ] ) block , napusbed , slayout = "r28.txt" , "all.bed" , "r28.layout" s = Synteny ( fig , root , block , napusbed , slayout , chr_label = False ) synteny_exts = [ ( x . xstart , x . xend ) for x in s . rr ] h = .1 order = "bzh,yudal" . split ( "," ) labels = ( r"\textit{B. napus} A$\mathsf{_n}$2" , r"\textit{B. rapa} A$\mathsf{_r}$2" , r"\textit{B. oleracea} C$\mathsf{_o}$2" , r"\textit{B. napus} C$\mathsf{_n}$2" ) for t in layout : xstart , xend = synteny_exts [ 2 * t . i ] canvas = [ xstart , t . y , xend - xstart , h ] root . text ( xstart - h , t . y + h / 2 , labels [ t . i ] , ha = "center" , va = "center" ) ch , ab = t . box_region . split ( ":" ) a , b = ab . split ( "-" ) vlines = [ int ( x ) for x in ( a , b ) ] Coverage ( fig , root , canvas , t . seqid , ( t . start , t . end ) , datadir , order = order , gauge = "top" , plot_chr_label = False , gauge_step = gs , palette = "gray" , cap = 40 , hlsuffix = "regions.forhaibao" , vlines = vlines ) a , b = ( 3 , "Bra029311" ) , ( 5 , "Bo2g161590" ) for gid in ( a , b ) : start , end = s . gg [ gid ] xstart , ystart = start xend , yend = end x = ( xstart + xend ) / 2 arrow = FancyArrowPatch ( posA = ( x , ystart - .04 ) , posB = ( x , ystart - .005 ) , arrowstyle = "fancy,head_width=6,head_length=8" , lw = 3 , fc = 'k' , ec = 'k' , zorder = 20 ) root . add_patch ( arrow ) root . set_xlim ( 0 , 1 ) root . set_ylim ( 0 , 1 ) root . set_axis_off ( ) image_name = "napus-fig4." + iopts . format savefig ( image_name , dpi = iopts . dpi , iopts = iopts )
%prog fig4 layout data
11,621
def ploidy ( args ) : p = OptionParser ( ploidy . __doc__ ) opts , args , iopts = p . set_image_options ( args , figsize = "8x7" ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) seqidsfile , klayout = args fig = plt . figure ( 1 , ( iopts . w , iopts . h ) ) root = fig . add_axes ( [ 0 , 0 , 1 , 1 ] ) Karyotype ( fig , root , seqidsfile , klayout ) fc = "darkslategrey" radius = .012 ot = - .05 TextCircle ( root , .1 , .9 + ot , r'$\gamma$' , radius = radius , fc = fc ) root . text ( .1 , .88 + ot , r"$\times3$" , ha = "center" , va = "top" , color = fc ) TextCircle ( root , .08 , .79 + ot , r'$\alpha$' , radius = radius , fc = fc ) TextCircle ( root , .12 , .79 + ot , r'$\beta$' , radius = radius , fc = fc ) root . text ( .1 , .77 + ot , r"$\times3\times2\times2$" , ha = "center" , va = "top" , color = fc ) root . text ( .1 , .67 + ot , r"Brassica triplication" , ha = "center" , va = "top" , color = fc , size = 11 ) root . text ( .1 , .65 + ot , r"$\times3\times2\times2\times3$" , ha = "center" , va = "top" , color = fc ) root . text ( .1 , .42 + ot , r"Allo-tetraploidy" , ha = "center" , va = "top" , color = fc , size = 11 ) root . text ( .1 , .4 + ot , r"$\times3\times2\times2\times3\times2$" , ha = "center" , va = "top" , color = fc ) bb = dict ( boxstyle = "round,pad=.5" , fc = "w" , ec = "0.5" , alpha = 0.5 ) root . text ( .5 , .2 + ot , r"\noindent\textit{Brassica napus}\\" "(A$\mathsf{_n}$C$\mathsf{_n}$ genome)" , ha = "center" , size = 16 , color = "k" , bbox = bb ) root . set_xlim ( 0 , 1 ) root . set_ylim ( 0 , 1 ) root . set_axis_off ( ) pf = "napus" image_name = pf + "." + iopts . format savefig ( image_name , dpi = iopts . dpi , iopts = iopts )
%prog ploidy seqids layout
11,622
def pasteprepare ( args ) : p = OptionParser ( pasteprepare . __doc__ ) p . add_option ( "--flank" , default = 5000 , type = "int" , help = "Get the seq of size on two ends [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) goodfasta , = args flank = opts . flank pf = goodfasta . rsplit ( "." , 1 ) [ 0 ] extbed = pf + ".ext.bed" sizes = Sizes ( goodfasta ) fw = open ( extbed , "w" ) for bac , size in sizes . iter_sizes ( ) : print ( "\t" . join ( str ( x ) for x in ( bac , 0 , min ( flank , size ) , bac + "L" ) ) , file = fw ) print ( "\t" . join ( str ( x ) for x in ( bac , max ( size - flank , 0 ) , size , bac + "R" ) ) , file = fw ) fw . close ( ) fastaFromBed ( extbed , goodfasta , name = True )
%prog pasteprepare bacs . fasta
11,623
def paste ( args ) : from jcvi . formats . bed import uniq p = OptionParser ( paste . __doc__ ) p . add_option ( "--maxsize" , default = 300000 , type = "int" , help = "Maximum size of patchers to be replaced [default: %default]" ) p . add_option ( "--prefix" , help = "Prefix of the new object [default: %default]" ) p . set_rclip ( rclip = 1 ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) pbed , blastfile , bbfasta = args maxsize = opts . maxsize order = Bed ( pbed ) . order beforebed , afterbed = blast_to_twobeds ( blastfile , order , log = True , rclip = opts . rclip , maxsize = maxsize , flipbeds = True ) beforebed = uniq ( [ beforebed ] ) afbed = Bed ( beforebed ) bfbed = Bed ( afterbed ) shuffle_twobeds ( afbed , bfbed , bbfasta , prefix = opts . prefix )
%prog paste flanks . bed flanks_vs_assembly . blast backbone . fasta
11,624
def eject ( args ) : p = OptionParser ( eject . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) candidates , chrfasta = args sizesfile = Sizes ( chrfasta ) . filename cbedfile = complementBed ( candidates , sizesfile ) cbed = Bed ( cbedfile ) for b in cbed : b . accn = b . seqid b . score = 1000 b . strand = '+' cbed . print_to_file ( )
%prog eject candidates . bed chr . fasta
11,625
def closest ( args ) : p = OptionParser ( closest . __doc__ ) p . add_option ( "--om" , default = False , action = "store_true" , help = "The bedfile is OM blocks [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) candidates , gapsbed , fastafile = args sizes = Sizes ( fastafile ) . mapping bed = Bed ( candidates ) ranges = [ ] for b in bed : r = range_parse ( b . accn ) if opts . om else b ranges . append ( [ r . seqid , r . start , r . end ] ) gapsbed = Bed ( gapsbed ) granges = [ ( x . seqid , x . start , x . end ) for x in gapsbed ] ranges = range_merge ( ranges ) for r in ranges : a = range_closest ( granges , r ) b = range_closest ( granges , r , left = False ) seqid = r [ 0 ] if a is not None and a [ 0 ] != seqid : a = None if b is not None and b [ 0 ] != seqid : b = None mmin = 1 if a is None else a [ 1 ] mmax = sizes [ seqid ] if b is None else b [ 2 ] print ( "\t" . join ( str ( x ) for x in ( seqid , mmin - 1 , mmax ) ) )
%prog closest candidates . bed gaps . bed fastafile
11,626
def insert ( args ) : from jcvi . formats . agp import mask , bed from jcvi . formats . sizes import agp p = OptionParser ( insert . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 4 : sys . exit ( not p . print_help ( ) ) candidates , gapsbed , chrfasta , unplacedfasta = args refinedbed = refine ( [ candidates , gapsbed ] ) sizes = Sizes ( unplacedfasta ) . mapping cbed = Bed ( candidates ) corder = cbed . order gbed = Bed ( gapsbed ) gorder = gbed . order gpbed = Bed ( ) gappositions = { } fp = open ( refinedbed ) gap_to_scf = defaultdict ( list ) seen = set ( ) for row in fp : atoms = row . split ( ) if len ( atoms ) <= 6 : continue unplaced = atoms [ 3 ] strand = atoms [ 5 ] gapid = atoms [ 9 ] if gapid not in seen : seen . add ( gapid ) gi , gb = gorder [ gapid ] gpbed . append ( gb ) gappositions [ ( gb . seqid , gb . start , gb . end ) ] = gapid gap_to_scf [ gapid ] . append ( ( unplaced , strand ) ) gpbedfile = "candidate.gaps.bed" gpbed . print_to_file ( gpbedfile , sorted = True ) agpfile = agp ( [ chrfasta ] ) maskedagpfile = mask ( [ agpfile , gpbedfile ] ) maskedbedfile = maskedagpfile . rsplit ( "." , 1 ) [ 0 ] + ".bed" bed ( [ maskedagpfile , "--outfile={0}" . format ( maskedbedfile ) ] ) mbed = Bed ( maskedbedfile ) finalbed = Bed ( ) for b in mbed : sid = b . seqid key = ( sid , b . start , b . end ) if key not in gappositions : finalbed . add ( "{0}\n" . format ( b ) ) continue gapid = gappositions [ key ] scfs = gap_to_scf [ gapid ] scfs . sort ( key = lambda x : corder [ x [ 0 ] ] [ 1 ] . start + corder [ x [ 0 ] ] [ 1 ] . end ) for scf , strand in scfs : size = sizes [ scf ] finalbed . add ( "\t" . join ( str ( x ) for x in ( scf , 0 , size , sid , 1000 , strand ) ) ) finalbedfile = "final.bed" finalbed . print_to_file ( finalbedfile ) toclean = [ gpbedfile , agpfile , maskedagpfile , maskedbedfile ] FileShredder ( toclean )
%prog insert candidates . bed gaps . bed chrs . fasta unplaced . fasta
11,627
def gaps ( args ) : from jcvi . formats . bed import uniq from jcvi . utils . iter import pairwise p = OptionParser ( gaps . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) ombed , fastafile = args ombed = uniq ( [ ombed ] ) bed = Bed ( ombed ) for a , b in pairwise ( bed ) : om_a = ( a . seqid , a . start , a . end , "+" ) om_b = ( b . seqid , b . start , b . end , "+" ) ch_a = range_parse ( a . accn ) ch_b = range_parse ( b . accn ) ch_a = ( ch_a . seqid , ch_a . start , ch_a . end , "+" ) ch_b = ( ch_b . seqid , ch_b . start , ch_b . end , "+" ) om_dist , x = range_distance ( om_a , om_b , distmode = "ee" ) ch_dist , x = range_distance ( ch_a , ch_b , distmode = "ee" ) if om_dist <= 0 and ch_dist <= 0 : continue print ( a ) print ( b ) print ( om_dist , ch_dist )
%prog gaps OM . bed fastafile
11,628
def tips ( args ) : p = OptionParser ( tips . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 4 : sys . exit ( not p . print_help ( ) ) pbedfile , cbedfile , sizesfile , bbfasta = args pbed = Bed ( pbedfile , sorted = False ) cbed = Bed ( cbedfile , sorted = False ) complements = dict ( ) for object , beds in groupby ( cbed , key = lambda x : x . seqid ) : beds = list ( beds ) complements [ object ] = beds sizes = Sizes ( sizesfile ) . mapping bbsizes = Sizes ( bbfasta ) . mapping tbeds = [ ] for object , beds in groupby ( pbed , key = lambda x : x . accn ) : beds = list ( beds ) startbed , endbed = beds [ 0 ] , beds [ - 1 ] start_id , end_id = startbed . seqid , endbed . seqid if startbed . start == 1 : start_id = None if endbed . end == sizes [ end_id ] : end_id = None print ( object , start_id , end_id , file = sys . stderr ) if start_id : b = complements [ start_id ] [ 0 ] b . accn = object tbeds . append ( b ) tbeds . append ( BedLine ( "\t" . join ( str ( x ) for x in ( object , 0 , bbsizes [ object ] , object , 1000 , "+" ) ) ) ) if end_id : b = complements [ end_id ] [ - 1 ] b . accn = object tbeds . append ( b ) tbed = Bed ( ) tbed . extend ( tbeds ) tbedfile = "tips.bed" tbed . print_to_file ( tbedfile )
%prog tips patchers . bed complements . bed original . fasta backbone . fasta
11,629
def fill ( args ) : p = OptionParser ( fill . __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 , badfasta = args Ext = opts . extend gapdist = 2 * Ext + 1 gapsbed = mergeBed ( gapsbed , d = gapdist , nms = True ) bed = Bed ( gapsbed ) sizes = Sizes ( badfasta ) . mapping pf = gapsbed . rsplit ( "." , 1 ) [ 0 ] extbed = pf + ".ext.bed" fw = open ( extbed , "w" ) for b in bed : gapname = b . accn start , end = max ( 0 , b . start - Ext - 1 ) , b . start - 1 print ( "\t" . join ( str ( x ) for x in ( b . seqid , start , end , gapname + "L" ) ) , file = fw ) start , end = b . end , min ( sizes [ b . seqid ] , b . end + Ext ) print ( "\t" . join ( str ( x ) for x in ( b . seqid , start , end , gapname + "R" ) ) , file = fw ) fw . close ( ) fastaFromBed ( extbed , badfasta , name = True )
%prog fill gaps . bed bad . fasta
11,630
def install ( args ) : from jcvi . apps . align import blast from jcvi . formats . fasta import SeqIO p = OptionParser ( install . __doc__ ) p . set_rclip ( rclip = 1 ) p . add_option ( "--maxsize" , default = 300000 , type = "int" , help = "Maximum size of patchers to be replaced [default: %default]" ) p . add_option ( "--prefix" , help = "Prefix of the new object [default: %default]" ) p . add_option ( "--strict" , default = False , action = "store_true" , help = "Only update if replacement has no gaps [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 4 : sys . exit ( not p . print_help ( ) ) pbed , pfasta , bbfasta , altfasta = args maxsize = opts . maxsize rclip = opts . rclip blastfile = blast ( [ altfasta , pfasta , "--wordsize=100" , "--pctid=99" ] ) order = Bed ( pbed ) . order beforebed , afterbed = blast_to_twobeds ( blastfile , order , rclip = rclip , maxsize = maxsize ) beforefasta = fastaFromBed ( beforebed , bbfasta , name = True , stranded = True ) afterfasta = fastaFromBed ( afterbed , altfasta , name = True , stranded = True ) ah = SeqIO . parse ( beforefasta , "fasta" ) bh = SeqIO . parse ( afterfasta , "fasta" ) count_Ns = lambda x : x . seq . count ( 'n' ) + x . seq . count ( 'N' ) exclude = set ( ) for arec , brec in zip ( ah , bh ) : an = count_Ns ( arec ) bn = count_Ns ( brec ) if opts . strict : if bn == 0 : continue elif bn < an : continue id = arec . id exclude . add ( id ) logging . debug ( "Ignore {0} updates because of decreasing quality." . format ( len ( exclude ) ) ) abed = Bed ( beforebed , sorted = False ) bbed = Bed ( afterbed , sorted = False ) abed = [ x for x in abed if x . accn not in exclude ] bbed = [ x for x in bbed if x . accn not in exclude ] abedfile = "before.filtered.bed" bbedfile = "after.filtered.bed" afbed = Bed ( ) afbed . extend ( abed ) bfbed = Bed ( ) bfbed . extend ( bbed ) afbed . print_to_file ( abedfile ) bfbed . print_to_file ( bbedfile ) shuffle_twobeds ( afbed , bfbed , bbfasta , prefix = opts . prefix )
%prog install patchers . bed patchers . fasta backbone . fasta alt . fasta
11,631
def refine ( args ) : p = OptionParser ( refine . __doc__ ) p . add_option ( "--closest" , default = False , action = "store_true" , help = "In case of no gaps, use closest [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) breakpointsbed , gapsbed = args ncols = len ( open ( breakpointsbed ) . next ( ) . split ( ) ) logging . debug ( "File {0} contains {1} columns." . format ( breakpointsbed , ncols ) ) cmd = "intersectBed -wao -a {0} -b {1}" . format ( breakpointsbed , gapsbed ) pf = "{0}.{1}" . format ( breakpointsbed . split ( "." ) [ 0 ] , gapsbed . split ( "." ) [ 0 ] ) ingapsbed = pf + ".bed" sh ( cmd , outfile = ingapsbed ) fp = open ( ingapsbed ) data = [ x . split ( ) for x in fp ] nogapsbed = pf + ".nogaps.bed" largestgapsbed = pf + ".largestgaps.bed" nogapsfw = open ( nogapsbed , "w" ) largestgapsfw = open ( largestgapsbed , "w" ) for b , gaps in groupby ( data , key = lambda x : x [ : ncols ] ) : gaps = list ( gaps ) gap = gaps [ 0 ] if len ( gaps ) == 1 and gap [ - 1 ] == "0" : assert gap [ - 3 ] == "." print ( "\t" . join ( b ) , file = nogapsfw ) continue gaps = [ ( int ( x [ - 1 ] ) , x ) for x in gaps ] maxgap = max ( gaps ) [ 1 ] print ( "\t" . join ( maxgap ) , file = largestgapsfw ) nogapsfw . close ( ) largestgapsfw . close ( ) beds = [ largestgapsbed ] toclean = [ nogapsbed , largestgapsbed ] if opts . closest : closestgapsbed = pf + ".closestgaps.bed" cmd = "closestBed -a {0} -b {1} -d" . format ( nogapsbed , gapsbed ) sh ( cmd , outfile = closestgapsbed ) beds += [ closestgapsbed ] toclean += [ closestgapsbed ] else : pointbed = pf + ".point.bed" pbed = Bed ( ) bed = Bed ( nogapsbed ) for b in bed : pos = ( b . start + b . end ) / 2 b . start , b . end = pos , pos pbed . append ( b ) pbed . print_to_file ( pointbed ) beds += [ pointbed ] toclean += [ pointbed ] refinedbed = pf + ".refined.bed" FileMerger ( beds , outfile = refinedbed ) . merge ( ) FileShredder ( toclean ) return refinedbed
%prog refine breakpoints . bed gaps . bed
11,632
def patcher ( args ) : from jcvi . formats . bed import uniq p = OptionParser ( patcher . __doc__ ) p . add_option ( "--backbone" , default = "OM" , help = "Prefix of the backbone assembly [default: %default]" ) p . add_option ( "--object" , default = "object" , help = "New object name [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) backbonebed , otherbed = args backbonebed = uniq ( [ backbonebed ] ) otherbed = uniq ( [ otherbed ] ) pf = backbonebed . split ( "." ) [ 0 ] key = lambda x : ( x . seqid , x . start , x . end ) cmd = "intersectBed -v -wa" cmd += " -a {0} -b {1}" . format ( otherbed , backbonebed ) outfile = otherbed . rsplit ( "." , 1 ) [ 0 ] + ".not." + backbonebed sh ( cmd , outfile = outfile ) uniqbed = Bed ( ) uniqbedfile = pf + ".merged.bed" uniqbed . extend ( Bed ( backbonebed ) ) uniqbed . extend ( Bed ( outfile ) ) uniqbed . print_to_file ( uniqbedfile , sorted = True ) bed = uniqbed key = lambda x : range_parse ( x . accn ) . seqid bed_fn = pf + ".patchers.bed" bed_fw = open ( bed_fn , "w" ) for k , sb in groupby ( bed , key = key ) : sb = list ( sb ) chr , start , end , strand = merge_ranges ( sb ) print ( "\t" . join ( str ( x ) for x in ( chr , start , end , opts . object , 1000 , strand ) ) , file = bed_fw ) bed_fw . close ( )
%prog patcher backbone . bed other . bed
11,633
def treds ( args ) : p = OptionParser ( treds . __doc__ ) p . add_option ( "--csv" , default = False , action = "store_true" , help = "Also write `meta.csv`" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) tredresults , = args df = pd . read_csv ( tredresults , sep = "\t" ) tredsfile = datafile ( "TREDs.meta.csv" ) tf = pd . read_csv ( tredsfile ) tds = list ( tf [ "abbreviation" ] ) ids = list ( tf [ "id" ] ) tags = [ "SampleKey" ] final_columns = [ "SampleKey" ] afs = [ ] for td , id in zip ( tds , ids ) : tag1 = "{}.1" . format ( td ) tag2 = "{}.2" . format ( td ) if tag2 not in df : afs . append ( "{}" ) continue tags . append ( tag2 ) final_columns . append ( id ) a = np . array ( list ( df [ tag1 ] ) + list ( df [ tag2 ] ) ) counts = alleles_to_counts ( a ) af = counts_to_af ( counts ) afs . append ( af ) tf [ "allele_frequency" ] = afs metafile = "TREDs_{}_SEARCH.meta.tsv" . format ( timestamp ( ) ) tf . to_csv ( metafile , sep = "\t" , index = False ) logging . debug ( "File `{}` written." . format ( metafile ) ) if opts . csv : metacsvfile = metafile . rsplit ( "." , 1 ) [ 0 ] + ".csv" tf . to_csv ( metacsvfile , index = False ) logging . debug ( "File `{}` written." . format ( metacsvfile ) ) pp = df [ tags ] pp . columns = final_columns datafile = "TREDs_{}_SEARCH.data.tsv" . format ( timestamp ( ) ) pp . to_csv ( datafile , sep = "\t" , index = False ) logging . debug ( "File `{}` written." . format ( datafile ) ) mask ( [ datafile , metafile ] )
%prog treds hli . tred . tsv
11,634
def stutter ( args ) : p = OptionParser ( stutter . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) vcf , = args pf = op . basename ( vcf ) . split ( "." ) [ 0 ] execid , sampleid = pf . split ( "_" ) C = "vcftools --remove-filtered-all --min-meanDP 10" C += " --gzvcf {} --out {}" . format ( vcf , pf ) C += " --indv {}" . format ( sampleid ) info = pf + ".INFO" if need_update ( vcf , info ) : cmd = C + " --get-INFO MOTIF --get-INFO RL" sh ( cmd ) allreads = pf + ".ALLREADS.FORMAT" if need_update ( vcf , allreads ) : cmd = C + " --extract-FORMAT-info ALLREADS" sh ( cmd ) q = pf + ".Q.FORMAT" if need_update ( vcf , q ) : cmd = C + " --extract-FORMAT-info Q" sh ( cmd ) outfile = pf + ".STUTTER" if need_update ( ( info , allreads , q ) , outfile ) : cmd = "cut -f1,2,5,6 {}" . format ( info ) cmd += r" | sed -e 's/\t/_/g'" cmd += " | paste - {} {}" . format ( allreads , q ) cmd += " | cut -f1,4,7" sh ( cmd , outfile = outfile )
%prog stutter a . vcf . gz
11,635
def filtervcf ( args ) : p = OptionParser ( filtervcf . __doc__ ) p . set_home ( "lobstr" , default = "/mnt/software/lobSTR" ) p . set_aws_opts ( store = "hli-mv-data-science/htang/str" ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) samples , = args lhome = opts . lobstr_home store = opts . output_path if samples . endswith ( ( ".vcf" , ".vcf.gz" ) ) : vcffiles = [ samples ] else : vcffiles = [ x . strip ( ) for x in must_open ( samples ) ] vcffiles = [ x for x in vcffiles if ".filtered." not in x ] run_args = [ ( x , lhome , x . startswith ( "s3://" ) and store ) for x in vcffiles ] cpus = min ( opts . cpus , len ( run_args ) ) p = Pool ( processes = cpus ) for res in p . map_async ( run_filter , run_args ) . get ( ) : continue
%prog filtervcf NA12878 . hg38 . vcf . gz
11,636
def meta ( args ) : p = OptionParser ( meta . __doc__ ) p . add_option ( "--cutoff" , default = .5 , type = "float" , help = "Percent observed required (chrY half cutoff)" ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 4 : sys . exit ( not p . print_help ( ) ) binfile , sampleids , strids , wobed = args cutoff = opts . cutoff af_file = "allele_freq" if need_update ( binfile , af_file ) : df , m , samples , loci = read_binfile ( binfile , sampleids , strids ) nalleles = len ( samples ) fw = must_open ( af_file , "w" ) for i , locus in enumerate ( loci ) : a = m [ : , i ] counts = alleles_to_counts ( a ) af = counts_to_af ( counts ) seqid = locus . split ( "_" ) [ 0 ] remove = counts_filter ( counts , nalleles , seqid , cutoff = cutoff ) print ( "\t" . join ( ( locus , af , remove ) ) , file = fw ) fw . close ( ) logging . debug ( "Load gene intersections from `{}`" . format ( wobed ) ) fp = open ( wobed ) gene_map = defaultdict ( set ) for row in fp : chr1 , start1 , end1 , chr2 , start2 , end2 , name , ov = row . split ( ) gene_map [ ( chr1 , start1 ) ] |= set ( name . split ( "," ) ) for k , v in gene_map . items ( ) : non_enst = sorted ( x for x in v if not x . startswith ( "ENST" ) ) gene_map [ k ] = "," . join ( non_enst ) TREDS , df = read_treds ( ) metafile = "STRs_{}_SEARCH.meta.tsv" . format ( timestamp ( ) ) write_meta ( af_file , gene_map , TREDS , filename = metafile ) logging . debug ( "File `{}` written." . format ( metafile ) )
%prog meta data . bin samples STR . ids STR - exons . wo . bed
11,637
def bin ( args ) : p = OptionParser ( bin . __doc__ ) p . add_option ( "--dtype" , choices = ( "float32" , "int32" ) , help = "dtype of the matrix" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) tsvfile , = args dtype = opts . dtype if dtype is None : dtype = np . int32 if "data" in tsvfile else np . float32 else : dtype = np . int32 if dtype == "int32" else np . float32 print ( "dtype: {}" . format ( dtype ) , file = sys . stderr ) fp = open ( tsvfile ) next ( fp ) arrays = [ ] for i , row in enumerate ( fp ) : a = np . fromstring ( row , sep = "\t" , dtype = dtype ) a = a [ 1 : ] arrays . append ( a ) print ( i , a , file = sys . stderr ) print ( "Merging" , file = sys . stderr ) b = np . concatenate ( arrays ) print ( "Binary shape: {}" . format ( b . shape ) , file = sys . stderr ) binfile = tsvfile . rsplit ( "." , 1 ) [ 0 ] + ".bin" b . tofile ( binfile )
%prog bin data . tsv
11,638
def data ( args ) : p = OptionParser ( data . __doc__ ) p . add_option ( "--notsv" , default = False , action = "store_true" , help = "Do not write data.tsv" ) opts , args = p . parse_args ( args ) if len ( args ) != 4 : sys . exit ( not p . print_help ( ) ) databin , sampleids , strids , metafile = args final_columns , percentiles = read_meta ( metafile ) df , m , samples , loci = read_binfile ( databin , sampleids , strids ) m %= 1000 m [ m == 999 ] = - 1 final = set ( final_columns ) remove = [ ] for i , locus in enumerate ( loci ) : if locus not in final : remove . append ( locus ) continue pf = "STRs_{}_SEARCH" . format ( timestamp ( ) ) filteredstrids = "{}.STR.ids" . format ( pf ) fw = open ( filteredstrids , "w" ) print ( "\n" . join ( final_columns ) , file = fw ) fw . close ( ) logging . debug ( "Dropped {} columns; Retained {} columns (`{}`)" . format ( len ( remove ) , len ( final_columns ) , filteredstrids ) ) df . drop ( remove , inplace = True , axis = 1 ) df . columns = final_columns filtered_bin = "{}.data.bin" . format ( pf ) if need_update ( databin , filtered_bin ) : m = df . as_matrix ( ) m . tofile ( filtered_bin ) logging . debug ( "Filtered binary matrix written to `{}`" . format ( filtered_bin ) ) filtered_tsv = "{}.data.tsv" . format ( pf ) if not opts . notsv and need_update ( databin , filtered_tsv ) : df . to_csv ( filtered_tsv , sep = "\t" , index_label = "SampleKey" )
%prog data data . bin samples . ids STR . ids meta . tsv
11,639
def mask ( args ) : p = OptionParser ( mask . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) not in ( 2 , 4 ) : sys . exit ( not p . print_help ( ) ) if len ( args ) == 4 : databin , sampleids , strids , metafile = args df , m , samples , loci = read_binfile ( databin , sampleids , strids ) mode = "STRs" elif len ( args ) == 2 : databin , metafile = args df = pd . read_csv ( databin , sep = "\t" , index_col = 0 ) m = df . as_matrix ( ) samples = df . index loci = list ( df . columns ) mode = "TREDs" pf = "{}_{}_SEARCH" . format ( mode , timestamp ( ) ) final_columns , percentiles = read_meta ( metafile ) maskfile = pf + ".mask.tsv" run_args = [ ] for i , locus in enumerate ( loci ) : a = m [ : , i ] percentile = percentiles [ locus ] run_args . append ( ( i , a , percentile ) ) if mode == "TREDs" or need_update ( databin , maskfile ) : cpus = min ( 8 , len ( run_args ) ) write_mask ( cpus , samples , final_columns , run_args , filename = maskfile ) logging . debug ( "File `{}` written." . format ( maskfile ) )
%prog mask data . bin samples . ids STR . ids meta . tsv
11,640
def compilevcf ( args ) : p = OptionParser ( compilevcf . __doc__ ) p . add_option ( "--db" , default = "hg38" , help = "Use these lobSTR db" ) p . add_option ( "--nofilter" , default = False , action = "store_true" , help = "Do not filter the variants" ) p . set_home ( "lobstr" ) p . set_cpus ( ) p . set_aws_opts ( store = "hli-mv-data-science/htang/str-data" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) samples , = args workdir = opts . workdir store = opts . output_path cleanup = not opts . nocleanup filtered = not opts . nofilter dbs = opts . db . split ( "," ) cwd = os . getcwd ( ) mkdir ( workdir ) os . chdir ( workdir ) samples = op . join ( cwd , samples ) stridsfile = "STR.ids" if samples . endswith ( ( ".vcf" , ".vcf.gz" ) ) : vcffiles = [ samples ] else : vcffiles = [ x . strip ( ) for x in must_open ( samples ) ] if not op . exists ( stridsfile ) : ids = [ ] for db in dbs : ids . extend ( STRFile ( opts . lobstr_home , db = db ) . ids ) uids = uniqify ( ids ) logging . debug ( "Combined: {} Unique: {}" . format ( len ( ids ) , len ( uids ) ) ) fw = open ( stridsfile , "w" ) print ( "\n" . join ( uids ) , file = fw ) fw . close ( ) run_args = [ ( x , filtered , cleanup , store ) for x in vcffiles ] cpus = min ( opts . cpus , len ( run_args ) ) p = Pool ( processes = cpus ) for res in p . map_async ( run_compile , run_args ) . get ( ) : continue
%prog compilevcf samples . csv
11,641
def ystr ( args ) : from jcvi . utils . table import write_csv p = OptionParser ( ystr . __doc__ ) p . set_home ( "lobstr" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) vcffile , = args si = STRFile ( opts . lobstr_home , db = "hg38-named" ) register = si . register header = "Marker|Reads|Ref|Genotype|Motif" . split ( "|" ) contents = [ ] fp = must_open ( vcffile ) reader = vcf . Reader ( fp ) simple_register = { } for record in reader : name = register [ ( record . CHROM , record . POS ) ] info = record . INFO ref = int ( float ( info [ "REF" ] ) ) rpa = info . get ( "RPA" , ref ) if isinstance ( rpa , list ) : rpa = "|" . join ( str ( int ( float ( x ) ) ) for x in rpa ) ru = info [ "RU" ] simple_register [ name ] = rpa for sample in record . samples : contents . append ( ( name , sample [ "ALLREADS" ] , ref , rpa , ru ) ) a , b , c = "DYS389I" , "DYS389B.1" , "DYS389B" if a in simple_register and b in simple_register : simple_register [ c ] = int ( simple_register [ a ] ) + int ( simple_register [ b ] ) mm = [ "DYS385" , "DYS413" , "YCAII" ] for m in mm : ma , mb = m + 'a' , m + 'b' if ma not in simple_register or mb not in simple_register : simple_register [ ma ] = simple_register [ mb ] = None del simple_register [ ma ] del simple_register [ mb ] continue if simple_register [ ma ] > simple_register [ mb ] : simple_register [ ma ] , simple_register [ mb ] = simple_register [ mb ] , simple_register [ ma ] write_csv ( header , contents , sep = " " ) print ( "[YSEARCH]" ) build_ysearch_link ( simple_register ) print ( "[YFILER]" ) build_yhrd_link ( simple_register , panel = YHRD_YFILER ) print ( "[YFILERPLUS]" ) build_yhrd_link ( simple_register , panel = YHRD_YFILERPLUS ) print ( "[YSTR-ALL]" ) build_yhrd_link ( simple_register , panel = USYSTR_ALL )
%prog ystr chrY . vcf
11,642
def liftover ( args ) : p = OptionParser ( liftover . __doc__ ) p . add_option ( "--checkvalid" , default = False , action = "store_true" , help = "Check minscore, period and length" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) refbed , fastafile = args genome = pyfasta . Fasta ( fastafile ) edits = [ ] fp = open ( refbed ) for i , row in enumerate ( fp ) : s = STRLine ( row ) seq = genome [ s . seqid ] [ s . start - 1 : s . end ] . upper ( ) s . motif = get_motif ( seq , len ( s . motif ) ) s . fix_counts ( seq ) if opts . checkvalid and not s . is_valid ( ) : continue edits . append ( s ) if i % 10000 == 0 : print ( i , "lines read" , file = sys . stderr ) edits = natsorted ( edits , key = lambda x : ( x . seqid , x . start ) ) for e in edits : print ( str ( e ) )
%prog liftover lobstr_v3 . 0 . 2_hg38_ref . bed hg38 . upper . fa
11,643
def trf ( args ) : from jcvi . apps . base import iglob cparams = "1 1 2 80 5 200 2000" p = OptionParser ( trf . __doc__ ) p . add_option ( "--mismatch" , default = 31 , type = "int" , help = "Mismatch and gap penalty" ) p . add_option ( "--minscore" , default = MINSCORE , type = "int" , help = "Minimum score to report" ) p . add_option ( "--period" , default = 6 , type = "int" , help = "Maximum period to report" ) p . add_option ( "--lobstr" , default = False , action = "store_true" , help = "Generate output for lobSTR" ) p . add_option ( "--telomeres" , default = False , action = "store_true" , help = "Run telomere search: minscore=140 period=7" ) p . add_option ( "--centromeres" , default = False , action = "store_true" , help = "Run centromere search: {}" . format ( cparams ) ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) outdir , = args minlength = opts . minscore / 2 mm = MakeManager ( ) if opts . telomeres : opts . minscore , opts . period = 140 , 7 params = "2 {0} {0} 80 10 {1} {2}" . format ( opts . mismatch , opts . minscore , opts . period ) . split ( ) if opts . centromeres : params = cparams . split ( ) bedfiles = [ ] for fastafile in natsorted ( iglob ( outdir , "*.fa,*.fasta" ) ) : pf = op . basename ( fastafile ) . split ( "." ) [ 0 ] cmd1 = "trf {0} {1} -d -h" . format ( fastafile , " " . join ( params ) ) datfile = op . basename ( fastafile ) + "." + "." . join ( params ) + ".dat" bedfile = "{0}.trf.bed" . format ( pf ) cmd2 = "cat {} | grep -v ^Parameters" . format ( datfile ) if opts . lobstr : cmd2 += " | awk '($8 >= {} && $8 <= {})'" . format ( minlength , READLEN - minlength ) else : cmd2 += " | awk '($8 >= 0)'" cmd2 += " | sed 's/ /\\t/g'" cmd2 += " | awk '{{print \"{0}\\t\" $0}}' > {1}" . format ( pf , bedfile ) mm . add ( fastafile , datfile , cmd1 ) mm . add ( datfile , bedfile , cmd2 ) bedfiles . append ( bedfile ) bedfile = "trf.bed" cmd = "cat {0} > {1}" . format ( " " . join ( natsorted ( bedfiles ) ) , bedfile ) mm . add ( bedfiles , bedfile , cmd ) mm . write ( )
%prog trf outdir
11,644
def batchlobstr ( args ) : p = OptionParser ( batchlobstr . __doc__ ) p . add_option ( "--sep" , default = "," , help = "Separator for building commandline" ) p . set_home ( "lobstr" , default = "s3://hli-mv-data-science/htang/str-build/lobSTR/" ) p . set_aws_opts ( store = "hli-mv-data-science/htang/str-data" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) samplesfile , = args store = opts . output_path computed = ls_s3 ( store ) fp = open ( samplesfile ) skipped = total = 0 for row in fp : total += 1 sample , s3file = row . strip ( ) . split ( "," ) [ : 2 ] exec_id , sample_id = sample . split ( "_" ) bamfile = s3file . replace ( ".gz" , "" ) . replace ( ".vcf" , ".bam" ) gzfile = sample + ".{0}.vcf.gz" . format ( "hg38" ) if gzfile in computed : skipped += 1 continue print ( opts . sep . join ( "python -m jcvi.variation.str lobstr" . split ( ) + [ "hg38" , "--input_bam_path" , bamfile , "--output_path" , store , "--sample_id" , sample_id , "--workflow_execution_id" , exec_id , "--lobstr_home" , opts . lobstr_home , "--workdir" , opts . workdir ] ) ) fp . close ( ) logging . debug ( "Total skipped: {0}" . format ( percentage ( skipped , total ) ) )
%prog batchlobstr samples . csv
11,645
def locus ( args ) : from jcvi . formats . sam import get_minibam INCLUDE = [ "HD" , "SBMA" , "SCA1" , "SCA2" , "SCA8" , "SCA17" , "DM1" , "DM2" , "FXTAS" ] db_choices = ( "hg38" , "hg19" ) p = OptionParser ( locus . __doc__ ) p . add_option ( "--tred" , choices = INCLUDE , help = "TRED name" ) p . add_option ( "--ref" , choices = db_choices , default = "hg38" , help = "Reference genome" ) p . set_home ( "lobstr" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) bamfile , = args ref = opts . ref lhome = opts . lobstr_home tred = opts . tred tredsfile = datafile ( "TREDs.meta.csv" ) tf = pd . read_csv ( tredsfile , index_col = 0 ) row = tf . ix [ tred ] tag = "repeat_location" ldb = "TREDs" if ref == "hg19" : tag += "." + ref ldb += "-" + ref seqid , start_end = row [ tag ] . split ( ":" ) PAD = 1000 start , end = start_end . split ( '-' ) start , end = int ( start ) - PAD , int ( end ) + PAD region = "{}:{}-{}" . format ( seqid , start , end ) minibamfile = get_minibam ( bamfile , region ) c = seqid . replace ( "chr" , "" ) cmd , vcf = allelotype_on_chr ( minibamfile , c , lhome , ldb ) sh ( cmd ) parser = LobSTRvcf ( columnidsfile = None ) parser . parse ( vcf , filtered = False ) items = parser . items ( ) if not items : print ( "No entry found!" , file = sys . stderr ) return k , v = parser . items ( ) [ 0 ] print ( "{} => {}" . format ( tred , v . replace ( ',' , '/' ) ) , file = sys . stderr )
%prog locus bamfile
11,646
def lobstrindex ( args ) : p = OptionParser ( lobstrindex . __doc__ ) p . add_option ( "--notreds" , default = False , action = "store_true" , help = "Remove TREDs from the bed file" ) p . set_home ( "lobstr" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) trfbed , fastafile = args pf = fastafile . split ( "." ) [ 0 ] lhome = opts . lobstr_home mkdir ( pf ) if opts . notreds : newbedfile = trfbed + ".new" newbed = open ( newbedfile , "w" ) fp = open ( trfbed ) retained = total = 0 seen = set ( ) for row in fp : r = STRLine ( row ) total += 1 name = r . longname if name in seen : continue seen . add ( name ) print ( r , file = newbed ) retained += 1 newbed . close ( ) logging . debug ( "Retained: {0}" . format ( percentage ( retained , total ) ) ) else : newbedfile = trfbed mm = MakeManager ( ) cmd = "python {0}/scripts/lobstr_index.py" . format ( lhome ) cmd += " --str {0} --ref {1} --out {2}" . format ( newbedfile , fastafile , pf ) mm . add ( ( newbedfile , fastafile ) , op . join ( pf , "lobSTR_ref.fasta.rsa" ) , cmd ) tabfile = "{0}/index.tab" . format ( pf ) cmd = "python {0}/scripts/GetSTRInfo.py" . format ( lhome ) cmd += " {0} {1} > {2}" . format ( newbedfile , fastafile , tabfile ) mm . add ( ( newbedfile , fastafile ) , tabfile , cmd ) infofile = "{0}/index.info" . format ( pf ) cmd = "cp {0} {1}" . format ( newbedfile , infofile ) mm . add ( trfbed , infofile , cmd ) mm . write ( )
%prog lobstrindex hg38 . trf . bed hg38 . upper . fa
11,647
def agp ( args ) : p = OptionParser ( agp . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) evidencefile , contigs = args ef = EvidenceFile ( evidencefile , contigs ) agpfile = evidencefile . replace ( ".evidence" , ".agp" ) ef . write_agp ( agpfile )
%prog agp evidencefile contigs . fasta
11,648
def spades ( args ) : from jcvi . formats . fastq import readlen p = OptionParser ( spades . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) == 0 : sys . exit ( not p . print_help ( ) ) folder , = args for p , pf in iter_project ( folder ) : rl = readlen ( [ p [ 0 ] , "--silent" ] ) kmers = None if rl >= 150 : kmers = "21,33,55,77" elif rl >= 250 : kmers = "21,33,55,77,99,127" cmd = "spades.py" if kmers : cmd += " -k {0}" . format ( kmers ) cmd += " --careful" cmd += " --pe1-1 {0} --pe1-2 {1}" . format ( * p ) cmd += " -o {0}_spades" . format ( pf ) print ( cmd )
%prog spades folder
11,649
def contamination ( args ) : from jcvi . apps . bowtie import align p = OptionParser ( contamination . __doc__ ) p . add_option ( "--mapped" , default = False , action = "store_true" , help = "Retain contaminated reads instead [default: %default]" ) p . set_cutoff ( cutoff = 800 ) p . set_mateorientation ( mateorientation = "+-" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) folder , ecoli = args ecoli = get_abs_path ( ecoli ) tag = "--mapped" if opts . mapped else "--unmapped" for p , pf in iter_project ( folder ) : align_opts = [ ecoli ] + p + [ tag ] align_opts += [ "--cutoff={0}" . format ( opts . cutoff ) , "--null" ] if opts . mateorientation : align_opts += [ "--mateorientation={0}" . format ( opts . mateorientation ) ] samfile , logfile = align ( align_opts )
%prog contamination folder Ecoli . fasta
11,650
def pairs ( args ) : p = OptionParser ( pairs . __doc__ ) p . set_firstN ( ) p . set_mates ( ) p . set_aligner ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) cwd = os . getcwd ( ) aligner = opts . aligner work = "-" . join ( ( "pairs" , aligner ) ) mkdir ( work ) from jcvi . formats . sam import pairs as ps if aligner == "bowtie" : from jcvi . apps . bowtie import align elif aligner == "bwa" : from jcvi . apps . bwa import align folder , ref = args ref = get_abs_path ( ref ) messages = [ ] for p , prefix in iter_project ( folder ) : samplefq = [ ] for i in range ( 2 ) : samplefq . append ( op . join ( work , prefix + "_{0}.first.fastq" . format ( i + 1 ) ) ) first ( [ str ( opts . firstN ) ] + [ p [ i ] ] + [ "-o" , samplefq [ i ] ] ) os . chdir ( work ) align_args = [ ref ] + [ op . basename ( fq ) for fq in samplefq ] outfile , logfile = align ( align_args ) bedfile , stats = ps ( [ outfile , "--rclip={0}" . format ( opts . rclip ) ] ) os . chdir ( cwd ) median = stats . median tag = "MP" if median > 1000 else "PE" median = str ( median ) pf , sf = median [ : 2 ] , median [ 2 : ] if sf and int ( sf ) != 0 : pf = str ( int ( pf ) + 1 ) lib = "{0}-{1}" . format ( tag , pf + '0' * len ( sf ) ) for i , xp in enumerate ( p ) : suffix = "fastq.gz" if xp . endswith ( ".gz" ) else "fastq" link = "{0}-{1}.{2}.{3}" . format ( lib , prefix . replace ( "-" , "" ) , i + 1 , suffix ) m = "\t" . join ( str ( x ) for x in ( xp , link ) ) messages . append ( m ) messages = "\n" . join ( messages ) write_file ( "f.meta" , messages , tee = True )
%prog pairs folder reference . fasta
11,651
def allpaths ( args ) : p = OptionParser ( allpaths . __doc__ ) p . add_option ( "--ploidy" , default = "1" , choices = ( "1" , "2" ) , help = "Ploidy [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) == 0 : sys . exit ( not p . print_help ( ) ) folders = args for pf in folders : if not op . isdir ( pf ) : continue assemble_dir ( pf , target = [ "final.contigs.fasta" , "final.assembly.fasta" ] , ploidy = opts . ploidy )
%prog allpaths folder1 folder2 ...
11,652
def prepare ( args ) : p = OptionParser ( prepare . __doc__ ) p . add_option ( "--first" , default = 0 , type = "int" , help = "Use only first N reads [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) jfile , = args metafile = jfile + ".meta" if need_update ( jfile , metafile ) : fp = open ( jfile ) fastqfiles = [ x . strip ( ) for x in fp if ".fastq" in x ] metas = [ Meta ( x ) for x in fastqfiles ] fw = open ( metafile , "w" ) print ( "\n" . join ( str ( x ) for x in metas ) , file = fw ) print ( "Now modify `{0}`, and restart this script." . format ( metafile ) , file = sys . stderr ) print ( "Each line is : genome library fastqfile" , file = sys . stderr ) fw . close ( ) return mf = MetaFile ( metafile ) for m in mf : m . make_link ( firstN = opts . first )
%prog prepare jira . txt
11,653
def assemble_pairs ( p , pf , tag , target = [ "final.contigs.fasta" ] ) : slink ( p , pf , tag ) assemble_dir ( pf , target )
Take one pair of reads and assemble to contigs . fasta .
11,654
def soap_trios ( p , pf , tag , extra ) : from jcvi . assembly . soap import prepare logging . debug ( "Work on {0} ({1})" . format ( pf , ',' . join ( p ) ) ) asm = "{0}.closed.scafSeq" . format ( pf ) if not need_update ( p , asm ) : logging . debug ( "Assembly found: {0}. Skipped." . format ( asm ) ) return slink ( p , pf , tag , extra ) cwd = os . getcwd ( ) os . chdir ( pf ) prepare ( sorted ( glob ( "*.fastq" ) + glob ( "*.fastq.gz" ) ) + [ "--assemble_1st_rank_only" , "-K 31" ] ) sh ( "./run.sh" ) sh ( "cp asm31.closed.scafSeq ../{0}" . format ( asm ) ) logging . debug ( "Assembly finished: {0}" . format ( asm ) ) os . chdir ( cwd )
Take one pair of reads and widow reads after correction and run SOAP .
11,655
def correctX ( args ) : p = OptionParser ( correctX . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) folder , tag = args tag = tag . split ( "," ) for p , pf in iter_project ( folder ) : correct_pairs ( p , pf , tag )
%prog correctX folder tag
11,656
def allpathsX ( args ) : p = OptionParser ( allpathsX . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) folder , tag = args tag = tag . split ( "," ) for p , pf in iter_project ( folder ) : assemble_pairs ( p , pf , tag )
%prog allpathsX folder tag
11,657
def stats ( args ) : p = OptionParser ( stats . __doc__ ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) folder , = args statsfiles = iglob ( folder , "*.stats" ) after_equal = lambda x : x . split ( "=" ) [ - 1 ] header = "Library Assembled_reads Contigs" . split ( ) contents = [ ] for statsfile in statsfiles : fp = open ( statsfile ) for row in fp : if row . startswith ( "label=" ) : break label , total , cnts = row . split ( ) [ : 3 ] label = after_equal ( label ) reads = int ( after_equal ( total ) ) contigs = int ( after_equal ( cnts ) ) contents . append ( ( label , reads , contigs ) ) all_labels , all_reads , all_contigs = zip ( * contents ) contents . append ( ( "SUM" , sum ( all_reads ) , sum ( all_contigs ) ) ) contents . append ( ( "AVERAGE (per sample)" , int ( np . mean ( all_reads ) ) , int ( np . mean ( all_contigs ) ) ) ) contents . append ( ( "MEDIAN (per sample)" , int ( np . median ( all_reads ) ) , int ( np . median ( all_contigs ) ) ) ) write_csv ( header , contents , filename = opts . outfile )
%prog stats folder
11,658
def stack ( S ) : S , nreps = zip ( * S ) S = np . array ( [ list ( x ) for x in S ] ) rows , cols = S . shape counts = [ ] for c in xrange ( cols ) : freq = [ 0 ] * NBASES for b , nrep in zip ( S [ : , c ] , nreps ) : freq [ BASES . index ( b ) ] += nrep counts . append ( freq ) return counts
From list of bases at a site D make counts of bases
11,659
def get_left_right ( seq ) : cseq = seq . strip ( GAPS ) leftjust = seq . index ( cseq [ 0 ] ) rightjust = seq . rindex ( cseq [ - 1 ] ) return leftjust , rightjust
Find position of the first and last base
11,660
def cons ( f , mindepth ) : C = ClustFile ( f ) for data in C : names , seqs , nreps = zip ( * data ) total_nreps = sum ( nreps ) if total_nreps < mindepth : continue S = [ ] for name , seq , nrep in data : S . append ( [ seq , nrep ] ) res = stack ( S ) yield [ x [ : 4 ] for x in res if sum ( x [ : 4 ] ) >= mindepth ]
Makes a list of lists of reads at each site
11,661
def estimateHE ( args ) : p = OptionParser ( estimateHE . __doc__ ) add_consensus_options ( p ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) clustSfile , = args HEfile = clustSfile . rsplit ( "." , 1 ) [ 0 ] + ".HE" if not need_update ( clustSfile , HEfile ) : logging . debug ( "File `{0}` found. Computation skipped." . format ( HEfile ) ) return HEfile D = [ ] for d in cons ( clustSfile , opts . mindepth ) : D . extend ( d ) logging . debug ( "Computing base frequencies ..." ) P = makeP ( D ) C = makeC ( D ) logging . debug ( "Solving log-likelihood function ..." ) x0 = [ .01 , .001 ] H , E = scipy . optimize . fmin ( LL , x0 , args = ( P , C ) ) fw = must_open ( HEfile , "w" ) print ( H , E , file = fw ) fw . close ( ) return HEfile
%prog estimateHE clustSfile
11,662
def alignfast ( names , seqs ) : matfile = op . join ( datadir , "blosum80.mat" ) cmd = "poa -read_fasta - -pir stdout {0} -tolower -silent -hb -fuse_all" . format ( matfile ) p = Popen ( cmd , shell = True , stdin = PIPE , stdout = PIPE , stderr = STDOUT , close_fds = True ) s = "" for i , j in zip ( names , seqs ) : s += "\n" . join ( ( i , j ) ) + "\n" return p . communicate ( s ) [ 0 ]
Performs MUSCLE alignments on cluster and returns output as string
11,663
def cluster ( args ) : p = OptionParser ( cluster . __doc__ ) add_consensus_options ( p ) p . set_align ( pctid = 95 ) p . set_outdir ( ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) < 2 : sys . exit ( not p . print_help ( ) ) prefix = args [ 0 ] fastqfiles = args [ 1 : ] cpus = opts . cpus pctid = opts . pctid mindepth = opts . mindepth minlength = opts . minlength fastafile , qualfile = fasta ( fastqfiles + [ "--seqtk" , "--outdir={0}" . format ( opts . outdir ) , "--outfile={0}" . format ( prefix + ".fasta" ) ] ) prefix = op . join ( opts . outdir , prefix ) pf = prefix + ".P{0}" . format ( pctid ) derepfile = prefix + ".derep" if need_update ( fastafile , derepfile ) : derep ( fastafile , derepfile , minlength , cpus ) userfile = pf + ".u" notmatchedfile = pf + ".notmatched" if need_update ( derepfile , userfile ) : cluster_smallmem ( derepfile , userfile , notmatchedfile , minlength , pctid , cpus ) clustfile = pf + ".clust" if need_update ( ( derepfile , userfile , notmatchedfile ) , clustfile ) : makeclust ( derepfile , userfile , notmatchedfile , clustfile , mindepth = mindepth ) clustSfile = pf + ".clustS" if need_update ( clustfile , clustSfile ) : parallel_musclewrap ( clustfile , cpus ) statsfile = pf + ".stats" if need_update ( clustSfile , statsfile ) : makestats ( clustSfile , statsfile , mindepth = mindepth )
%prog cluster prefix fastqfiles
11,664
def align ( args ) : p = OptionParser ( align . __doc__ ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) clustfile , = args parallel_musclewrap ( clustfile , opts . cpus )
%prog align clustfile
11,665
def discrete_rainbow ( N = 7 , cmap = cm . Set1 , usepreset = True , shuffle = False , plot = False ) : import random from scipy import interpolate if usepreset : if 0 < N <= 5 : cmap = cm . gist_rainbow elif N <= 20 : cmap = cm . Set1 else : sys . exit ( discrete_rainbow . __doc__ ) cdict = cmap . _segmentdata . copy ( ) colors_i = np . linspace ( 0 , 1. , N ) indices = np . linspace ( 0 , 1. , N + 1 ) rgbs = [ ] for key in ( 'red' , 'green' , 'blue' ) : D = np . array ( cdict [ key ] ) I = interpolate . interp1d ( D [ : , 0 ] , D [ : , 1 ] ) colors = I ( colors_i ) rgbs . append ( colors ) A = np . zeros ( ( N + 1 , 3 ) , float ) A [ : , 0 ] = indices A [ 1 : , 1 ] = colors A [ : - 1 , 2 ] = colors L = [ ] for l in A : L . append ( tuple ( l ) ) cdict [ key ] = tuple ( L ) palette = zip ( * rgbs ) if shuffle : random . shuffle ( palette ) if plot : print_colors ( palette ) return mpl . colors . LinearSegmentedColormap ( 'colormap' , cdict , 1024 ) , palette
Return a discrete colormap and the set of colors .
11,666
def write_messages ( ax , messages ) : tc = "gray" axt = ax . transAxes yy = .95 for msg in messages : ax . text ( .95 , yy , msg , color = tc , transform = axt , ha = "right" ) yy -= .05
Write text on canvas usually on the top right corner .
11,667
def quickplot ( data , xmin , xmax , xlabel , title , ylabel = "Counts" , figname = "plot.pdf" , counts = True , print_stats = True ) : plt . figure ( 1 , ( 6 , 6 ) ) left , height = zip ( * sorted ( data . items ( ) ) ) pad = max ( height ) * .01 if counts : for l , h in zip ( left , height ) : if xmax and l > xmax : break plt . text ( l , h + pad , str ( h ) , color = "darkslategray" , size = 8 , ha = "center" , va = "bottom" , rotation = 90 ) if xmax is None : xmax = max ( left ) plt . bar ( left , height , align = "center" ) plt . xlabel ( markup ( xlabel ) ) plt . ylabel ( markup ( ylabel ) ) plt . title ( markup ( title ) ) plt . xlim ( ( xmin - .5 , xmax + .5 ) ) messages = [ ] counts_over_xmax = sum ( [ v for k , v in data . items ( ) if k > xmax ] ) if counts_over_xmax : messages += [ "Counts over xmax({0}): {1}" . format ( xmax , counts_over_xmax ) ] kk = [ ] for k , v in data . items ( ) : kk += [ k ] * v messages += [ "Total: {0}" . format ( np . sum ( height ) ) ] messages += [ "Maximum: {0}" . format ( np . max ( kk ) ) ] messages += [ "Minimum: {0}" . format ( np . min ( kk ) ) ] messages += [ "Average: {0:.2f}" . format ( np . mean ( kk ) ) ] messages += [ "Median: {0}" . format ( np . median ( kk ) ) ] ax = plt . gca ( ) if print_stats : write_messages ( ax , messages ) set_human_axis ( ax ) set_ticklabels_helvetica ( ax ) savefig ( figname )
Simple plotting function - given a dictionary of data produce a bar plot with the counts shown on the plot .
11,668
def get_name_parts ( au ) : parts = au . split ( ) first = parts [ 0 ] middle = [ x for x in parts if x [ - 1 ] == '.' ] middle = "" . join ( middle ) last = [ x for x in parts [ 1 : ] if x [ - 1 ] != '.' ] last = " " . join ( last ) initials = "{0}.{1}" . format ( first [ 0 ] , middle ) if first [ - 1 ] == '.' : middle , last = last . split ( None , 1 ) initials = "{0}.{1}." . format ( first [ 0 ] , middle ) return last , first , initials
Fares Z . Najar = > last first initials
11,669
def names ( args ) : p = OptionParser ( names . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( p . print_help ( ) ) namelist , templatefile = args if open ( namelist ) . read ( ) [ 0 ] == '[' : out = parse_names ( namelist ) make_template ( templatefile , out ) return reader = csv . reader ( open ( namelist ) , delimiter = "\t" ) header = next ( reader ) ncols = len ( header ) assert ncols > 3 nextras = ncols - 3 blocks = [ ] bools = [ ] for row in reader : first , middle , last = row [ : 3 ] extras = row [ 3 : ] bools . append ( [ ( x . upper ( ) == 'Y' ) for x in extras ] ) middle = middle . strip ( ) if middle != "" : middle = middle . rstrip ( '.' ) + '.' initials = "{0}.{1}" . format ( first [ 0 ] , middle ) suffix = "" nameblock = NameTemplate . format ( last = last , first = first , initials = initials , suffix = suffix ) blocks . append ( nameblock ) selected_idx = zip ( * bools ) out = [ ] * nextras for i , sbools in enumerate ( selected_idx ) : selected = [ ] for b , ss in zip ( blocks , sbools ) : if ss : selected . append ( b ) bigblock = ",\n" . join ( selected ) out . append ( bigblock ) logging . debug ( "List N{0} contains a total of {1} names." . format ( i , len ( selected ) ) ) make_template ( templatefile , out )
%prog names namelist templatefile
11,670
def main ( ) : p = OptionParser ( main . __doc__ ) p . add_option ( "-g" , "--graphic" , default = False , action = "store_true" , help = "Create boilerplate for a graphic script" ) opts , args = p . parse_args ( ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) script , = args imports = graphic_imports if opts . graphic else default_imports app = graphic_app if opts . graphic else default_app template = default_template . format ( imports , app ) write_file ( script , template ) message = "template writes to `{0}`" . format ( script ) if opts . graphic : message = "graphic " + message message = message [ 0 ] . upper ( ) + message [ 1 : ] logging . debug ( message )
%prog scriptname . py
11,671
def unpack_ambiguous ( s ) : sd = [ ambiguous_dna_values [ x ] for x in s ] return [ "" . join ( x ) for x in list ( product ( * sd ) ) ]
List sequences with ambiguous characters in all possibilities .
11,672
def split ( args ) : p = OptionParser ( split . __doc__ ) p . set_outdir ( outdir = "deconv" ) p . add_option ( "--nocheckprefix" , default = False , action = "store_true" , help = "Don't check shared prefix [default: %default]" ) p . add_option ( "--paired" , default = False , action = "store_true" , help = "Paired-end data [default: %default]" ) p . add_option ( "--append" , default = False , action = "store_true" , help = "Append barcode to 2nd read [default: %default]" ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) < 2 : sys . exit ( not p . print_help ( ) ) barcodefile = args [ 0 ] fastqfile = args [ 1 : ] paired = opts . paired append = opts . append if append : assert paired , "--append only works with --paired" nfiles = len ( fastqfile ) barcodes = [ ] fp = open ( barcodefile ) for row in fp : id , seq = row . split ( ) for s in unpack_ambiguous ( seq ) : barcodes . append ( BarcodeLine . _make ( ( id , s ) ) ) nbc = len ( barcodes ) logging . debug ( "Imported {0} barcodes (ambiguous codes expanded)." . format ( nbc ) ) checkprefix = not opts . nocheckprefix if checkprefix : excludebarcodes = [ ] for bc in barcodes : exclude = [ ] for s in barcodes : if bc . id == s . id : continue assert bc . seq != s . seq if s . seq . startswith ( bc . seq ) and len ( s . seq ) > len ( bc . seq ) : logging . error ( "{0} shares same prefix as {1}." . format ( s , bc ) ) exclude . append ( s ) excludebarcodes . append ( exclude ) else : excludebarcodes = nbc * [ [ ] ] outdir = opts . outdir mkdir ( outdir ) cpus = opts . cpus logging . debug ( "Create a pool of {0} workers." . format ( cpus ) ) pool = Pool ( cpus ) if paired : assert nfiles == 2 , "You asked for --paired, but sent in {0} files" . format ( nfiles ) split_fun = append_barcode_paired if append else split_barcode_paired mode = "paired" else : split_fun = split_barcode mode = "single" logging . debug ( "Mode: {0}" . format ( mode ) ) pool . map ( split_fun , zip ( barcodes , excludebarcodes , nbc * [ outdir ] , nbc * [ fastqfile ] ) )
%prog split barcodefile fastqfile1 ..
11,673
def merge ( args ) : p = OptionParser ( merge . __doc__ ) p . set_outdir ( outdir = "outdir" ) opts , args = p . parse_args ( args ) if len ( args ) < 1 : sys . exit ( not p . print_help ( ) ) folders = args outdir = opts . outdir mkdir ( outdir ) files = flatten ( glob ( "{0}/*.*.fastq" . format ( x ) ) for x in folders ) files = list ( files ) key = lambda x : op . basename ( x ) . split ( "." ) [ 0 ] files . sort ( key = key ) for id , fns in groupby ( files , key = key ) : fns = list ( fns ) outfile = op . join ( outdir , "{0}.fastq" . format ( id ) ) FileMerger ( fns , outfile = outfile ) . merge ( checkexists = True )
%prog merge folder1 ...
11,674
def expand_alleles ( p , tolerance = 0 ) : _p = set ( ) for x in p : _p |= set ( range ( x - tolerance , x + tolerance + 1 ) ) return _p
Returns expanded allele set given the tolerance .
11,675
def get_progenies ( p1 , p2 , x_linked = False , tolerance = 0 ) : _p1 = expand_alleles ( p1 , tolerance = tolerance ) _p2 = expand_alleles ( p2 , tolerance = tolerance ) possible_progenies = set ( tuple ( sorted ( x ) ) for x in product ( _p1 , _p2 ) ) if x_linked : possible_progenies |= set ( ( x , x ) for x in ( set ( _p1 ) | set ( _p2 ) ) ) return possible_progenies
Returns possible progenies in a trio .
11,676
def mendelian_errors2 ( args ) : p = OptionParser ( mendelian_errors2 . __doc__ ) opts , args , iopts = p . set_image_options ( args , figsize = "7x7" , format = "png" ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) csvfile , = args fig , ax = plt . subplots ( ncols = 1 , nrows = 1 , figsize = ( iopts . w , iopts . h ) ) root = fig . add_axes ( [ 0 , 0 , 1 , 1 ] ) ymin = - .2 df = pd . read_csv ( csvfile ) data = [ ] for i , d in df . iterrows ( ) : tred = d [ 'Name' ] motif = d [ 'Motif' ] if tred in ignore : logging . debug ( "Ignore {}" . format ( d [ 'TRED' ] ) ) continue if len ( motif ) > 6 : if "/" in motif : motif = motif . split ( "/" ) [ 0 ] else : motif = motif [ : 6 ] + ".." xtred = "{} {}" . format ( tred , motif ) accuracy = d [ - 1 ] data . append ( ( xtred , accuracy ) ) key = lambda x : float ( x . rstrip ( '%' ) ) data . sort ( key = lambda x : key ( x [ - 1 ] ) ) print ( data ) treds , accuracies = zip ( * data ) ntreds = len ( treds ) ticks = range ( ntreds ) accuracies = [ key ( x ) for x in accuracies ] for tick , accuracy in zip ( ticks , accuracies ) : ax . plot ( [ tick , tick ] , [ ymin , accuracy ] , "-" , lw = 2 , color = 'lightslategray' ) trios , = ax . plot ( accuracies , "o" , mfc = 'w' , mec = 'b' ) ax . set_title ( "Mendelian errors based on STR calls in trios in HLI samples" ) ntrios = "Mendelian errors in 802 trios" ax . legend ( [ trios ] , [ ntrios ] , loc = 'best' ) ax . set_xticks ( ticks ) ax . set_xticklabels ( treds , rotation = 45 , ha = "right" , size = 8 ) ax . set_yticklabels ( [ int ( x ) for x in ax . get_yticks ( ) ] , family = 'Helvetica' ) ax . set_ylabel ( "Mendelian errors (\%)" ) ax . set_ylim ( ymin , 100 ) normalize_axes ( root ) image_name = "mendelian_errors2." + iopts . format savefig ( image_name , dpi = iopts . dpi , iopts = iopts )
%prog mendelian_errors2 Trios . summary . csv
11,677
def mendelian_check ( tp1 , tp2 , tpp , is_xlinked = False ) : call_to_ints = lambda x : tuple ( int ( _ ) for _ in x . split ( "|" ) if _ != "." ) tp1_sex , tp1_call = tp1 [ : 2 ] tp2_sex , tp2_call = tp2 [ : 2 ] tpp_sex , tpp_call = tpp [ : 2 ] tp1_call = call_to_ints ( tp1_call ) tp2_call = call_to_ints ( tp2_call ) tpp_call = call_to_ints ( tpp_call ) possible_progenies = set ( tuple ( sorted ( x ) ) for x in product ( tp1_call , tp2_call ) ) if is_xlinked and tpp_sex == "Male" : possible_progenies = set ( tuple ( ( x , ) ) for x in tp1_call ) if - 1 in tp1_call or - 1 in tp2_call or - 1 in tpp_call : tag = "Missing" else : tag = "Correct" if tpp_call in possible_progenies else "Error" return tag
Compare TRED calls for Parent1 Parent2 and Proband .
11,678
def in_region ( rname , rstart , target_chr , target_start , target_end ) : return ( rname == target_chr ) and ( target_start <= rstart <= target_end )
Quick check if a point is within the target region .
11,679
def mendelian_errors ( args ) : p = OptionParser ( mendelian_errors . __doc__ ) opts , args , iopts = p . set_image_options ( args , figsize = "6x6" ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) csvfile , = args fig , ax = plt . subplots ( ncols = 1 , nrows = 1 , figsize = ( iopts . w , iopts . h ) ) root = fig . add_axes ( [ 0 , 0 , 1 , 1 ] ) ymin = - .2 df = pd . read_csv ( csvfile ) data = [ ] for i , d in df . iterrows ( ) : if d [ 'TRED' ] . split ( ) [ 0 ] in ignore : logging . debug ( "Ignore {}" . format ( d [ 'TRED' ] ) ) continue data . append ( d ) treds , duos , trios = zip ( * data ) ntreds = len ( treds ) ticks = range ( ntreds ) treds = [ x . split ( ) [ 0 ] for x in treds ] duos = [ float ( x . rstrip ( '%' ) ) for x in duos ] trios = [ float ( x . rstrip ( '%' ) ) for x in trios ] for tick , duo , trio in zip ( ticks , duos , trios ) : m = max ( duo , trio ) ax . plot ( [ tick , tick ] , [ ymin , m ] , "-" , lw = 2 , color = 'lightslategray' ) duos , = ax . plot ( duos , "o" , mfc = 'w' , mec = 'g' ) trios , = ax . plot ( trios , "o" , mfc = 'w' , mec = 'b' ) ax . set_title ( "Mendelian errors based on trios and duos in HLI samples" ) nduos = "Mendelian errors in 362 duos" ntrios = "Mendelian errors in 339 trios" ax . legend ( [ trios , duos ] , [ ntrios , nduos ] , loc = 'best' ) ax . set_xticks ( ticks ) ax . set_xticklabels ( treds , rotation = 45 , ha = "right" , size = 8 ) yticklabels = [ int ( x ) for x in ax . get_yticks ( ) ] ax . set_yticklabels ( yticklabels , family = 'Helvetica' ) ax . set_ylabel ( "Mendelian errors (\%)" ) ax . set_ylim ( ymin , 20 ) normalize_axes ( root ) image_name = "mendelian_errors." + iopts . format savefig ( image_name , dpi = iopts . dpi , iopts = iopts )
%prog mendelian_errors STR - Mendelian - errors . csv
11,680
def read_tred_tsv ( tsvfile ) : df = pd . read_csv ( tsvfile , sep = "\t" , index_col = 0 , dtype = { "SampleKey" : str } ) return df
Read the TRED table into a dataframe .
11,681
def mendelian ( args ) : p = OptionParser ( mendelian . __doc__ ) p . add_option ( "--tolerance" , default = 0 , type = "int" , help = "Tolernace for differences" ) p . set_verbose ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) triosjson , tredtsv = args verbose = opts . verbose tolerance = opts . tolerance js = json . load ( open ( triosjson ) ) allterms = set ( ) duos = set ( ) trios = set ( ) for v in js : allterms |= set ( v . keys ( ) ) for trio_or_duo in extract_trios ( v ) : assert len ( trio_or_duo ) in ( 2 , 3 ) if len ( trio_or_duo ) == 2 : duos . add ( trio_or_duo ) else : trios . add ( trio_or_duo ) print ( "A total of {} families imported" . format ( len ( js ) ) ) df = read_tred_tsv ( tredtsv ) ids , treds = read_treds ( ) table = { } for tred , inheritance in zip ( treds [ "abbreviation" ] , treds [ "inheritance" ] ) : x_linked = inheritance [ 0 ] == 'X' name = tred if x_linked : name += " (X-linked)" print ( "[TRED] {}" . format ( name ) ) n_total = len ( duos ) n_error = 0 for duo in duos : n_error += duo . check_mendelian ( df , tred , tolerance = tolerance , x_linked = x_linked , verbose = verbose ) tag = "Duos - Mendelian errors" print ( "{}: {}" . format ( tag , percentage ( n_error , n_total ) ) ) duo_error = percentage ( n_error , n_total , mode = 2 ) table [ ( name , tag ) ] = "{0:.1f}%" . format ( duo_error ) n_total = len ( trios ) n_error = 0 for trio in trios : n_error += trio . check_mendelian ( df , tred , tolerance = tolerance , x_linked = x_linked , verbose = verbose ) tag = "Trios - Mendelian errors" print ( "{}: {}" . format ( tag , percentage ( n_error , n_total ) ) ) trio_error = percentage ( n_error , n_total , mode = 2 ) table [ ( name , tag ) ] = "{0:.1f}%" . format ( trio_error ) print ( tabulate ( table ) )
%prog mendelian trios_candidate . json hli . 20170424 . tred . tsv
11,682
def mini ( args ) : p = OptionParser ( mini . __doc__ ) p . add_option ( "--pad" , default = 20000 , type = "int" , help = "Add padding to the STR reigons" ) p . add_option ( "--treds" , default = None , help = "Extract specific treds, use comma to separate" ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) bamfile , minibam = args treds = opts . treds . split ( "," ) if opts . treds else None pad = opts . pad bedfile = make_STR_bed ( pad = pad , treds = treds ) get_minibam_bed ( bamfile , bedfile , minibam ) logging . debug ( "Mini-BAM written to `{}`" . format ( minibam ) )
%prog mini bamfile minibamfile
11,683
def likelihood2 ( args ) : from matplotlib import gridspec p = OptionParser ( likelihood2 . __doc__ ) opts , args , iopts = p . set_image_options ( args , figsize = "10x5" , style = "white" , cmap = "coolwarm" ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) jsonfile , = args fig = plt . figure ( figsize = ( iopts . w , iopts . h ) ) gs = gridspec . GridSpec ( 2 , 2 ) ax1 = fig . add_subplot ( gs [ : , 0 ] ) ax2 = fig . add_subplot ( gs [ 0 , 1 ] ) ax3 = fig . add_subplot ( gs [ 1 , 1 ] ) plt . tight_layout ( pad = 3 ) pf = plot_panel ( jsonfile , ax1 , ax2 , ax3 , opts . cmap ) root = fig . add_axes ( [ 0 , 0 , 1 , 1 ] ) normalize_axes ( root ) image_name = "likelihood2.{}." . format ( pf ) + iopts . format savefig ( image_name , dpi = iopts . dpi , iopts = iopts )
%prog likelihood2 100_20 . json
11,684
def likelihood3 ( args ) : from matplotlib import gridspec p = OptionParser ( likelihood3 . __doc__ ) opts , args , iopts = p . set_image_options ( args , figsize = "10x10" , style = "white" , cmap = "coolwarm" ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) jsonfile1 , jsonfile2 = args fig = plt . figure ( figsize = ( iopts . w , iopts . h ) ) gs = gridspec . GridSpec ( 9 , 2 ) ax1 = fig . add_subplot ( gs [ : 4 , 0 ] ) ax2 = fig . add_subplot ( gs [ : 2 , 1 ] ) ax3 = fig . add_subplot ( gs [ 2 : 4 , 1 ] ) ax4 = fig . add_subplot ( gs [ 5 : , 0 ] ) ax5 = fig . add_subplot ( gs [ 5 : 7 , 1 ] ) ax6 = fig . add_subplot ( gs [ 7 : , 1 ] ) plt . tight_layout ( pad = 2 ) plot_panel ( jsonfile1 , ax1 , ax2 , ax3 , opts . cmap ) plot_panel ( jsonfile2 , ax4 , ax5 , ax6 , opts . cmap ) root = fig . add_axes ( [ 0 , 0 , 1 , 1 ] ) pad = .02 panel_labels ( root , ( ( pad , 1 - pad , "A" ) , ( pad , 4. / 9 , "B" ) ) ) normalize_axes ( root ) image_name = "likelihood3." + iopts . format savefig ( image_name , dpi = iopts . dpi , iopts = iopts )
%prog likelihood3 140_20 . json 140_70 . json
11,685
def allelefreqall ( args ) : p = OptionParser ( allelefreqall . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) reportfile , = args treds , df = read_treds ( reportfile ) treds = sorted ( treds ) count = 6 pdfs = [ ] for page in xrange ( len ( treds ) / count + 1 ) : start = page * count page_treds = treds [ start : start + count ] if not page_treds : break allelefreq ( [ "," . join ( page_treds ) , "--usereport" , reportfile , "--nopanels" , "--figsize" , "12x16" ] ) outpdf = "allelefreq.{}.pdf" . format ( page ) sh ( "mv allelefreq.pdf {}" . format ( outpdf ) ) pdfs . append ( outpdf ) from jcvi . formats . pdf import cat pf = op . basename ( reportfile ) . split ( "." ) [ 0 ] finalpdf = pf + ".allelefreq.pdf" logging . debug ( "Merging pdfs into `{}`" . format ( finalpdf ) ) cat ( pdfs + [ "-o" , finalpdf , "--cleanup" ] )
%prog allelefreqall HN_Platinum_Gold . 20180525 . tsv . report . txt
11,686
def allelefreq ( args ) : p = OptionParser ( allelefreq . __doc__ ) p . add_option ( "--nopanels" , default = False , action = "store_true" , help = "No panel labels A, B, ..." ) p . add_option ( "--usereport" , help = "Use allele frequency in report file" ) opts , args , iopts = p . set_image_options ( args , figsize = "9x13" ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) loci , = args fig , ( ( ax1 , ax2 ) , ( ax3 , ax4 ) , ( ax5 , ax6 ) ) = plt . subplots ( ncols = 2 , nrows = 3 , figsize = ( iopts . w , iopts . h ) ) plt . tight_layout ( pad = 4 ) if opts . usereport : treds , df = read_treds ( tredsfile = opts . usereport ) else : treds , df = read_treds ( ) df = df . set_index ( [ "abbreviation" ] ) axes = ( ax1 , ax2 , ax3 , ax4 , ax5 , ax6 ) loci = loci . split ( "," ) for ax , locus in zip ( axes , loci ) : plot_allelefreq ( ax , df , locus ) for ax in axes [ len ( loci ) : ] : ax . set_axis_off ( ) root = fig . add_axes ( [ 0 , 0 , 1 , 1 ] ) pad = .03 if not opts . nopanels : panel_labels ( root , ( ( pad / 2 , 1 - pad , "A" ) , ( .5 + pad , 1 - pad , "B" ) , ( pad / 2 , 2 / 3. - pad / 2 , "C" ) , ( .5 + pad , 2 / 3. - pad / 2 , "D" ) , ( pad / 2 , 1 / 3. , "E" ) , ( .5 + pad , 1 / 3. , "F" ) , ) ) normalize_axes ( root ) image_name = "allelefreq." + iopts . format savefig ( image_name , dpi = iopts . dpi , iopts = iopts )
%prog allelefreq HD DM1 SCA1 SCA17 FXTAS FRAXE
11,687
def simulate ( args ) : p = OptionParser ( simulate . __doc__ ) p . add_option ( "--method" , choices = ( "wgsim" , "eagle" ) , default = "eagle" , help = "Read simulator" ) p . add_option ( "--ref" , default = "hg38" , choices = ( "hg38" , "hg19" ) , help = "Reference genome version" ) p . add_option ( "--tred" , default = "HD" , help = "TRED locus" ) add_simulate_options ( p ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) rundir , startunits , endunits = args ref = opts . ref ref_fasta = "/mnt/ref/{}.upper.fa" . format ( ref ) startunits , endunits = int ( startunits ) , int ( endunits ) basecwd = os . getcwd ( ) mkdir ( rundir ) os . chdir ( rundir ) cwd = os . getcwd ( ) pad_left , pad_right = 1000 , 10000 repo = TREDsRepo ( ref = ref ) tred = repo [ opts . tred ] chr , start , end = tred . chr , tred . repeat_start , tred . repeat_end logging . debug ( "Simulating {}" . format ( tred ) ) fasta = Fasta ( ref_fasta ) seq_left = fasta [ chr ] [ start - pad_left : start - 1 ] seq_right = fasta [ chr ] [ end : end + pad_right ] motif = tred . repeat simulate_method = wgsim if opts . method == "wgsim" else eagle for units in range ( startunits , endunits + 1 ) : pf = str ( units ) mkdir ( pf ) os . chdir ( pf ) seq = str ( seq_left ) + motif * units + str ( seq_right ) fastafile = pf + ".fasta" make_fasta ( seq , fastafile , id = chr . upper ( ) ) simulate_method ( [ fastafile , "--depth={}" . format ( opts . depth ) , "--readlen={}" . format ( opts . readlen ) , "--distance={}" . format ( opts . distance ) , "--outfile={}" . format ( pf ) ] ) read1 = pf + ".bwa.read1.fastq" read2 = pf + ".bwa.read2.fastq" samfile , _ = align ( [ ref_fasta , read1 , read2 ] ) indexed_samfile = index ( [ samfile ] ) sh ( "mv {} ../{}.bam" . format ( indexed_samfile , pf ) ) sh ( "mv {}.bai ../{}.bam.bai" . format ( indexed_samfile , pf ) ) os . chdir ( cwd ) shutil . rmtree ( pf ) os . chdir ( basecwd )
%prog simulate run_dir 1 300
11,688
def batchlobstr ( args ) : p = OptionParser ( batchlobstr . __doc__ ) p . add_option ( "--haploid" , default = "chrY,chrM" , help = "Use haploid model for these chromosomes" ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) bamlist , = args cmd = "python -m jcvi.variation.str lobstr TREDs" cmd += " --input_bam_path {}" cmd += " --haploid {}" . format ( opts . haploid ) cmd += " --simulation" cmds = [ cmd . format ( x . strip ( ) ) for x in open ( bamlist ) . readlines ( ) ] p = Parallel ( cmds , cpus = opts . cpus ) p . run ( )
%prog batchlobstr bamlist
11,689
def compilevcf ( args ) : from jcvi . variation . str import LobSTRvcf p = OptionParser ( compilevcf . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) folder , = args vcf_files = iglob ( folder , "*.vcf,*.vcf.gz" ) for vcf_file in vcf_files : try : p = LobSTRvcf ( columnidsfile = None ) p . parse ( vcf_file , filtered = False ) res = p . items ( ) if res : k , v = res [ 0 ] res = v . replace ( ',' , '/' ) else : res = "-1/-1" num = op . basename ( vcf_file ) . split ( "." ) [ 0 ] print ( num , res ) except ( TypeError , AttributeError ) as e : p = TREDPARSEvcf ( vcf_file ) continue
%prog compilevcf dir
11,690
def draw_jointplot ( figname , x , y , data = None , kind = "reg" , color = None , xlim = None , ylim = None , format = "pdf" ) : import seaborn as sns sns . set_context ( 'talk' ) plt . clf ( ) register = { "MeanCoverage" : "Sample Mean Coverage" , "HD.FDP" : "Depth of full spanning reads" , "HD.PDP" : "Depth of partial spanning reads" , "HD.PEDP" : "Depth of paired-end reads" , "HD.2" : "Repeat size of the longer allele" } g = sns . jointplot ( x , y , data = data , kind = kind , color = color , xlim = xlim , ylim = ylim ) g . ax_joint . set_xlabel ( register . get ( x , x ) ) g . ax_joint . set_ylabel ( register . get ( y , y ) ) savefig ( figname + "." + format , cleanup = False )
Wraps around sns . jointplot
11,691
def get_lo_hi_from_CI ( s , exclude = None ) : a , b = s . split ( "|" ) ai , aj = a . split ( "-" ) bi , bj = b . split ( "-" ) los = [ int ( ai ) , int ( bi ) ] his = [ int ( aj ) , int ( bj ) ] if exclude and exclude in los : los . remove ( exclude ) if exclude and exclude in his : his . remove ( exclude ) return max ( los ) , max ( his )
Parse the confidence interval from CI .
11,692
def compare ( args ) : p = OptionParser ( compare . __doc__ ) opts , args , iopts = p . set_image_options ( args , figsize = "10x10" ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) datafile , = args pf = datafile . rsplit ( "." , 1 ) [ 0 ] fig , ( ( ax1 , ax2 ) , ( ax3 , ax4 ) ) = plt . subplots ( ncols = 2 , nrows = 2 , figsize = ( iopts . w , iopts . h ) ) plt . tight_layout ( pad = 3 ) bbox = { 'facecolor' : 'tomato' , 'alpha' : .2 , 'ec' : 'w' } pad = 2 df = pd . read_csv ( "Evaluation.csv" ) truth = df [ "Truth" ] axes = ( ax1 , ax2 , ax3 , ax4 ) progs = ( "Manta" , "Isaac" , "GATK" , "lobSTR" ) markers = ( "bx-" , "yo-" , "md-" , "c+-" ) for ax , prog , marker in zip ( axes , progs , markers ) : ax . plot ( truth , df [ prog ] , marker ) ax . plot ( truth , truth , 'k--' ) ax . axhline ( infected_thr , color = 'tomato' ) ax . text ( max ( truth ) - pad , infected_thr + pad , 'Risk threshold' , bbox = bbox , ha = "right" ) ax . axhline ( ref_thr , color = 'tomato' ) ax . text ( max ( truth ) - pad , ref_thr - pad , 'Reference repeat count' , bbox = bbox , ha = "right" , va = "top" ) ax . set_title ( SIMULATED_HAPLOID ) ax . set_xlabel ( r'Num of CAG repeats inserted ($\mathit{h}$)' ) ax . set_ylabel ( 'Num of CAG repeats called' ) ax . legend ( [ prog , 'Truth' ] , loc = 'best' ) root = fig . add_axes ( [ 0 , 0 , 1 , 1 ] ) pad = .03 panel_labels ( root , ( ( pad / 2 , 1 - pad , "A" ) , ( 1 / 2. , 1 - pad , "B" ) , ( pad / 2 , 1 / 2. , "C" ) , ( 1 / 2. , 1 / 2. , "D" ) ) ) normalize_axes ( root ) image_name = pf + "." + iopts . format savefig ( image_name , dpi = iopts . dpi , iopts = iopts )
%prog compare Evaluation . csv
11,693
def stem_leaf_plot ( data , vmin , vmax , bins , digit = 1 , title = None ) : assert bins > 0 range = vmax - vmin step = range * 1. / bins if isinstance ( range , int ) : step = int ( ceil ( step ) ) step = step or 1 bins = np . arange ( vmin , vmax + step , step ) hist , bin_edges = np . histogram ( data , bins = bins ) bin_edges = bin_edges [ : len ( hist ) ] asciiplot ( bin_edges , hist , digit = digit , title = title ) print ( "Last bin ends in {0}, inclusive." . format ( vmax ) , file = sys . stderr ) return bin_edges , hist
Generate stem and leaf plot given a collection of numbers
11,694
def prepare ( args ) : valid_enzymes = "ApeKI|ApoI|BamHI|EcoT22I|HinP1I|HpaII|MseI|MspI|" "NdeI|PasI|PstI|Sau3AI|SbfI|AsiSI-MspI|BssHII-MspI|" "FseI-MspI|PaeR7I-HhaI|PstI-ApeKI|PstI-EcoT22I|PstI-MspI" "PstI-TaqI|SalI-MspI|SbfI-MspI" . split ( "|" ) p = OptionParser ( prepare . __doc__ ) p . add_option ( "--enzyme" , default = "ApeKI" , choices = valid_enzymes , help = "Restriction enzyme used [default: %default]" ) p . set_home ( "tassel" ) p . set_aligner ( aligner = "bwa" ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) barcode , reference = args thome = opts . tassel_home reference = get_abs_path ( reference ) folders = ( "fastq" , "tagCounts" , "mergedTagCounts" , "topm" , "tbt" , "mergedTBT" , "hapmap" , "hapmap/raw" , "hapmap/mergedSNPs" , "hapmap/filt" , "hapmap/bpec" ) for f in folders : mkdir ( f ) runsh = [ ] o = "-i fastq -k {0} -e {1} -o tagCounts" . format ( barcode , opts . enzyme ) cmd = run_pipeline ( thome , "FastqToTagCountPlugin" , o ) runsh . append ( cmd ) o = "-i tagCounts -o mergedTagCounts/myMasterTags.cnt" o += " -c 5 -t mergedTagCounts/myMasterTags.cnt.fq" cmd = run_pipeline ( thome , "MergeMultipleTagCountPlugin" , o ) runsh . append ( cmd ) runsh . append ( "cd mergedTagCounts" ) cmd = "python -m jcvi.apps.{0} align --cpus {1}" . format ( opts . aligner , opts . cpus ) cmd += " {0} myMasterTags.cnt.fq" . format ( reference ) runsh . append ( cmd ) runsh . append ( "cd .." ) o = "-i mergedTagCounts/*.sam -o topm/myMasterTags.topm" cmd = run_pipeline ( thome , "SAMConverterPlugin" , o ) runsh . append ( cmd ) o = "-i mergedTBT/myStudy.tbt.byte -y -m topm/myMasterTags.topm" o += " -mUpd topm/myMasterTagsWithVariants.topm" o += " -o hapmap/raw/myGBSGenos_chr+.hmp.txt" o += " -mnF 0.8 -p myPedigreeFile.ped -mnMAF 0.02 -mnMAC 100000" o += " -ref {0} -sC 1 -eC 10" . format ( reference ) cmd = run_pipeline ( thome , "TagsToSNPByAlignmentPlugin" , o ) runsh . append ( cmd ) o = "-hmp hapmap/raw/myGBSGenos_chr+.hmp.txt" o += " -o hapmap/mergedSNPs/myGBSGenos_mergedSNPs_chr+.hmp.txt" o += " -misMat 0.1 -p myPedigreeFile.ped -callHets -sC 1 -eC 10" cmd = run_pipeline ( thome , "MergeDuplicateSNPsPlugin" , o ) runsh . append ( cmd ) o = "-hmp hapmap/mergedSNPs/myGBSGenos_mergedSNPs_chr+.hmp.txt" o += " -o hapmap/filt/myGBSGenos_mergedSNPsFilt_chr+.hmp.txt" o += " -mnTCov 0.01 -mnSCov 0.2 -mnMAF 0.01 -sC 1 -eC 10" cmd = run_pipeline ( thome , "GBSHapMapFiltersPlugin" , o ) runsh . append ( cmd ) runfile = "run.sh" write_file ( runfile , "\n" . join ( runsh ) )
%prog prepare barcode_key . csv reference . fasta
11,695
def batch ( args ) : p = OptionParser ( batch . __doc__ ) set_align_options ( p ) p . set_sam_options ( ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) ref_fasta , proj_dir , outdir = args outdir = outdir . rstrip ( "/" ) s3dir = None if outdir . startswith ( "s3://" ) : s3dir = outdir outdir = op . basename ( outdir ) mkdir ( outdir ) mm = MakeManager ( ) for p , pf in iter_project ( proj_dir ) : targs = [ ref_fasta ] + p cmd1 , bamfile = mem ( targs , opts ) if cmd1 : cmd1 = output_bam ( cmd1 , bamfile ) nbamfile = op . join ( outdir , bamfile ) cmd2 = "mv {} {}" . format ( bamfile , nbamfile ) cmds = [ cmd1 , cmd2 ] if s3dir : cmd = "aws s3 cp {} {} --sse" . format ( nbamfile , op . join ( s3dir , bamfile ) ) cmds . append ( cmd ) mm . add ( p , nbamfile , cmds ) mm . write ( )
%proj batch database . fasta project_dir output_dir
11,696
def index ( args ) : p = OptionParser ( index . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) dbfile , = args check_index ( dbfile )
%prog index database . fasta
11,697
def samse ( args , opts ) : dbfile , readfile = args dbfile = check_index ( dbfile ) saifile = check_aln ( dbfile , readfile , cpus = opts . cpus ) samfile , _ , unmapped = get_samfile ( readfile , dbfile , bam = opts . bam , unmapped = opts . unmapped ) if not need_update ( ( dbfile , saifile ) , samfile ) : logging . error ( "`{0}` exists. `bwa samse` already run." . format ( samfile ) ) return "" , samfile cmd = "bwa samse {0} {1} {2}" . format ( dbfile , saifile , readfile ) cmd += " " + opts . extra if opts . uniq : cmd += " -n 1" return cmd , samfile
%prog samse database . fasta short_read . fastq
11,698
def sampe ( args , opts ) : dbfile , read1file , read2file = args dbfile = check_index ( dbfile ) sai1file = check_aln ( dbfile , read1file , cpus = opts . cpus ) sai2file = check_aln ( dbfile , read2file , cpus = opts . cpus ) samfile , _ , unmapped = get_samfile ( read1file , dbfile , bam = opts . bam , unmapped = opts . unmapped ) if not need_update ( ( dbfile , sai1file , sai2file ) , samfile ) : logging . error ( "`{0}` exists. `bwa samse` already run." . format ( samfile ) ) return "" , samfile cmd = "bwa sampe " + " " . join ( ( dbfile , sai1file , sai2file , read1file , read2file ) ) cmd += " " + opts . extra if opts . cutoff : cmd += " -a {0}" . format ( opts . cutoff ) if opts . uniq : cmd += " -n 1" return cmd , samfile
%prog sampe database . fasta read1 . fq read2 . fq
11,699
def bwasw ( args , opts ) : dbfile , readfile = args dbfile = check_index ( dbfile ) samfile , _ , unmapped = get_samfile ( readfile , dbfile , bam = opts . bam , unmapped = opts . unmapped ) if not need_update ( dbfile , samfile ) : logging . error ( "`{0}` exists. `bwa bwasw` already run." . format ( samfile ) ) return "" , samfile cmd = "bwa bwasw " + " " . join ( args ) cmd += " -t {0}" . format ( opts . cpus ) cmd += " " + opts . extra return cmd , samfile
%prog bwasw database . fasta long_read . fastq