index.py 17.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
'''
Created on 28 sept. 2014

@author: coissac
'''

from subprocess import Popen
from tempfile   import mkdtemp
from tempfile   import mktemp
from shutil     import rmtree

import atexit
import os.path
import sys

from orgasm.indexer import Index
17
from orgasm.reads._sequences import readPairedEnd, setLogger, getStats  # @UnresolvedImport
18 19 20 21 22 23 24

__title__="Index a set of reads"

default_config = { 'reformat' : False,
                   'single'   : False,
                   'forward'  : None,
                   'reverse'  : None,
25 26
                   '5trim'    : 4,
                   'qualtrim' : 0,
27
                   'badqual'  : 20,
28 29
                   'skip'     : 0,
                   'maxread'  : 0,
30
                   'length'   : 0,
31 32
                   'estimate' : 0,
                   'minlength': 81,
33 34 35 36 37 38
                   'fasta'    : False,
                   'ffasta'   : False,
                   'rfasta'   : False,
                   'nopipe'   : False,
                   'checkpairs':False,
                   'mate'     : False,
39 40 41 42
                   "phix"     : True,
                   "fastqdump": False,
                   'shift'    : 33,
                   "direct"   : False
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
                 }

def addOptions(parser):
    parser.add_argument(dest='orgasm:indexfilename',  metavar='index', 
                        help='name of the produced index')

    parser.add_argument(dest='index:forward',  metavar='forward', 
                        nargs='?', 
                        default=None,
                        help='Filename of the forward reads')
    
    parser.add_argument(dest='index:reverse',     
                        metavar='reverse', 
                        nargs='?', 
                        default=None,
                        help='Filename of the reverse reads' )
    
    
    parser.add_argument("--reformat",
                        dest="index:reformat",
                        action='store_true',
                        default=None,
                        help='Asks for reformatting an old sequence index to the new format'
                       )
    
    parser.add_argument('--single',           
                        dest='index:single', 
                        action='store_true', 
                        default=None, 
72 73 74 75 76 77 78 79 80 81 82 83 84
                        help='Single read mode, pair-end reads will be simulated')

    parser.add_argument('--check-phiX174',           
                        dest='index:phix', 
                        action='store_true', 
                        default=None, 
                        help='Checks for PhiX174 contamination (default)')

    parser.add_argument('--no-check-phiX174',           
                        dest='index:phix', 
                        action='store_false', 
                        default=None, 
                        help='Does not check for PhiX174 contamination')
85 86 87 88 89 90

    parser.add_argument('--mate-pairs',       dest='index:mate', 
                                              action='store_true', 
                                              default=None, 
                        help='Mate pair library mode')

91 92 93 94 95
    parser.add_argument('--5-prime-trim',     dest='index:5trim', 
                                              type=int, 
                                              action='store', 
                                              default=None, 
                        help='Cut the N first base pairs of '
96
                             'reads (default %dbp)' % default_config['5trim'])
97 98 99
    
    parser.add_argument('--3-prime-quality',  dest='index:qualtrim', 
                                              metavar="Q",
100 101 102
                                              type=int, 
                                              action='store', 
                                              default=None, 
103 104 105 106 107 108 109 110 111 112 113 114 115
                        help="Hard clips the 3' end of each reads"
                             'after the first base with a score '
                             "less or equal to Q (default 0 no clipping)")
    
    parser.add_argument('--bad-quality',  dest='index:badqual', 
                                              metavar="Q",
                                              type=int, 
                                              action='store', 
                                              default=None, 
                        help="Consider quality below Q as bad "
                             "quality score, and try to clip "
                             "reads to maximise the overall "
                             "quality. Zero means no clipping "
116
                             "(default %d)" % default_config['badqual'])
117 118 119 120 121 122 123
    
    parser.add_argument('--skip',             dest='index:skip', 
                                              metavar="N",
                                              type=int, 
                                              action='store', 
                                              default=None, 
                        help='Skip the N first read pairs '
124
                             '(default %d)' % default_config['skip'])
