<s> '''<STR_LIT>''' <EOL> import sys <EOL> import os <EOL> from ngsutils . bed import BedFile <EOL> from ngsutils . support import revcomp <EOL> import pysam <EOL> def bed_tofasta ( bed , ref_fasta , min_size = <NUM_LIT:50> , stranded = True , include_name = False , out = sys . stdout ) : <EOL> if not os . path . exists ( '<STR_LIT>' % ref_fasta ) : <EOL> pysam . faidx ( ref_fasta ) <EOL> fasta = pysam . Fastafile ( ref_fasta ) <EOL> refs = set ( ) <EOL> with open ( '<STR_LIT>' % ref_fasta ) as f : <EOL> for line in f : <EOL> refs . add ( line . split ( '<STR_LIT:\t>' ) [ <NUM_LIT:0> ] . strip ( ) ) <EOL> name = '<STR_LIT>' <EOL> for region in bed : <EOL> if include_name : <EOL> name = '<STR_LIT>' % ( region . name . strip ( ) ) <EOL> if region . end - region . start >= min_size and region . chrom in refs : <EOL> seq = fasta . fetch ( region . chrom , region . start , region . end ) <EOL> if stranded and region . strand : <EOL> if region . strand == '<STR_LIT:->' : <EOL> seq = revcomp ( seq ) <EOL> out . write ( '<STR_LIT>' % ( name , region . chrom , region . start , region . end , region . strand , seq ) ) <EOL> else : <EOL> out . write ( '<STR_LIT>' % ( name , region . chrom , region . start , region . end , seq ) ) <EOL> fasta . close ( ) <EOL> def usage ( ) : <EOL> print __doc__ <EOL> print """<STR_LIT>""" <EOL> if __name__ == "<STR_LIT:__main__>" : <EOL> min_size = <NUM_LIT:50> <EOL> bed = None <EOL> ref = None <EOL> stranded = True <EOL> include_name = False <EOL> last = None <EOL> for arg in sys . argv [ <NUM_LIT:1> : ] : <EOL> if last == '<STR_LIT>' : <EOL> min_size = int ( arg ) <EOL> last = None <EOL> elif arg in [ '<STR_LIT>' ] : <EOL> last = arg <EOL> elif arg == '<STR_LIT>' : <EOL> include_name = True <EOL> elif arg == '<STR_LIT>' : <EOL> stranded = False <EOL> elif not bed and os . path . exists ( arg ) : <EOL> bed = arg <EOL> elif not ref and os . path . exists ( arg ) : <EOL> ref = arg <EOL> if not bed or not ref : <EOL> usage ( ) <EOL> sys . exit ( <NUM_LIT:1> ) <EOL> bed_tofasta ( BedFile ( bed ) , ref , min_size = min_size , stranded = stranded , include_name = include_name ) </s>
