utils.py 11 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#
# Copyright (C) 2009 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/>.
#

__author__ = 'Plateforme bioinformatique Midi Pyrenees'
__copyright__ = 'Copyright (C) 2009 INRA'
__license__ = 'GNU General Public License'
__version__ = '1.0'
__email__ = 'support.genopole@toulouse.inra.fr'
__status__ = 'beta'

import glob
import os
import string, gzip, bz2
import tarfile, tempfile
from shutil import copyfile, rmtree
import re

class Utils(object):
    """
    Class Utils: in charge to all the programme utilities
    """

    # Files with this extensions won't be compressed if asked
    UNCOMPRESS_EXTENSION = [".gz", ".zip", ".bam", ".bz", ".bz2"]
Penom Nom's avatar
Penom Nom committed
39
40
41
42
    
    # CASAVA filename format
    CASAVA_FILENAME = { 'sample' : 1, 'barcode' : 2, 'lane' : 3, 'read' : 4, 'package' : 5 }
    CASAVA_FILENAME_SEPARATOR = '_'
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
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

    @staticmethod
    def gzip(file, out_dir, delete=False):
        """
          Gzip compress the given file.
          @param file    : the file to gzip 
          @param out_dir : the out directory where to store the gziped file
          @param delete  : delete files     
          @return        : the compressed file path
        """
        # If the file is not already a compressed file
        if os.path.splitext(file)[1] not in Utils.UNCOMPRESS_EXTENSION:
            f_in = open(file, 'rb')
            f_out_name = os.path.join(out_dir, os.path.basename(file)) + ".gz"
            f_out = gzip.open(f_out_name, 'wb')
            f_out.writelines(f_in)
            f_out.close()
            f_in.close()
        # Otherwise, just copy it
        else:
            f_out_name = os.path.join(out_dir, os.path.basename(file))
            copyfile(file, f_out_name)
        
        # Finaly try to delete the original file if asked to do so
        try:
            if delete:
                os.remove(file)
        except:
            pass
        return f_out_name


    @staticmethod
    def gunzip(file, out_dir):
        """
          Gunzip given file.
          @param file    : the file to gunzip 
          @param out_dir : the out directory where to store the decompressed file 
          @return        : the uncompressed file path
        """
        f_in = gzip.open(file)
        f_out_name = os.path.join(out_dir, os.path.splitext(os.path.basename(file))[0])
        f_out = open(f_out_name, 'w')
        f_out.writelines(f_in)
        f_out.close()
        f_in.close()
        return f_out_name


    @staticmethod
    def bz2(file, out_dir, delete=False):
        """
          Bzip compress the given file.
          @param file    : the file to compress 
          @param out_dir : the out directory where to store the compressed file
          @param delete  : delete files     
          @return        : the compressed file path
        """
        # If the file is not already a compressed file
        if os.path.splitext(file)[1] not in Utils.UNCOMPRESS_EXTENSION:
            f_in = open(file, 'rb')
            f_out_name = os.path.join(out_dir, os.path.basename(file)) + ".bz2"
            f_out = bz2.BZ2File(f_out_name, 'wb')
            f_out.writelines(f_in)
            f_out.close()
            f_in.close()
        # Otherwise, just copy it
        else:
            f_out_name = os.path.join(out_dir, os.path.basename(file))
            copyfile(file, f_out_name)
        
        # Finaly try to delete the original file if asked to do so
        try:
            if delete:
                os.remove(file)
        except:
            pass

        return f_out_name


    @staticmethod
    def uncompress_bz2(file, out_dir):
        """
          Bzip compress the given file.
          @param file    : the file to compress 
          @param out_dir : the out directory where to store the compressed file     
          @return        : the compressed file path
        """
        f_in = bz2.BZ2File(file)
        f_out_name = os.path.join(out_dir, os.path.splitext(os.path.basename(file))[0])
        f_out = open(f_out_name, 'w')
        f_out.writelines(f_in)
        f_out.close()
        f_in.close()
        return f_out_name


    @staticmethod
    def tar_files(files, out_tar_name, delete=False):
        """
        Tar all files given.
          @param files        : table of files
          @param out_tar_name : the full output tar path (archive name included)
          @param delete       : delete files     
          @return             : the path to the tar file
        """
        tarf = tarfile.open(out_tar_name, "w")
        for file in files:
            if os.path.isfile(file) :
                (head, tail)= os.path.split(file)
                os.chdir(head)
                tarf.add(tail)
        tarf.close()
        
        for file in files:
            try:
                if delete:
                    os.remove(file)
            except:
                pass
        return out_tar_name


    @staticmethod
    def yield_files(files_tab):
        """
        yield objects to untar
        """
        for file in files_tab:
            yield file


    @staticmethod
    def untar_files(archive, pattern, out_dir):
        """
        Tar all files given.
          @param archive : the tar file
          @param pattern : the extension to search for
          @param out_dir : where should be untar the files
          @return        : a list of untared files
        """
        tarf = tarfile.open(archive)
        files = []
        files_to_return = []
        for tarinfo in tarf:
            if os.path.splitext(tarinfo.name)[1] == "."+pattern:
                files.append(tarinfo)
                files_to_return.append(os.path.join(out_dir, tarinfo.name))
        tarf.extractall(path=out_dir, members=Utils.yield_files(files))
        tarf.close()
        return files_to_return
        
        
    @staticmethod
    def tar_dir(directory, out_tar_name, delete=False):
        """
        Tar the given directory.
          @param directory    : the directory to tar
          @param out_tar_name : the full output tar path (archive name included)
          @param delete       : delete dir
          @return             : the path to the tar file
        """
        tarf = tarfile.open(out_tar_name, "w")
        os.chdir(directory)
        tarf.add(".")
        tarf.close()
        try:
            if delete:
                shutil.remove(directory)
        except:
            pass
        return out_tar_name
    
    
    @staticmethod
    def getUniqueCombinaison(items, n):
        """
        Return all combinaison for the list
          @param items : the list
          @param n : the max depth
        """
        if n==0: 
            yield []
        else:
            for i in xrange( len(items) - n+1 ):
                for j in Utils.getUniqueCombinaison( items[i+1:], n-1 ):
                    yield [items[i]] + j

    
    @staticmethod             
    def getSizesUniqueCombinaison(items):
        """
        Return all combinaison for the list
          @param items : the list
        """
        res = []
        for n in xrange(1,len(items)+1):
            res += Utils.getUniqueCombinaison(items,n)
        return res
