rs_subreads.py 18.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#
# Copyright (C) 2012 INRA
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#


import os
import json
Gerald Salin's avatar
Gerald Salin committed
21
import logging
22

23
from workflows.pacbio_qc.lib.pacbiolib import h5file
24
25
26
27
28

from ng6.analysis import Analysis

from weaver.function import PythonFunction

Claire Kuchly's avatar
Claire Kuchly committed
29
def rs_subreads(inputfile, stdout, componentdir, smrtpipe, fofnToSmrtpipeInput, min_subreads_length, polymerase_read_qual, polymerase_read_length, barcode_file, barcode_score ):
30
31
32
    
    import subprocess
    import os
Gerald Salin's avatar
Gerald Salin committed
33
    import logging
34
35
    
    from workflows.pacbio_qc.lib.pacbiolib import PacbioH5Reader
Gerald Salin's avatar
Gerald Salin committed
36
37
    logging.getLogger("jflow").debug("Begin rs_subreads!")
    # create directory
38
39
40
41
42
43
44
45
46
    filebase = os.path.basename(os.path.splitext(os.path.splitext(inputfile)[0])[0])
    outputdir = os.path.join(componentdir, filebase)
    settings_xml = os.path.join(componentdir, filebase + "_settings.xml" )
    inputs_fofn = os.path.join(componentdir, filebase + "_inputs.fofn" )
    inputs_xml = os.path.join(componentdir, filebase + "_inputs.xml" )
    
    if not os.path.exists(outputdir) :
        subprocess.check_call("mkdir %s >> %s"%(outputdir, stdout), shell=True)
    
Claire Kuchly's avatar
Claire Kuchly committed
47
48
49
50
51
52
53
54
55
56
    barcode_string=""
    if barcode_file != None :
        barcode_string="""
    <module id="P_Barcode">
        <param name='mode'><value>symmetric</value></param>
        <param name='barcode.fasta'>
            <value>{0}</value>
        </param>
        <param name='score'><value>{1}</value></param>
    </module>""".format(barcode_file, barcode_score)
Gerald Salin's avatar
Gerald Salin committed
57
58
59
        # write settings
        with open( settings_xml, "w") as fh:
            fh.write(("""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<smrtpipeSettings>
    <module id="P_Fetch" />
    <module id="P_Filter" >
        <param name="minSubReadLength">
            <value>{0}</value>
        </param>
        <param name="readScore">
            <value>{1}</value>
        </param>
        <param name="minLength">
            <value>{2}</value>
        </param>
    </module>
    <module id="P_FilterReports"/>
Claire Kuchly's avatar
Claire Kuchly committed
74
    """+barcode_string+"""
75
</smrtpipeSettings>
Claire Kuchly's avatar
Claire Kuchly committed
76
    """).format(min_subreads_length, polymerase_read_qual, polymerase_read_length))
77

Gerald Salin's avatar
Gerald Salin committed
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
    if barcode_file == 'None' or barcode_file is None :
        # write settings
        with open( settings_xml, "w") as fh:
            fh.write(("""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<smrtpipeSettings>
    <module id="P_Fetch" />
    <module id="P_Filter" >
        <param name="minSubReadLength">
            <value>{0}</value>
        </param>
        <param name="readScore">
            <value>{1}</value>
        </param>
        <param name="minLength">
            <value>{2}</value>
        </param>
    </module>
    <module id="P_FilterReports"/>
</smrtpipeSettings>
    """).format(min_subreads_length, polymerase_read_qual, polymerase_read_length))

99
100
101
102
103
104
105
106
107
108
109
    # write fofn and xml
    reader = PacbioH5Reader(inputfile)
    with open( inputs_fofn, "w") as fh:
        for baxh5 in reader.bash5.parts :
            fh.write(baxh5.filename + "\n")
    
    subprocess.check_call("%s %s > %s"%(fofnToSmrtpipeInput, inputs_fofn, inputs_xml), shell = True)
    
    # run smrtpipe
    subprocess.check_call("%s --output=%s --params=%s  xml:%s >> %s"%(smrtpipe, outputdir, settings_xml, inputs_xml,stdout), shell = True)

