Commits

Davide Cittaro  committed 922beab

list samples to sm

  • Participants
  • Parent commits f4cdaa5

Comments (0)

Files changed (1)

File extract_sm.py

 samples = []
 extract_by_rg = False
 extract_prefix = "extract_"
+list_samples = False
 
-(opts, args) = getopt.getopt(sys.argv[1:], 'f:rp:')
+(opts, args) = getopt.getopt(sys.argv[1:], 'f:rp:l')
 for o, a in opts:
   if o == '-f':
     bam_file = a
     extract_by_rg = True  
   if o == '-p':
     extract_prefix = a
+  if o == '-l':
+    list_samples = True  
 
 if not bam_file or not os.path.exists(bam_file):
   sys.stderr.write("Please, provide a BAM file\n")
 sample2fo = {}
 
 bamh = pysam.Samfile(bam_file, 'rb')
+
+if list_samples:
+  for rg in bamh.header['RG']:
+    sys.stdout.write("Sample: %s\tRead Group: %s\n" % (rg['SM'], rg['ID']))
+  sys.exit(0)
+  
 for rg in bamh.header['RG']:
   if len(samples) == 0:
     # create one file for each
   sys.exit(1)
 
 for sm in tokeep.keys():
-  fname = extract_prefix + sn + '.bam'
+  fname = extract_prefix + sm + '.bam'
   header = bamh.header
   if extract_by_rg:
     rh = [x for x in header['RG'] if x['RG'] == sm]
 
 for r in bamh.fetch():
   rg = [x[1] for x in r.tags if x[0] == 'RG'][0]
-  sm = rg2sm[rg]
-  sample2fo[sm].write(r)
+  try:
+    sm = rg2sm[rg]
+    sample2fo[sm].write(r)
+  except KeyError:
+    continue  
   
 for sm in sample2fo.keys():
   sample2fo[sm].close()