Penom Nom's avatar
Penom Nom committed
243
244
245
246
247
248
249
250
251
252
253
254
255
256
 
    
    @staticmethod
    def split_pair( file_list, is_casava=False ):
        """
        Return the list of read 1 and the list of read 1 from a list
          @param file_list : the list
          @param is_casava : files names in file_list are in CASVAVA format 
        """
        read_1_list = []
        read_2_list = []
    
        if is_casava:
            for file in file_list:
Penom Nom's avatar
Penom Nom committed
257
258
                basename_without_ext = os.path.basename(file).split(".")[0]
                file_name_fields = basename_without_ext.split(Utils.CASAVA_FILENAME_SEPARATOR)
Penom Nom's avatar
Penom Nom committed
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
                read_tag = file_name_fields[Utils.CASAVA_FILENAME['read']-1]
                if read_tag == "R1":
                    read_1_list.append(file)
                else:
                    read_2_list.append(file)
        else:
            sort_list = file_list
            sort_list.sort()
    
            for i in range(0,len(sort_list),2):
                read_1_list.append(file_list[i])
                read_2_list.append(file_list[i+1])
     
        return [read_1_list, read_2_list]


    @staticmethod
    def get_group_basenames( file_list, group_by ):
        """
        Return the list of prefix according to keywords. Ex : [/home/sampleA_ATGCTC_L001_R1_001.fastq.gz, /home/sampleA_ATGCTC_L001_R2_001.fastq.gz, /home/sampleB_ATGCCG_L001_R1_001.fastq.gz]  => [sampleA_ATGCTC_L001_R1, sampleA_ATGCTC_L001_R2, sampleB_ATGCCG_L001_R1]
          @param file_list : the list of files (files names are in CASVAVA format)
          @param group_by : CASAVA_FILENAME key (ex : read)
        """
        group_basenames = {}

        for file in file_list:      
            file_name_fields = os.path.basename(file).split(Utils.CASAVA_FILENAME_SEPARATOR)
        
            group_tag = Utils.CASAVA_FILENAME_SEPARATOR.join( file_name_fields[:Utils.CASAVA_FILENAME[group_by]] )
        
            if group_basenames.has_key(group_tag) :
                group_basenames[group_tag].append(file)
            else:
                group_basenames[group_tag] = [file]
     
        return group_basenames
Penom Nom's avatar
Penom Nom committed
295
296
297
298
299
300
301
302
303
304
305
306
307
    
    
    @staticmethod
    def get_argument_pattern( list, start_number=1 ):
        """
        Return the argument pattern for arguments files. Ex : with 3 element in list this function returns ["$1 $2 $3", 4]
          @param list : the list of files
          @param start_number : number of the first argument
        """
        arg_pattern = ""
        next_number = start_number
        
        for elt in list:
308
            arg_pattern += ' ${' + str(next_number) + '}'
Penom Nom's avatar
Penom Nom committed
309
310
            next_number += 1
        
Penom Nom's avatar
Penom Nom committed
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
        return [arg_pattern, next_number]

    @staticmethod
    def get_filepath_by_prefix( path_list, prefixes ):
        """
        Gather files path with same prefix. Ex :
        list [/home/sample1_L002.fastq, /home/sample2_L002.fastq, /home/sample1_L003.fastq] 
        with prefixes [sample1, sample2]
        return {'sample1':[/home/sample1_L002.fastq, /home/sample1_L003.fastq], 'sample2':[/home/sample2_L002.fastq]}
          @param path_list : the list of files
          @param prefixes : prefix to gather
        """
        path_groups = {}
        
        for current_prefix in prefixes:
            path_groups[current_prefix] = []           
            for file_path in path_list:
                if os.path.basename(file_path).startswith(current_prefix):
                    path_groups[current_prefix].append(file_path)
        
        return path_groups