Penom Nom's avatar
Penom Nom committed
110
111
112
113
114
115
116
117
118
119
120
121
122

def extract_metrics(inputfile):
    import h5py
    import os
    
    from workflows.pacbio_qc.lib.pacbiolib import PacbioH5Reader
    
    reader = PacbioH5Reader(inputfile)
    for baxh5 in reader.bash5.parts :
        h5 = h5py.File(baxh5,'r')
        metrics = h5['PulseData']['BaseCalls']['ZMWMetrics'] 
    

123
124
125
126
127
128
class RS_Subreads (Analysis):
    """
        implementation of pacbio RS_Subreads.1 protocol
        This module filters reads based on a minimum subread length, polymerase read quality and polymerase read length
    """
    
Claire Kuchly's avatar
Claire Kuchly committed
129
    def define_parameters(self, sample_names, input_files, min_subreads_length = 0, polymerase_read_qual = 0, polymerase_read_length = 0, barcode_file=None, barcode_score=22):
Gerald Salin's avatar
Gerald Salin committed
130
        logging.getLogger("jflow").debug("Begin RS_Subreads.define_parameters!")
Penom Nom's avatar
Penom Nom committed
131
        self.add_parameter_list("sample_names", "sample names, each sample name must correspond to an input file", default=sample_names, required=True)
132
        self.add_input_file_list( "input_files", "Input pacbio bas.h5 files", default=input_files, file_format = h5file, required=True)
133
134
135
        self.add_parameter("min_subreads_length", "Subreads shorter than this value (in base pairs) are filtered out and excluded from analysis", default=min_subreads_length, type='int')
        self.add_parameter("polymerase_read_qual", "Polymerase reads with lower quality than this value are filtered out and excluded from analysis", default=polymerase_read_qual, type='float')
        self.add_parameter("polymerase_read_length", "Polymerase reads shorter than this value (in base pairs) are filtered out and excluded from analysis", default=polymerase_read_length, type='int')
Claire Kuchly's avatar
Claire Kuchly committed
136
137
138
        
        self.add_input_file( "barcode_file", "Input barcode file", default=barcode_file)
        self.add_parameter("barcode_score", "Min identical base for barcode", default=barcode_score, type='int')
139
140
141
142
143

        items = [os.path.basename(os.path.splitext(os.path.splitext(filename)[0])[0]) for filename in self.input_files]
        self.add_output_file_list( 'stdouts', "logs", pattern="{basename}.stdout", items=items)

    def process(self):
Gerald Salin's avatar
Gerald Salin committed
144
        logging.getLogger("jflow").debug("Begin RS_Subreads.process!")
Claire Kuchly's avatar
Claire Kuchly committed
145
        subreads = PythonFunction(rs_subreads, cmd_format="{EXE} {IN} {OUT} {ARG}")
146
        for i,e in  enumerate(self.input_files) :
Gerald Salin's avatar
Gerald Salin committed
147
148
149
150
151
152
153
154
155
156
            logging.getLogger("jflow").debug("Begin RS_Subreads.process! " + e)
            print('START FOR ',i,'------>',e)
            '''self.add_python_execution(rs_subreads, 
                cmd_format="{EXE} {IN} {OUT} {ARG}",
                map=False,
                inputs = [self.input_files[i]],
                outputs = [self.stdouts[i]],
                arguments = [self.output_directory, self.get_exec_path("smrtpipe"), self.get_exec_path("fofnToSmrtpipeInput.py"), self.min_subreads_length, self.polymerase_read_qual, self.polymerase_read_length, self.barcode_file, self.barcode_score]
                )'''