125 126 127 128 129 130 131 132
    
    parser.add_argument('--max-reads',        dest='index:maxread', 
                                              metavar="N",
                                              type=int, 
                                              action='store', 
                                              default=None, 
                        help='index a maximum of N read pairs '
                             '(default the full file)')
133 134 135 136 137 138 139 140 141 142 143 144 145 146
    
    parser.add_argument('--length',           dest='index:length', 
                                              type=int, 
                                              action='store', 
                                              default=None, 
                        help='The length of the read to index '
                             ' (default indexed length is estimated from the first read)')
    
    parser.add_argument('--estimate-length',  dest='index:estimate', 
                                              metavar='FRACTION',
                                              type=float, 
                                              action='store', 
                                              default=None, 
                        help='Estimate the length to index for conserving FRACTION '
147
                             'of the overall data set')
148
    
149 150 151
    parser.add_argument('--minimum-length',   dest='index:minlength', 
                                              type=int, 
                                              action='store', 
152
                                              default=None, 
153 154 155
                        help='The minimum length of the read to index '
                             'if the --estimate-length is activated (default 81)')
    
156 157 158 159 160
    parser.add_argument('--no-pipe',          dest='index:nopipe', 
                                              action='store_true', 
                                              default=None, 
                        help='do not use pipe but temp files instead')

161
    parser.add_argument('--bypass-filtering', dest='index:direct', 
162
                                              action='store_true', 
163 164 165 166 167 168 169 170 171
                                              default=None, 
                        help='Sequence files are considered as '
                             'pre-filtered fastq files')

    parser.add_argument('--fastq-dump',           
                        dest='index:fastqdump', 
                        action='store_true', 
                        default=None, 
                        help='Dump the fastq file or the trimmed reads')
172 173 174 175 176 177

    parser.add_argument('--check-pairing',            dest='index:checkpairs', 
                                              action='store_true', 
                                              default=False, 
                        help='ensure that forward and reverse files are correctly paired')

178 179 180 181 182 183
    parser.add_argument('--quality-encoding-offset',  dest='index:shift', 
                                              type=int, 
                                              action='store', 
                                              default=None, 
                        help='The code offset added to each quality '
                             'score to encode fastq quality '
184
                             '(default %d - Sanger format)' % default_config['shift'])
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 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
tmpdir = []

# @atexit.register
# def cleanup():
#     try:
#         os.unlink(FIFO)
#     except:
#         pass

def reformatOldIndex(config):

    logger  = config['orgasm']['logger']
    output  = config['orgasm']['indexfilename']
    if not (os.path.exists('%s.ofx' % output ) and
            os.path.exists('%s.ogx' % output ) and
            os.path.exists('%s.opx' % output ) and
            os.path.exists('%s.orx' % output )
           ):
        logger.error('The %s index does not exist or is not complete' % output)
        sys.exit(1)
    
    dirname = '%s.odx' % output
    if not os.path.exists(dirname):
        os.makedirs(dirname) 

    os.rename('%s.ofx' % output, '%s/index.ofx' % dirname)
    os.rename('%s.ogx' % output, '%s/index.ogx' % dirname)
    os.rename('%s.opx' % output, '%s/index.opx' % dirname)
    os.rename('%s.orx' % output, '%s/index.orx' % dirname)

    sys.exit(0)

def postponerm(filename):
    def trigger():
        print("Deleting tmp file : %s" % filename,file=sys.stderr)
        try:
            os.unlink(filename)
        except:
            pass
        
    return trigger

def postponermdir(filename):
    def trigger():
        print("Deleting tmp directory : %s" % filename,file=sys.stderr)
        try:
            rmtree(filename)
        except:
            pass
        
    return trigger

