run.py 16.9 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
#
# 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 os, uuid, logging, tempfile, re
import datetime, time
from subprocess import call
from shutil import copyfile, rmtree
from ConfigParser import ConfigParser, RawConfigParser

31
from jflow import seqio
32
33
from ng6.t3MySQLdb import t3MySQLdb
from ng6.config_reader import NG6ConfigReader
Jerome Mariette's avatar
Jerome Mariette committed
34
35
from ng6.utils import Utils
from ng6.exceptions import UnsavedRunError
36

37
38
39
40
41
42
43
44

class Run(object):
    """
    Class Run: Define a nG6 run object
    """

    # The directories structure into ng6
    DIRECTORIES_STRUCTURE = "/data/run/"
Jerome Mariette's avatar
Jerome Mariette committed
45
46
    SEQUENCERS = ["454", "454 GS FLX Titanium", "454 GS FLX+", "454 GS FLX XL+", "HiSeq 2000", "MiSeq"]
    
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
    def __init__(self, name, date, species, data_nature, type, description, sequencer, id = None):
        """
        Build a Run object
          @param name        : the run name
          @param date        : the run data in a date format
          @param species     : the species used in the run
          @param data_nature : the data nature used in the run
          @param type        : the type of run
          @param description : the run description
          @param sequencer   : the sequencer used
          @param run_id      : the id of the run, if None a new one will be created
        """
        self.name = name
        self.date = date
        self.species = species
        self.data_nature = data_nature
        self.type = type
        self.description = description
        self.sequencer = sequencer
        self.__mids_description = None
67
        self.raw_files = []
68
69
70
71
        
        # Set the temp folder to the ng6 temp folder
        ng6conf = NG6ConfigReader()
        tempfile.tempdir = ng6conf.get_tmp_directory()
Jerome Mariette's avatar
Jerome Mariette committed
72
73
74
        if not os.path.isdir(tempfile.tempdir): 
            os.makedirs(tempfile.tempdir, 0751)
            
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
        if id != None : # If not a new run
            self.id = id
            t3mysql = t3MySQLdb()
            self.directory = t3mysql.select_run_directory(id)
        else :
            # First find out a uniq id
            uniq = False
            directory_name = uuid.uuid4().hex[:9]
            while True:
                save_dir = os.path.join(ng6conf.get_save_directory()+self.DIRECTORIES_STRUCTURE, directory_name)
                work_dir = os.path.join(ng6conf.get_work_directory()+self.DIRECTORIES_STRUCTURE, directory_name)
                if not os.path.isdir(save_dir) and not os.path.isdir(work_dir):
                    break
                directory_name = uuid.uuid4().hex[:9]
            # Then make directories
            work_dir = os.path.join(ng6conf.get_work_directory()+self.DIRECTORIES_STRUCTURE, directory_name)
            os.makedirs(work_dir, 0751)
            self.directory = os.path.join(self.DIRECTORIES_STRUCTURE, directory_name)

94
    def process_raw_files(self, mode):
Jerome Mariette's avatar
Jerome Mariette committed
95
96
97
98
99
        """
        Copy, archive and compress the files list to the run. And add info to the run
          @param mode: can be none, gz, bz2, tar.gz and tar.bz2    
        """
        nb_seq, full_size = 0, 0
100
        for file in self.raw_files:
Jerome Mariette's avatar
Jerome Mariette committed
101
102
103
104
105
106
107
            # Get nb_seq and full_size values
            reader = seqio.SequenceReader(file)
            for id, desc, seq, qualities in reader:
                nb_seq += 1
                full_size += len(seq)
        self.set_nb_sequences(nb_seq)
        self.set_full_size(full_size)
