Debian Codegraph @

pycoQC/Barcode_split.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~IMPORTS~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
4
5 # Standard library imports
6 from collections import *
7 import warnings
8 import datetime
9 import os
10
11 # Third party imports
12 import pandas as pd
13
14 # Local lib import
15 from pycoQC import __name__ as package_name
16 from pycoQC import __version__ as package_version
17 from pycoQC.common import *
18 from pycoQC.pycoQC_parse import pycoQC_parse
19
20 #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~GLOBAL SETTINGS~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
21
22 # Silence futurewarnings
23 warnings.filterwarnings("ignore", category=FutureWarning)
24
25 #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~MAIN CLASS~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
26 def Barcode_split (
27 summary_file:str,
28 barcode_file:str="",
29 output_dir:str="",
30 output_unclassified:bool=False,
31 min_barcode_percent:float=0.1,
32 verbose:bool=False,
33 quiet:bool=False):
34 """
35 Parse Albacore sequencing_summary.txt file and split per barcode
36 By default, data for low frequency barcodes and unclassified reads are not written in the output directory
37 * summary_file
38 Path to a sequencing_summary generated by Albacore 1.0.0 + (read_fast5_basecaller.py) / Guppy 2.1.3+ (guppy_basecaller).
39 One can also pass multiple space separated file paths or a UNIX style regex matching multiple files
40 * barcode_file
41 Path to the barcode_file generated by Guppy 2.1.3+ (guppy_barcoder) or Deepbinner 0.2.0+. This is not a required file.
42 One can also pass multiple space separated file paths or a UNIX style regex matching multiple files
43 * output_dir
44 Folder where to output split barcode data
45 * output_unclassified
46 If True unclassified barcodes are also written in a file. By default they are skiped
47 * min_barcode_percent
48 Minimal percent of total reads to write barcode reads in file.
49 * verbose
50 Increase verbosity
51 * quiet
52 Reduce verbosity
53 """
54
55 # Save args and init options in dict for report
56 options_d = locals()
57 info_d = {"package_name":package_name, "package_version":package_version, "timestamp":str(datetime.datetime.now())}
58
59 # Set logging level
60 logger = get_logger (name=__name__, verbose=verbose, quiet=quiet)
61
62 # Print debug info
63 logger.debug("General info")
64 logger.debug(dict_to_str(info_d))
65 logger.debug("Runtime options")
66 logger.debug(dict_to_str(options_d))
67
68 # Process data
69 logger.warning ("Import data from sequencing summary file(s) and cleanup")
70 logger.info ("\tRead files and import in a dataframe")
71 pps = pycoQC_parse(summary_file=summary_file, barcode_file=barcode_file, cleanup=False, verbose=verbose, quiet=quiet)
72 df = pps.reads_df
73
74 # Rename barcode field and check if present
75 df = df.rename(columns={"barcode_arrangement":"barcode"})
76 if not "barcode" in df:
77 raise pycoQCError ("No barcode information found in provided file(s)")
78
79 # Quick data cleanup
80 logger.info ("\tCleanup missing barcodes values")
81 df = df.fillna({"barcode":"unclassified"})
82
83 # List barcode with low frequency
84 if min_barcode_percent:
85 logger.info ("\tCleaning up low frequency barcodes")
86 barcode_counts = df["barcode"][df["barcode"]!="unclassified"].value_counts()
87 cutoff = int(barcode_counts.sum()*min_barcode_percent/100)
88 low_barcode = barcode_counts[barcode_counts<cutoff].index
89 # df.loc[df["barcode"].isin(low_barcode), "barcode"] = "unclassified"
90
91 bc = namedtuple ("bc", ["Counts", "Write"])
92 bc_l = OrderedDict()
93
94 logger.warning ("Split data per barcode")
95 for barcode, barcode_df in df.groupby("barcode"):
96 logger.info ("\tProcessing data for Barcode {}".format(barcode))
97
98 # Skip unclassified if required
99 if not output_unclassified and barcode == "unclassified":
100 bc_l[barcode] = bc(len(barcode_df), False)
101
102 # Skip low frequency if required
103 elif min_barcode_percent and barcode in low_barcode:
104 bc_l[barcode] = bc(len(barcode_df), False)
105
106 # Cleanup and write barcode to file
107 else:
108 bc_l[barcode] = bc(len(barcode_df), True)
109 # Remove any field containing barcode in it
110 barcode_df = barcode_df[[i for i in df.columns if not i.startswith("barcode")]]
111 # Write to file
112 file_name = os.path.join(output_dir, "sequencing_summary_{}.txt".format(barcode))
113 barcode_df.to_csv(file_name, sep="\t", index=False)
114
115 logger.info("Barcode Counts")
116 bc_df = pd.DataFrame.from_dict(bc_l, orient="index")
117 logger.info(bc_df)