def getTmpDir():
    global tmpdir

    if not tmpdir:
        tmpdir.append(mkdtemp())
        atexit.register(postponermdir(tmpdir[0]))
        
    return tmpdir[0]


def ungzip(filename,nopipe):
    tmpdir = getTmpDir()

    fifo = mktemp(prefix="unziped-", dir=tmpdir)
    command="gzip -d -c %s > %s" % (filename,fifo)
    
    if nopipe:
        os.system(command)
    else:
        os.mkfifo(fifo)
        process = Popen(command,                                            # @UnusedVariable
                        shell=True,
                        stderr=open('/dev/null','w')) 
    
    atexit.register(postponerm(fifo))

    return fifo

def unbzip(filename,nopipe):
    tmpdir = getTmpDir()

    fifo = mktemp(prefix="unziped-", dir=tmpdir)
    command="bzip2 -d -c %s > %s" % (filename,fifo)
    atexit.register(postponerm(fifo))
    
    if nopipe:
        os.system(command)
    else:
        os.mkfifo(fifo)
        process = Popen(command,                                            # @UnusedVariable
                        shell=True,
                        stderr=open('/dev/null','w')) 
    
    return fifo
283
                
284 285
def formatFastq(seq):
    fastq = '@{id:0>7}\n{seq}\n+\n{qual}'
286
    return fastq.format(id=seq[0].decode('ascii'),
287
                        seq=seq[1].decode('ascii'),
288 289 290
                        qual=bytes(seq[2]).decode('ascii'))
                       
def writeToFifo(pairs,forward,reverse,fastq,logger):
291 292 293
    logger.info("Forward tmp file : %s" % forward)
    logger.info("Reverse tmp file : %s" % reverse)
    i=0
294 295 296 297 298
    
    if fastq:
        ffq=open("%s.odx/forward.fastq" % fastq,'w')
        rfq=open("%s.odx/reverse.fastq" % fastq,'w')
        
299 300
    with open(forward,'w',buffering=1) as f, \
         open(reverse,'w',buffering=1) as r:
301 302 303 304 305
        for p in pairs:
            i+=1
            if not i % 1000000:
                logger.info('%d sequence pairs written' % i)
            if len(p[0][1]) > 0 and len(p[1][1]) > 0:
306 307 308 309
                fread = formatFastq(p[0])
                rread = formatFastq(p[1])
                print(fread,file=f)
                print(rread,file=r)
310
                if fastq:
311 312
                    print(fread,file=ffq)
                    print(rread,file=rfq)
313
        
314 315 316
    if fastq:
        ffq.close()
        rfq.close()
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335

def run(config):

    logger  = config['orgasm']['logger']
    output  = config['orgasm']['indexfilename']
    forward = config['index']['forward']
    reverse = config['index']['reverse']
    nopipe  = config['index']['nopipe']
    
    if config['index']['reformat']:
        reformatOldIndex(config)
    else:
        if forward is None:
            logger.error('No sequence file specified')
            sys.exit(1)
    
    if nopipe:
        logger.info("Indexing in no pipe mode")
    
336 337 338 339 340 341 342
    if reverse is None:
        if config['index']['mate']:
            mode="IMP"
        elif config['index']['single']:
            mode="SimPE"
        else:
            mode='IPE'
343
    else:
344 345 346 347 348 349 350 351
        if config['index']['mate']:
            mode="MP"
        elif config['index']['single']:
            logger.error('Two sequence files provided and --single specified')
            sys.exit(1)
        else:
            mode='PE'
  
352 353 354
    if not os.path.exists('%s.odx' % output ):
        os.makedirs('%s.odx' % output ) 
        