108
        self.archive_files(self.raw_files, mode)
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
    
    def export_mids_to_newbler_cfg_file(self, error=2, midscheme="454MIDS"):
        """
        Export the config file in newbler format
        the script add_raw_files.
          @param files: the files to archive
          @param mode: can be none, gz, bz2, tar.gz and tar.bz2    
        """
        mids_cfg_path = tempfile.NamedTemporaryFile(suffix=".cfg").name
        mid_file = open(mids_cfg_path, "w")
        mid_file.write(midscheme+"\n")
        mid_file.write("{\n")
        # MID1:desc_ex1;MID2:desc_ex2;MID3,MID4:
        cfg_reader = NG6ConfigReader()
        mids = cfg_reader.get_454_mids()
        # First write the run mids config file
        for mid in self.__mids_description:
            for mid_name in mid.split(","):
                try:
                    mid_name = mid_name.strip()
                    seq = mids[mid_name.lower()].split(",")
                    seq_val = ''
                    if len(seq) > 1:
                        seq_val += '"' + seq[0] + '", ' + str(error) + ', "' + seq[1] + '";'
                    else:
                        seq_val += '"' + seq[0] + '", ' + str(error) + ';'
                    mid_file.write('\tmid = "' + self.__mids_description[mid] + '", ' + seq_val +"\n")
                except:
                    pass
        mid_file.write("}")
        mid_file.close()
        return [mids_cfg_path, midscheme]
    
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
    def archive_files(self, files, mode, archive_name="ng6_archive.tar", delete=False):
        """
        Copy, archive and compress the files list to the run. Files can then be downloaded and gave back by
        the script ng6run2ergatis.
          @param files: the files to archive
          @param mode: can be none, gz, bz2, tar.gz and tar.bz2
          @param archive_name: the archive name if tar is requested
          @param delete: delete files     
        """
        # First handle if only one file
        if len(files) == 1 and mode == "tar.gz":
            mode = "gz"
        elif len(files) == 1 and mode == "tar.bz2":
            mode = "bz2"
        
        if mode == "none":
            for file in files:
                if os.path.isfile(file):
                    copyfile(file, os.path.join(self.__get_work_directory(), os.path.basename(file)))
                # Finaly try to delete the original file if asked to do so
                try:
                    if delete:
                        os.remove(file)
                except:
                    pass

        elif mode == "gz":
            for file in files:
                Utils.gzip(file, self.__get_work_directory(), delete)

        elif mode == "bz2":
            for file in files:
                Utils.bz2(file, self.__get_work_directory(), delete)

        elif mode == "tar.gz":
            Utils.tar_files(files, os.path.join(self.__get_work_directory(), archive_name), delete)
            Utils.gzip(os.path.join(self.__get_work_directory(), archive_name), self.__get_work_directory(), True)

        elif mode == "tar.bz2":
            Utils.tar_files(files, os.path.join(self.__get_work_directory(), archive_name), delete)
            Utils.bz2(os.path.join(self.__get_work_directory(), archive_name), self.__get_work_directory(), True)
                
    def set_nb_sequences(self, nb_seqs):
        """
        Sets the number of sequences to nb_seqs
          @param nb_seqs : the run number of sequences
        """
        if self.id != None:
            t3mysql = t3MySQLdb()
            t3mysql.update_run_info(self.id, nb_sequences=nb_seqs)
        else :
            raise UnsavedRunError()

    def set_full_size(self, full_size):
        """
        Sets the number of nucleotides in all sequences
          @param full_size : the number of nucleotides
        """
        if self.id != None :
            t3mysql = t3MySQLdb()
            t3mysql.update_run_info(self.id, full_seq_size=full_size)
        else :
            raise UnsavedRunError()

    def get_analysis(self):
        """
Jerome Mariette's avatar
Jerome Mariette committed
208
        Return a table of Analysis object that belongs to the run
209
        """
Jerome Mariette's avatar
Jerome Mariette committed
210
        from ng6.analysis import Analysis
211
212
        t3mysql = t3MySQLdb()
        analysis = []
Jerome Mariette's avatar
Jerome Mariette committed
213
214
215
216
        analysis_ids = t3mysql.get_run_analysis_ids(self.id)
        # For each analysis
        for analysis_id in analysis_ids:
            analysis.append(Analysis.get_from_id(analysis_id))