157
158
159
            subreads(inputs = self.input_files[i],
                     outputs = [self.stdouts[i]],
                     arguments = [self.output_directory, self.get_exec_path("smrtpipe"), self.get_exec_path("fofnToSmrtpipeInput.py"),
Claire Kuchly's avatar
Claire Kuchly committed
160
                                  self.min_subreads_length, self.polymerase_read_qual, self.polymerase_read_length, self.barcode_file, self.barcode_score ])
Gerald Salin's avatar
Gerald Salin committed
161
162
        logging.getLogger("jflow").debug("End RS_Subreads.process! ")
        print('END PROCESS')
163
164
165
166
167
168
169
170
171
172
173
174
        
    def get_version(self):
        return "1.0"
        
    def define_analysis(self):
        self.name = "RS_Subreads"
        self.description = "Run SMRTAnalysis RS_Subreads.1"
        self.software = "Python"
        self.options = "minSubReadLength %s readScore %s  minLength %s"%(self.min_subreads_length, self.polymerase_read_qual, self.polymerase_read_length)
    
    def post_process(self):
        metrics = []
Gerald Salin's avatar
Gerald Salin committed
175
        metrics2 = []
176
177
        
        for i,samplefile in enumerate(self.input_files) :
Penom Nom's avatar
Penom Nom committed
178
179
180
            sample = self.sample_names[i]
            sdir = os.path.basename(os.path.splitext(os.path.splitext(samplefile)[0])[0])
            sample_outdir = os.path.join(self.output_directory, sdir)
Gerald Salin's avatar
Gerald Salin committed
181
182
183
            '''print ('sample ------->  ',sample,'\n')
            print ('self.sample_names ------->  ',self.sample_names,'\n')'''

