diff adjust_bracken_for_unclassified_reads.py @ 2:87459bd1615a draft

planemo upload for repository https://github.com/public-health-bioinformatics/galaxy_tools/blob/master/tools/adjust_bracken_for_unclassified_reads commit 4ebe8216c423e2d66be92247f273df21cb5852f1
author public-health-bioinformatics
date Thu, 27 Oct 2022 00:37:27 +0000
parents 3ab9d37e547e
children
line wrap: on
line diff
--- a/adjust_bracken_for_unclassified_reads.py	Thu Mar 10 21:39:43 2022 +0000
+++ b/adjust_bracken_for_unclassified_reads.py	Thu Oct 27 00:37:27 2022 +0000
@@ -43,23 +43,14 @@
     kraken_report = parse_kraken_report(args.kraken_report)
     bracken_abundances = parse_bracken_abundances(args.bracken_abundances)
 
-    kraken_report_unclassified_seqs = list(filter(lambda x: x['taxon_name'] == 'unclassified', kraken_report))[0]['seqs_this_level']
+    try:
+        kraken_report_unclassified_seqs = list(filter(lambda x: x['taxon_name'] == 'unclassified', kraken_report))[0]['seqs_this_level']
+    except IndexError as e:
+        kraken_report_unclassified_seqs = 0
     kraken_report_classified_seqs = list(filter(lambda x: x['taxon_name'] == 'root', kraken_report))[0]['seqs_total']
 
     total_seqs = kraken_report_classified_seqs + kraken_report_unclassified_seqs
-    percent_unclassified = float(kraken_report_unclassified_seqs) / float(total_seqs)
-
-    bracken_unclassified_entry = {
-        'name': 'unclassified',
-        'taxonomy_id': 0,
-        'taxonomy_lvl': 'U',
-        'kraken_assigned_seqs': kraken_report_unclassified_seqs,
-        'bracken_assigned_seqs': kraken_report_unclassified_seqs,
-        'kraken_fraction_total_seqs': percent_unclassified,
-        'bracken_fraction_total_seqs': 0.0,
-    }
-
-    bracken_abundances = [bracken_unclassified_entry] + bracken_abundances
+    fraction_unclassified = float(kraken_report_unclassified_seqs) / float(total_seqs)
 
     output_fieldnames = [
         'name',
@@ -82,7 +73,20 @@
         bracken_adjusted_fraction_total_seqs = float(b['bracken_assigned_seqs']) / float(total_seqs)
         b['bracken_fraction_total_seqs'] = '{:.6f}'.format(bracken_adjusted_fraction_total_seqs)
 
-    for b in sorted(bracken_abundances, key=lambda x: x['bracken_fraction_total_seqs'], reverse=True):
+    bracken_unclassified_entry = {
+        'name': 'unclassified',
+        'taxonomy_id': 0,
+        'taxonomy_lvl': 'U',
+        'kraken_assigned_seqs': kraken_report_unclassified_seqs,
+        'bracken_assigned_seqs': kraken_report_unclassified_seqs,
+        'total_seqs': total_seqs,
+        'kraken_fraction_total_seqs': '{:.6f}'.format(fraction_unclassified),
+        'bracken_fraction_total_seqs': '{:.6f}'.format(fraction_unclassified),
+    }
+    
+    bracken_abundances = sorted(bracken_abundances, key=lambda x: x['bracken_fraction_total_seqs'], reverse=True)
+    bracken_abundances = [bracken_unclassified_entry] + bracken_abundances
+    for b in bracken_abundances:
         writer.writerow(b)