217
218
219
220
221
222
223
224
225
226
227
        return analysis

    def sync(self):
        """
        Synchronyze data related to the Run between temporary folder and long term storage folder.
        """
        logging.getLogger("Run.sync").debug("Synchronizing run id=" + str(self.id) + " from " + self.__get_work_directory() + " to " + self.__get_save_directory())
        if self.id == None :
            raise UnsavedRunError()
        # First sync all analysis
        try :
Jerome Mariette's avatar
Jerome Mariette committed
228
229
            for my_analysis in self.get_analysis():
                my_analysis.sync()
230
231
232
        except Exception, err:
            logging.getLogger("Run.sync").error("Error when synchronizing analysis that belongs to run id=" + str(self.id))
            raise Exception(str(err))
Jerome Mariette's avatar
Jerome Mariette committed
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
        # If a sync is required
        if not os.path.isdir(self.__get_save_directory()) and len(os.listdir(self.__get_work_directory())):
            # Finally the Run itself
            try :
                # First make the save directory
                os.makedirs(self.__get_save_directory(), 0751)            
                if os.path.exists(self.__get_work_directory()) and self.__get_work_directory() != self.__get_save_directory():
                    cmd = "rsync -avh --remove-sent-files "+ self.__get_work_directory() + "/ " + self.__get_save_directory()
                    logging.getLogger("Run.sync").debug(cmd)
                    retcode = call(["rsync", "-avh", "--remove-sent-files", self.__get_work_directory() + "/", self.__get_save_directory()], shell=False)
                    if retcode < 0:
                        logging.getLogger("Run.sync").error("Error when synchronizing run id=" + str(self.id) + "(retcode=" + str(retcode) + ")")
                    else:
                        try: os.rmdir(self.__get_work_directory())
                        except: pass
                        logging.getLogger("Run.sync").debug("Synchronization done for run id=" + str(self.id) + "(retcode=" + str(retcode) + ")")
            except Exception, err:
                raise Exception(str(err))
251

Jerome Mariette's avatar
Jerome Mariette committed
252
    def add_analysis(self, my_analysis):
253
        """
Jerome Mariette's avatar
Jerome Mariette committed
254
255
        Add the analysis to the run
          @param my_analysis   : the analysis to add
256
257
258
        """
        if self.id != None :
            # First define the run
Jerome Mariette's avatar
Jerome Mariette committed
259
            analysis_id = my_analysis.save()
260
            t3mysql = t3MySQLdb()
Jerome Mariette's avatar
Jerome Mariette committed
261
            t3mysql.add_analysis_to_run(self.id, analysis_id)
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
        else :
            raise UnsavedRunError()

    def get_directory_path(self):
        """
        Return the full path to the Run directory
        """
        return self.__get_save_directory()

    def get_mids_description(self):
        """
        Return a dictionary with mids description
          @return : {"MID1":"mid1_desc", "MID2":"mid2_desc", ...}
        """
        if self.__mids_description :
            return self.__mids_description
        else :
            return t3mysql.select_run_samples(self.id)

    def add_mids_description(self, mids_desc):
        """
        Add a mids description to the run
          @param mids_desc  : the mids description dictionnary
                              {"MID1":"mid1_desc", "MID2":"mid2_desc", ...}
        """
        # First add the description to the python object
        self.__mids_description = mids_desc