184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
            
            # loading 
            jsonfile = os.path.join(sample_outdir, 'results', 'filter_reports_loading.json')
            if os.path.isfile(jsonfile):
                group = 'loading'
                if group not in metrics : 
                    metrics.append(group)
                    self._add_result_element("metrics", "headers", ','.join(['Productive ZMWs', 'Productivity 0', 'Productivity 1', 'Productivity 2']), group)
                stats = self.parse_loading_json(jsonfile)
                self._add_result_element(sample, 'Productive ZMWs', stats['Productive ZMWs'] , group)
                self._add_result_element(sample, 'Productivity 0', stats['Productivity 0'] , group)
                self._add_result_element(sample, 'Productivity 1', stats['Productivity 1'] , group)
                self._add_result_element(sample, 'Productivity 2', stats['Productivity 2'] , group)
            
            # adapters
            jsonfile = os.path.join(sample_outdir, 'results', 'filter_reports_adapters.json')
            if os.path.isfile(jsonfile):
                group = 'adapter_stats'
                if group not in metrics : 
                    metrics.append(group)
                    self._add_result_element("metrics", "headers", ','.join(['Adapter Dimers', 'Medium Inserts', 'Short Inserts', "insert"]), group)
                stats = self.parse_adapter_json(jsonfile)
                self._add_result_element(sample, 'Adapter Dimers', stats['Adapter Dimers'] , group)
                self._add_result_element(sample, 'Medium Inserts', stats['Medium Inserts'] , group)
                self._add_result_element(sample, 'Short Inserts', stats['Short Inserts'] , group)
                image = os.path.join(sample_outdir, 'results', 'adapter_observed_insert_length_distribution.png')
                self._add_result_element(sample, "insert", self._save_file(image, sample + ".adapter_observed_insert_length_distribution.png"), group)
            
            # filter stats
            jsonfile = os.path.join(sample_outdir, 'results', 'filter_reports_filter_stats.json')
            if os.path.isfile(jsonfile):
                stats = self.parse_filter_json(jsonfile)
                
                groups = ['prefilter_stats', 'postfilter_stats']
                for group in groups :
                    if group not in metrics : 
                        metrics.append(group)
                        self._add_result_element("metrics", "headers", ','.join(['Mean Read Score', 'Number of Reads', 'Number of Bases', 
                                                                                 'N50', 'Mean Read Length', 'readlen', 'readscore']), group)
                    self._add_result_element(sample, 'Mean Read Score', stats[group]['Mean Read Score'] , group)
                    self._add_result_element(sample, 'Number of Reads', stats[group]['Number of Reads'] , group)
                    self._add_result_element(sample, 'Number of Bases', stats[group]['Number of Bases'] , group)
                    self._add_result_element(sample, 'N50', stats[group]['N50'] , group)
                    self._add_result_element(sample, 'Mean Read Length', stats[group]['Mean Read Length'] , group)
                    
                    if group == 'prefilter_stats' :
                        image = os.path.join(sample_outdir, 'results', 'pre_filter_readlength_histogram.png')
                        self._add_result_element(sample, "readlen", self._save_file(image, sample + ".pre_filter_readlength_histogram.png"), group)
                        image = os.path.join(sample_outdir, 'results', 'pre_filterread_score_histogram.png')
                        self._add_result_element(sample, "readscore", self._save_file(image, sample + ".pre_filterread_score_histogram.png"), group)
                    
                    if group == 'postfilter_stats' :
                        image = os.path.join(sample_outdir, 'results', 'post_filter_readlength_histogram.png')
                        self._add_result_element(sample, "readlen", self._save_file(image, sample + ".post_filter_readlength_histogram.png"), group)
                        image = os.path.join(sample_outdir, 'results', 'post_filterread_score_histogram.png')
                        self._add_result_element(sample, "readscore", self._save_file(image, sample + ".post_filterread_score_histogram.png"), group)
            
            # subreads filter stats
            jsonfile = os.path.join(sample_outdir, 'results', 'filter_reports_filter_subread_stats.json')
            if os.path.isfile(jsonfile):
                group = 'subreads_stats'
                
                if group not in metrics : 
                    metrics.append(group)
                    self._add_result_element("metrics", "headers", ','.join(['Mean Subread length', 'N50', 'Number of Bases', "Number of Reads", 'report']), group)
                stats = self.parse_subreads_filter_json(jsonfile)
                self._add_result_element(sample, 'Mean Subread length', stats['Mean Subread length'] , group)
                self._add_result_element(sample, 'N50', stats['N50'] , group)
                self._add_result_element(sample, 'Number of Bases', stats['Number of Bases'] , group)
                self._add_result_element(sample, 'Number of Reads', stats['Number of Reads'] , group)
                
                image = os.path.join(sample_outdir, 'results', 'filtered_subread_report.png')
                self._add_result_element(sample, "report", self._save_file(image, sample + ".filtered_subread_report.png"), group)