355
    command = ['orgasmi','-o','%s.odx/index'  % output]
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
          
    if config['index']['direct']:
        if mode!='PE':
            logger.error('Bypass filtering mode but no regular pair-end files used')
            sys.exit(1)
        else:
            if forward[-3:]=='.gz':
                logger.info('Forward file compressed by gzip')
                forward = ungzip(forward,nopipe)
                 
            if forward[-4:]=='.bz2':
                logger.info('Forward file compressed by bzip2')
                forward = unbzip(forward,nopipe)
         
                 
            if reverse[-3:]=='.gz':
                logger.info('Reverse file compressed by gzip')
                reverse = ungzip(reverse,nopipe)
          
            if reverse[-4:]=='.bz2':
                logger.info('Reverse file compressed by bzip2')
                reverse = unbzip(reverse,nopipe)
                
    else:
        filenames = [forward]
        if reverse is not None:
            filenames.append(reverse)
            
384 385 386 387 388 389 390 391 392 393 394
        forward = mktemp(prefix="forward-", dir=getTmpDir())
        atexit.register(postponerm(forward))
        
        if not nopipe:
            os.mkfifo(forward)
        
        reverse = mktemp(prefix="reverse-", dir=getTmpDir())
        atexit.register(postponerm(reverse))
        
        if not nopipe:
            os.mkfifo(reverse)
395 396
            
        setLogger(logger)
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411

        pairs = readPairedEnd(filenames,
                              mode            = mode,
                              checkIds        = config['index']['checkpairs'],
                              cut             = config['index']['5trim'],
                              badQualityLimit = config['index']['badqual'],
                              qualityCut      = config['index']['qualtrim'],
                              length          = config['index']['length'],
                              lengthestimate  = config['index']['estimate'],
                              minlength       = config['index']['minlength'],
                              skip            = config['index']['skip'],
                              maxread         = config['index']['maxread'],
                              phix            = config['index']['phix'],
                              shift           = config['index']['shift']
                             )
412
        
413 414 415 416 417
        if config['index']['fastqdump']:
            fastq = output
        else:
            fastq = None
                                       
418 419 420 421 422
    command.append(forward)
    command.append(reverse)
    
    logger.info(" ".join(command))
    
423
    if not config['index']['direct']:
424 425
        if nopipe:
            logger.info("Writting transformed sequence files...")
426
            writeToFifo(pairs,forward,reverse,fastq,logger)
427 428 429 430 431 432 433 434 435
            logger.info("Done.")
            
            logger.info("Starting indexing...")
            logger.info(" ".join(command))
            os.system(" ".join(command)) 
        else:
            try:
                logger.info("Starting indexing...")
                process=Popen(command)
436
                writeToFifo(pairs,forward,reverse,fastq,logger)
437 438 439 440 441 442 443 444 445 446 447 448 449
                process.wait()
                logger.info('Done.')
            except BrokenPipeError:
                process.wait()
                logger.info('Done.')
                logger.warning("Maximum count of read indexed.")
                logger.warning("Indexing stopped but the index is usable.")
    else: 
        logger.info("Starting indexing...")
        logger.info(" ".join(command))
        os.system(" ".join(command)) 
    
        
450 451
    stats = getStats()
    
452 453 454
    if "paircount" in stats:
        logger.info("%9d reads pairs processed" % stats["paircount"])
    
455 456 457 458 459 460 461 462 463 464 465 466 467
    if "phix174" in stats:
        logger.info("%9d phix174 reads pairs sorted out" % stats["phix174"])
    
    if "SoftQualityTrim" in stats:
        logger.info("%9d reads pairs soft trimmed on a quality of %d" % (stats["SoftQualityTrim"],
                                                                         config['index']['badqual']))
    if "ACGTtrim" in stats:
        logger.info("%9d reads pairs clipped for not [A,C,G,T] bases" % stats["ACGTtrim"])
    
    if "bad_ids" in stats:
        logger.info("%9d reads pairs sorted out because of not corresponding ids" % stats["bad_ids"]) 
        
    
468 469 470 471 472 473
    
    r=Index('%s.odx/index'  % output)
            
    logger.info('Count of indexed reads: %d' % len(r))