289
290
291
292
293
294
        
        if self.id != None:
            # Update database
            t3mysql = t3MySQLdb()
            for mid_name in self.__mids_description.keys():
                t3mysql.add_sample_to_run(self.id, mid=mid_name, description=self.__mids_description[mid_name])
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406

    def get_config_file(self):
        """
        Return a Run config file
          @return : path the the config file
        """
        t3mysql = t3MySQLdb()
        
        # First select run
        [name, date, species, data_nature, type, description, sequencer] = t3mysql.select_run(self.id)
        config = RawConfigParser()
        config.add_section("Run")
        config.set("Run", "run_id", self.id)
        config.set("Run", "name", name)
        config.set("Run", "date", date)
        config.set("Run", "species", species)
        config.set("Run", "data_nature", data_nature)
        config.set("Run", "type", type)
        config.set("Run", "description", description)
        config.set("Run", "sequencer", sequencer)
        
        # Then run samples
        samples = t3mysql.select_run_samples(self.id)
        if len(samples.keys()) > 0 : config.add_section("MIDS")
        for sample in samples.keys():
            config.set("MIDS", sample, samples[sample])
        
        config_path = tempfile.NamedTemporaryFile(suffix=".cfg").name
        config.write(open(config_path,'w'))
        return config_path

    def get_run_files(self, pattern, unzip=True):
        """
        Return list of file corresponding to the pattern
          @param file  : the pattern of files to return
          @param unzip : true for unzip files returned with pattern
          @return      : list of file.
        """
        list = []
        for file in os.listdir(self.__get_save_directory()) :
            # If it fits criteria
            if pattern != "":
                if unzip:
                    if re.search("^" + pattern + "\.gz$", file) or re.search("^" + pattern + "\.zip$", file):
                        tmp_dir = tempfile.mkdtemp()
                        list.append(Utils.gunzip(os.path.join(self.__get_save_directory(), file), tmp_dir))
                    elif re.search("^" + pattern + "\.bz2$", file) or re.search("^" + pattern + "\.bz$", file):
                        tmp_dir = tempfile.mkdtemp()
                        list.append(Utils.uncompress_bz2(os.path.join(self.__get_save_directory(), file), tmp_dir))
                    elif re.search("^" + pattern + "$", file):
                        list.append(os.path.join(self.__get_save_directory(), file))
                else:
                    if re.search("^" + pattern + "$", file):
                        list.append(os.path.join(self.__get_save_directory(), file))
            else:
                list.append(file)
        return list

    def save(self):
        """
        Creates the run config file and save it in the run directory
        """
        # First add the run into the database
        t3mysql = t3MySQLdb()
        self.id = t3mysql.add_run(self.name, self.date, self.directory, self.species, self.data_nature,
                                  self.type, 0, 0, self.description, self.sequencer)
        
        # If there is some mids desc provided
        if self.__mids_description != None:
            for mid_name in self.__mids_description.keys():
                t3mysql.add_sample_to_run(self.id, mid=mid_name, description=self.__mids_description[mid_name])

        # Finaly return it's id
        return self.id

    def __get_work_directory(self):
        """
        Return the full path of the run directory into the work dir
        """
        ng6conf = NG6ConfigReader()
        return ng6conf.get_work_directory() + self.directory

    def __get_save_directory(self):
        """
        Return the full path of the run directory into the save dir
        """
        ng6conf = NG6ConfigReader()
        return ng6conf.get_save_directory() + self.directory

    @staticmethod
    def get_from_id (id):
        """
        Return a run object specified by its id
          @param id : the run id
        """
        try:
            t3mysql = t3MySQLdb()
            [name, date, species, data_nature, type, description, sequencer] = t3mysql.select_run(id)
            my_run = Run(name, date, species, data_nature, type, description, sequencer, id)
            # Add the mids_description to the object
            try :
                mids_desc = {}
                samples = t3mysql.select_run_samples(id)
                # Create the mids_desc table
                for sample in samples.keys():
                    mids_desc[sample] = samples[sample]
                my_run.__mids_description = mids_desc
            except :
                pass
            return my_run
        except :
            logging.getLogger("Run.get_from_id").debug("Impossible to build run id=" + str(id))
407
            return None
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423

    @staticmethod
    def get_from_config (config_file):
        """
        Return a run object specified by its config file
          @param config_file : the run config file
        """
        try:
            reader = ConfigParser()
            reader.read(config_file)
            run_id = reader.get('Run', 'run_id')
            my_run = Run.get_from_id(run_id)
            return my_run
        except :
            pass