Gerald Salin's avatar
Gerald Salin committed
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
                
            # Barcode report
            jsonfile = os.path.join(sample_outdir, 'results', 'barcode_report.json')
            if os.path.isfile(jsonfile):
                group = 'barcode_results'
                
                if group not in metrics2 : 
                    metrics2.append(group)
                    self._add_result_element("metrics2", "headers", ','.join(['Reads', 'Bases']), group)
                stats = self.parse_barcode_report_json(jsonfile)

                for i,barcode in enumerate(stats['Barcode Name']):
                   self._add_result_element(barcode, 'Reads', stats['Reads'][i] , group)
                   self._add_result_element(barcode, 'Bases', stats['Bases'][i] , group)
                
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
            
    # ------ parsing of json files ------
    
    def load_json(self,filename):
        jsonstring = "{}"
        with open(filename) as fh :
            jsonstring = fh.readline()
        return json.loads(jsonstring)
    
    def parse_loading_json(self,jsonfile):
        obj = self.load_json(jsonfile)
        res = {}
        for e in obj['attributes'] :
            if e['name'] == 'Productive ZMWs' :
                res["Productive ZMWs"] = e['value']
            elif e['name'] == 'ZMW Loading Productivity 2' :
                res["Productivity 0"] = e['value']
            elif e['name'] == 'ZMW Loading Productivity 3' :
                res["Productivity 1"] = e['value']
            elif e['name'] == 'ZMW Loading Productivity 4' :
                res["Productivity 2"] = e['value']
        return res
    
    def parse_adapter_json(self,jsonfile):
        obj = self.load_json(jsonfile)
        res = {}
        for e in obj['attributes'] :
            if e['id'] == 'adapter.adapter_dimers' :
                res["Adapter Dimers"] = e['value']
            elif e['id'] == 'adapter.short_inserts' :
                res["Short Inserts"] = e['value']
            elif e['id'] == 'adapter.medium_inserts' :
                res["Medium Inserts"] = e['value']
        return res
    
    def parse_filter_json(self, jsonfile):
        obj = self.load_json(jsonfile)
        res = {
            'prefilter_stats' : {},
            'postfilter_stats': {}
        }
        for e in obj['attributes'] :
            if e['id'] == 'filtering_report.mean_read_score_pre_filter' :
                res['prefilter_stats']["Mean Read Score"] = e['value']
            elif e['id'] == 'filtering_report.reads_n_pre_filter' :
                res['prefilter_stats']["Number of Reads"] = e['value']
            elif e['id'] == 'filtering_report.base_n_pre_filter' :
                res['prefilter_stats']["Number of Bases"] = e['value']
            elif e['id'] == 'filtering_report.n50_read_length_pre_filter' :
                res['prefilter_stats']["N50"] = e['value']
            elif e['id'] == 'filtering_report.mean_read_length_pre_filter' :
                res['prefilter_stats']["Mean Read Length"] = e['value']
                
            elif e['id'] == 'filtering_report.mean_read_score_post_filter' :
                res['postfilter_stats']["Mean Read Score"] = e['value']
            elif e['id'] == 'filtering_report.reads_n_post_filter' :
                res['postfilter_stats']["Number of Reads"] = e['value']
            elif e['id'] == 'filtering_report.base_n_post_filter' :
                res['postfilter_stats']["Number of Bases"] = e['value']
            elif e['id'] == 'filtering_report.n50_read_length_post_filter' :
                res['postfilter_stats']["N50"] = e['value']
            elif e['id'] == 'filtering_report.mean_read_length_post_filter' :
                res['postfilter_stats']["Mean Read Length"] = e['value']
        return res
    
    def parse_subreads_filter_json(self,jsonfile):
        obj = self.load_json(jsonfile)
        res = {}
        for e in obj['attributes'] :
            if e['id'] == 'filter_subread.filter_subread_mean' :
                res["Mean Subread length"] = e['value']
            elif e['id'] == 'filter_subread.filter_subread_n50' :
                res["N50"] = e['value']
            elif e['id'] == 'filter_subread.filter_subread_nbases' :
                res["Number of Bases"] = e['value']
            elif e['id'] == 'filter_subread.filter_subread_nreads' :
                res["Number of Reads"] = e['value']
        return res
        
Gerald Salin's avatar
Gerald Salin committed
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
    def parse_barcode_report_json(self,jsonfile):
        obj = self.load_json(jsonfile)
        '''print (obj)'''
        res = {}
        for e in obj['tables'] :
            '''print ("ATTRIBUTE")
            print ("e ----> ",e,'\n')'''
            for c in e['columns']:
                '''print ('c------> ', c,'\n')'''

                if c['id'] == 'barcode.barcode_table.barcode' :
                   res['Barcode Name'] = c['values']
                elif c['id'] == 'barcode.barcode_table.number_of_reads' :
                   res['Reads'] = c['values']
                elif c['id'] == 'barcode.barcode_table.number_of_bases' :
                   res['Bases'] = c['values']

            '''print ("res ---> ",res,'\n')'''
        return res
370
371
372
373