vihgo.py 42.6 KB
Newer Older
Yannis Duffourd's avatar
Yannis Duffourd committed
1 2 3 4
#!/usr/bin/env python
# -*- coding: utf-8 -*-


5 6 7 8
#  ### GAD development file  ###
#  ## hiv_genotyping.py
#  ## Version : 1.0
#  ## Description : 
Yannis Duffourd's avatar
Yannis Duffourd committed
9
#  ## Usage : hiv_genotyping.py 
10 11 12 13 14
#  ## Output : 
#  ## Requirements : python 2.7+ - pySAM - scipy 
#  
#  ## Author: yannis.duffourd@u-bourgogne.fr
#  ## Creation Date: 2016-10-18
Yannis Duffourd's avatar
Yannis Duffourd committed
15
#  ## last revision date: 2018-03-29
16 17 18 19 20 21 22 23 24
#  ## Known bugs: None
#  ## TODO: 
#  

import os
import sys
import getopt
import logging
import math
Yannis Duffourd's avatar
Yannis Duffourd committed
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
import random
import string 


# pysam requirement
try:
	import pysam 
except ImportError:
	sys.stderr.write( "pysam library is required and was not found on your system. Please check PYTHONPATH, or install the library. Exiting.\n" )
	sys.exit( 1 )

# scipy requirement
try:
	from scipy import stats
except ImportError:
	sys.stderr.write( "scipy library is required and was not found on your system. Please check PYTHONPATH, or install the library. Exiting.\n" )
	sys.exit( 1 )
	
# plotly optional requirement
isGraphicalPossible = False
try:
	import plotly.plotly as py
	from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
	import plotly.graph_objs as go
	from plotly.graph_objs import Scatter, Figure, Layout
	isGraphicalPossible = True
except ImportError:
	sys.stderr.write( "plotly library is required and was not found on your system. Please check PYTHONPATH, or install the library. Continuing without graphical possibilities.\n" )

	
	
	
	
58 59

currentThread = 0
Yannis Duffourd's avatar
Yannis Duffourd committed
60 61 62 63 64 65
integraseFile , samFile , rtFile , proteaseFile , referenceFile , logFile , outputFile , allControlBamList , inRunControlBam , gtfFile , csFile = "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , ""

#  generate a temp hash for the file result
hsh = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(12))


66 67 68 69 70 71
depthThreshold = 200
ratioThreshold = 0
pvalueThreshold = 1.0
annotationIsDefined = False
nbThread = 1
countStop = False
Yannis Duffourd's avatar
Yannis Duffourd committed
72 73 74 75 76 77 78 79 80 81 82 83 84 85
graphical = False
loggingLevel = 1
referenceSequence = {}
referenceCodon = {}
knownMutationTable = {}
genes = {}
effectifTable = {}
totalAltSequencedBase = {}
protCodon = {}
bamCodon = {}
bamCodonReference = {}

# codon table 
codonTable = { "TTT":"F" , "TTC" : "F" , "TTA" : "L" , "TTG" : "L" , "CTT":"L" , "CTC":"L" , "CTA":"L" , "CTG":"L" , "ATT" : "I" , "ATC":"I" , "ATA":"I" , "ATG":"M" , "GTT":"V" , "GTC":"V" , "GTA":"V" , "GTG":"V" , "TCT":"S" , "TCC":"S" , "TCA":"S" , "TCG":"S" , "CCT":"P" , "CCC":"P" , "CCA":"P" , "CCG":"P", "ACT":"T" , "ACC":"T" , "ACA":"T" , "ACG":"T" , "GCT":"A" , "GCC":"A" , "GCA":"A" , "GCG":"A" , "TAT":"Y", "TAC":"Y" , "TAA":"*" , "TAG":"*" , "CAT":"H" , "CAC":"H" , "CAA":"Q" , "CAG" : "Q" , "AAT":"N" , "AAC":"N" , "AAA":"K" , "AAG":"K" , "GAT":"D" , "GAC":"D" , "GAA":"E" , "GAG":"E", "TGT":"C" , "TGC":"C" , "TGA":"*" , "TGG":"W" , "CGT":"R" , "CGC":"R" , "CGA":"R" , "CGG":"R" , "AGT":"S" , "AGC":"S" , "AGA":"R" , "AGG":"R" , "GGT":"G", "GGC":"G" , "GGA":"G", "GGG":"G" }
86

Yannis Duffourd's avatar
Yannis Duffourd committed
87 88
# we need to store some stuff for further statistical tests some values 
totalRefSequencedBase = {}
89

Yannis Duffourd's avatar
Yannis Duffourd committed
90
opts, args = getopt.getopt(sys.argv[1:], 's:i:r:p:R:D:l:P:o:c:b:a:n:SGe:L:g:C:')  
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
for opt, arg in opts:
	if opt in ("-i"):
		integraseFile = arg
	elif opt in ("-s"):
		samFile = arg
	elif opt in ("-r"):
		rtFile = arg
	elif opt in ("-p"):
		proteaseFile = arg
	elif opt in ("-R"):
		referenceFile = arg
	elif opt in ("-D"):
		depthThreshold = int(arg)
	elif opt in ("-l"):
		ratioThreshold = int(arg)
	elif opt in ("-P"):
		pvalueThreshold = float(arg)
	elif opt in ("-o"):
		outputFile = arg
	elif opt in ("-c"):
		codonResultFile = arg
Yannis Duffourd's avatar
Yannis Duffourd committed
112 113
	elif opt in ("-C"):
		csFile = arg
114 115
	elif opt in ("-b"):
		inRunControlBam = arg
Yannis Duffourd's avatar
Yannis Duffourd committed
116 117
	elif opt in ("-g"):
		gtfFile = arg
118 119 120 121 122 123 124
	elif opt in ("-a"):
		allControlBamList = arg
	elif opt in ("-n"):
		nbThread = int( arg )
	elif opt in ("-S"):
		countStop = True
		sys.stderr.write('Stop codon detection activated.')
Yannis Duffourd's avatar
Yannis Duffourd committed
125 126 127 128 129 130 131 132 133 134 135 136
	elif opt in ("-G"):
		if isGraphicalPossible : 
			sys.stderr.write('Graphical capabilities activated.')
			graphical = True
		else:
			sys.stderr.write('Warning : Unable to use graphical capabilities.')
			graphical = False
	elif opt in ("-e") :
		logFile = arg
	elif opt in ("-L") :
		loggingLevel = int( arg )
	
137

Yannis Duffourd's avatar
Yannis Duffourd committed
138 139 140 141 142 143 144 145 146 147 148
if logFile == "" :
	logging.basicConfig(stream = sys.stderr , filemode = 'w', level = logging.INFO, format = '%(asctime)s %(levelname)s - %(message)s')
else:	
	logging.basicConfig(filename =  logFile , filemode = 'w', level = logging.INFO, format = '%(asctime)s %(levelname)s - %(message)s')
logging.info('start')
	
# sample name
if samFile.find( "/" ) != -1 :
	sample = samFile.split( "/" ) [-1]
else:
	sample = samFile
149 150
sample = sample.replace( ".bam" , "" )
sample = sample.split( "." )[0]
Yannis Duffourd's avatar
Yannis Duffourd committed
151 152
logging.info( "Sample name detected : %s" % sample )

153

Yannis Duffourd's avatar
Yannis Duffourd committed
154
# codon output file name
155 156 157 158 159
if countStop == True :
	codonResultFile = "codons.stop.tsv" 
else:
	codonResultFile = "codons.tsv"

Yannis Duffourd's avatar
Yannis Duffourd committed
160
 
161 162 163
def phredToInt( incString ):
    # convert to ascii 
    score = ord( incString )
Yannis Duffourd's avatar
Yannis Duffourd committed
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
    # substract 33 to the score 
    score -= 33
    
    return score

def igf( lddl , chiStat ):
    if chiStat < 0.0:
		return 0.0
    
    sc = 1.0 / lddl
    sc *= chiStat**lddl
    sc *= math.exp( -chiStat )
    sys.stderr.write( "sc value = %s\n" % ( sc ) )
    
    somme = 1.0
    nom = 1.0
    denom = 1.0
    
    for i in range( 1 , 200):
		nom *= chiStat
		lddl += 1
		denom *= lddl
		somme += (nom / denom)
		
    if ( somme * sc ) < 0.000000000000001:
		sys.stderr.write( "igf value = %s\n" % (0.000000000000001) )
		return 0.000000000000001
    
    sys.stderr.write( "igf value = %s\n" % (somme * sc ) )
    return somme * sc
    
def gamma( lddl ):
    RECIP_E = 0.36787944117144232159552377016147
    TWOPI = 6.283185307179586476925286766559
    D = 1.0 / (10.0 * lddl)
    D = 1.0 / ((12 * lddl) - D)
    D = (D + lddl) * RECIP_E
    D = D**lddl
    D *= math.sqrt(TWOPI / lddl)
    
    
    sys.stderr.write( "gamma = %s\n" % D )
    return D

def adequationChiTwo( effectTable , localRef , localAlt  ):
    
    
    # compute deviation between obs & theoritical
    thMean = sum( effectTable ) / len( effectTable )
    obsMean = localAlt * 100 / ( float( localRef ) + float( localAlt  ) )
    
    
    if obsMean < thMean:
		return 1
    
    if obsMean == 100:
		obsMean = 99.99999
Yannis Duffourd's avatar
Yannis Duffourd committed
222
    logging.info( "Th mean : %s ; obsMean : %s\n" % ( thMean , obsMean ))
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 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 351 352 353 354 355 356 357
    
    refDev = ( ( (100 - obsMean) - (100 - thMean) )**2 ) /  (100 - obsMean)
    altDev = ( ( obsMean - thMean )**2 ) / obsMean
    ddl = 1
    qSquare = refDev + altDev
    alpha = 5
    
    sys.stderr.write( "X2 statistical value = %s\n" % qSquare )
    
    # with alpha = 5% and a ddl = 1, the confidence interval is [0;5.991] 
    # H0 is rejected if qSquare superior to  5.991 with a 5% error risk
    # so there is asignificant difference between the position wie observed and the rest of the reference. 
    # need to compute a p-value
    
    return pochisq( qSquare , 1 )
    
def pochisq(x, df) :
       
    LOG_SQRT_PI = 0.5723649429247000870717135
    I_SQRT_PI = 0.5641895835477562869480795

    if x <= 0.0 or df < 1 :
	return 1.0

    s = 2.0 * poz( - math.sqrt( x ) )
    
    sys.stderr.write( " p-value : %s\n" % s )
    return s
 
def poz(z) :
    sys.stderr.write( "Incoming z : %s\n" % z )

    y = 0 
    x = 0 
    w = 0
    Z_MAX = 6.0          

    if z == 0.0 :
		x = 0.0
    else :
		y = 0.5 * abs(z)
		
		if (y >= (Z_MAX * 0.5)): 
			x = 1.0
		elif y < 1.0 :
			w = y * y
			x = ((((((((0.000124818987 * w - 0.001075204047) * w + 0.005198775019) * w - 0.019198292004) * w + 0.059054035642) * w
				 - 0.151968751364) * w + 0.319152932694) * w - 0.531923007300) * w + 0.797884560593) * y * 2.0
		else :
			y -= 2.0
			x = (((((((((((((-0.000045255659 * y + 0.000152529290) * y - 0.000019538132) * y - 0.000676904986) * y + 0.001390604284) * y -   0.000794620820) * y - 0.002034254874) * y + 0.006549791214) * y - 0.010557625006) * y + 0.011630447319) * y - 0.009279453341) * y + 0.005353579108) * y - 0.002141268741) * y + 0.000535310849) * y + 0.999936657524
		
	
    if z > 0.0 :
		sys.stderr.write( "Output : %s\n" % ((x + 1.0) * 0.5) )
		return ((x + 1.0) * 0.5)
    else:
		sys.stderr.write( "Output : %s\n" % ((1.0 - x) * 0.5) )
		return ((1.0 - x) * 0.5)

# need the bam already parsed to be used.
def getEffectiveTable( ref , excludeList ):
    localEffectifTable = []
    for position in bamCodon[ref].keys():
	
		# pass the position if new as a mutation
		if position in excludeList:
			continue
			
		totalOnPos = 0
		totalAltOnPos = 0

		refAA = codonTable[ referenceCodon[ref][position] ]
		for codon in bamCodon[ref][position].keys():
			totalOnPos += bamCodon[ref][position][codon]
			obsAA = codonTable[ codon ]
			
			if obsAA != refAA:
				totalAltOnPos += bamCodon[ref][position][codon]

		if totalAltOnPos == 0:
			localEffectifTable.append( 0 )
			#~ sys.stderr.write( "Adding 0 to %s effectives for pos : %s \n" % ( ref , position ) )
		else:
			localEffectifTable.append( totalAltOnPos * 100 / float( totalOnPos ) )
			#~ sys.stderr.write( "Adding %s to %s effectives for pos : %s \n" % ( totalAltOnPos * 100 / float( totalOnPos ) , ref , position ) )
			
    return localEffectifTable

# compute factoriel
def fact(n):
    """fact(n): calcule la factorielle de n (entier >= 0)"""
    if n<2:
        return 1
    else:
        return n*fact(n-1)

# compute log factoriel
def logFactoriel( inc ):
    ret = 0
    while inc > 0:
		ret += math.log( inc )
		inc -= 1
    return ret;

# compute log of hypergeometrique for FET
def logHypergeometricProb( a ,  b , c  , d ):
    return logFactoriel( a + b ) + logFactoriel( c + d ) + logFactoriel( a + c ) + logFactoriel( b + d )- logFactoriel( a ) - logFactoriel( b ) - logFactoriel( c ) - logFactoriel( d ) - logFactoriel( a + b + c + d )

# compute pvalue from FET
def FETPvalue( a , b , c, d ):
	#sys.stderr.write( "Computing a p-value from FET ..." )
	n = a + b + c + d 
	logpCutOff = logHypergeometricProb( a , b , c , d )
	pFraction = 0
	logpValue = 0
	
	for x in range( 0 , n ):
		if( ( a + b - x >= 0 ) and ( a + c - x >= 0 ) and ( d - a + x >= 0 ) ) :
			l = logHypergeometricProb( x , a + b - x , a + c - x , d - a + x )
			if  l <= logpCutOff :
				pFraction += math.exp( l - logpCutOff )

	logpValue = logpCutOff + math.log( pFraction )
	#sys.stderr.write( " done \n" )
	return math.exp(logpValue);

# determine if a codon is a stop or not
def isStop( incCodon ):
	stopList = [ "TAG" , "TAA" , "TGA" ]
	if incCodon in stopList :
		return True 
	else:
		return False

Yannis Duffourd's avatar
Yannis Duffourd committed
358 359 360 361 362 363 364 365 366
# compute the complement of a sequence
def complement( incCodon ):
	t = {"A":"T" , "T":"A" , "G":"C" ,"C":"G" }
	s = ""
	incCodon = incCodon.upper()
	for i in incCodon:
		s += t[i]
	return s
	
367
# deal with the ref genome
Yannis Duffourd's avatar
Yannis Duffourd committed
368 369 370 371 372 373 374 375
def get_genome():
	logging.info( "Starting genome parsing" )
	
	referenceStream = open( referenceFile , "r" )
	currentChr = ""
	i = 1
	for line in referenceStream:
		# name of the sequence
376
		line = line.strip()
Yannis Duffourd's avatar
Yannis Duffourd committed
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
		if line.startswith( ">" ):
			line = line.replace( ">" , "" )
			line = line.split( " " )[0]
			currentChr = line
			referenceSequence[line] = {}
			logging.info( "New reference sequence detected : %s." % currentChr )
		else:
			for base in line:
				referenceSequence[currentChr][i] = base
				i += 1
	referenceStream.close()
	
	logging.info( "Genome summary : \n" )
	for chr in referenceSequence.keys():
		logging.info("\t%s\t%s" % ( chr , len(referenceSequence[chr] )) )
	logging.info( "Ending genome parsing." )

# codon table for each genes. 
def get_genes():
	# parse the gtf file to get every cds 
	# warning : need to deal with genes in reverse ... 
	logging.info( "Starting genes parsing." )
	
	for line in open( gtfFile , 'r' ):
		line = line.strip()
		if line.split( "\t" )[0] not in referenceSequence.keys() :
403
			continue
Yannis Duffourd's avatar
Yannis Duffourd committed
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
		if line.split( "\t" )[2] == "CDS" :
			a = line.split( "\t" )[8] 
			aTable = a.split( ";" )
			for elt in aTable :
				if elt.startswith( "protein_id" ):
					g = elt.split( "=" )[1]
					g = g.replace( '"' , '' )
					if g not in genes.keys():
						genes[g] = {}
						referenceCodon[g] = {}
						genes[g]["start"] = []
						genes[g]["end"] = []
						genes[g]["strand"] = ""
						genes[g]["chrom"] = line.split( "\t" )[0]
						
						
					genes[g]["start"].append( int( line.split( "\t" )[3] ) )
					genes[g]["end"].append( int( line.split( "\t" )[4] ) )
					genes[g]["strand"] = line.split( "\t" )[6]	
						
	# get codon from reference
	for g in genes.keys():
		logging.info( "Getting codons for gene : %s" % g )
	
		codon = ""
		chrom = genes[g]["chrom"]
		logging.info( "\tchrom is %s" % chrom )
		if genes[g]["strand"] == "+" :
			logging.info( "\tstrand is +" )
			posList = referenceSequence[chrom].keys()
			posList.sort()
			for pos in posList:
				for start,end in zip(genes[g]["start"],genes[g]["end"]) :
					if (pos >= start) and (pos <= end) :
						codon += referenceSequence[chrom][pos]
						if (len(codon) % 3 == 0) and (len(codon) != 0 ) :
							codon = codon.upper()
							referenceCodon[g][(pos-3)+1] = codon
							# ~ referenceCodon[g][(pos-3)] = codon
							codon = ""
					
		if genes[g]["strand"] == "-" :
			logging.info( "\tstrand is -" )
			posList = referenceSequence[chrom].keys()	
			posList.sort()
			posList.reverse()
			for pos in	posList :
				for start,end in zip(genes[g]["start"],genes[g]["end"]) :
					if (pos >= start) and (pos <= end) :
						codon += referenceSequence[chrom][pos]
						if (len(codon) % 3 == 0) and (len(codon) != 0 ) :
							codon = codon.upper()
							referenceCodon[g][(pos+3)+1] = complement(codon)
							# ~ referenceCodon[g][(pos+3)] = complement(codon)
							codon = ""
						
				
				
				
				
	logging.info( "Genes content : " )
465
	
Yannis Duffourd's avatar
Yannis Duffourd committed
466 467 468 469 470
	for g in referenceCodon.keys():
		posList = referenceCodon[g].keys()
		posList.sort()
		for pos in posList:
			logging.info( "%s\t%s\t%s" % ( g , pos , referenceCodon[g][pos] ) )
471 472 473
			
	
	
Yannis Duffourd's avatar
Yannis Duffourd committed
474 475 476 477 478 479 480 481 482
	# conversion to the protein numbers 
	for g in referenceCodon.keys():
		protCodon[g] = {}
		i = 1
		posList = referenceCodon[g].keys()	
		posList.sort()
		for pos in posList :
			protCodon[g][pos] = i
			i += 1
483

Yannis Duffourd's avatar
Yannis Duffourd committed
484 485 486 487 488 489 490 491
	logging.info( "/ conversion : " )
	for g in protCodon.keys():
		posList = protCodon[g].keys()	
		posList.sort()
		for pos in posList:
			logging.info( "%s\t%s\t%s" % ( g , pos , protCodon[g][pos] ) )
	
	
492
		
Yannis Duffourd's avatar
Yannis Duffourd committed
493
	logging.info( "Ending genes parsing." )
494
		
Yannis Duffourd's avatar
Yannis Duffourd committed
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
def display_reference_codon():
	w = open( "referenceCodon.tsv" , "w" )
	w.write( "##### Ref codons : #####\n" ) 
	for g in referenceCodon.keys():
		for pos in sorted(referenceCodon[g].keys()):
			w.write( "\t%s : %s : %s \n" % (g, pos , referenceCodon[g][pos]))	
	w.close()

def display_prot_codon():
	w = open( "protCodon.tsv" , "w" )
	w.write( "##### Prot codons : #####\n" ) 
	for g in protCodon.keys():
		for pos in sorted(protCodon[g].keys()):
			w.write( "\t%s : %s : %s \n" % (g, pos , protCodon[g][pos]))	
	w.close()

def display_bam_codon():
512
	
Yannis Duffourd's avatar
Yannis Duffourd committed
513 514 515 516 517 518 519
	w = open( "bamCodon.tsv" , "w" )
	w.write( "###### bam codons ######\n")
	for a in bamCodon.keys():
		for b in sorted(bamCodon[a].keys()):
			for c in bamCodon[a][b].keys():
				w.write( "%s %s %s %s\n" % ( a , b , c , bamCodon[a][b][c] ) )
	w.close()
520
	
Yannis Duffourd's avatar
Yannis Duffourd committed
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
def display_bam_ref_codon():
	
	w = open( "bamRefCodon.tsv" , "w" )
	w.write( "###### bam codons ######\n")
	for a in bamCodonReference.keys():
		for b in sorted(bamCodonReference[a].keys()):
			for c in bamCodonReference[a][b].keys():
				w.write( "%s %s %s %s\n" % ( a , b , c , bamCodonReference[a][b][c] ) )
	w.close()

def display_bam_reference_codon():
	
	w = open( "bamCodonReference.tsv" , "w" )
	w.write( "###### bam codons ######\n")
	for a in bamCodonReference.keys():
		for b in sorted(bamCodonReference[a].keys()):
			for c in bamCodonReference[a][b].keys():
				w.write( "%s %s %s %s\n" % ( a , b , c , bamCodonReference[a][b][c] ) )
	w.close()

def get_annotation():
	logging.info( "Starting genotype tables parsing" )
	logging.info( "Starting %s parsing" % integraseFile )
	global annotationIsDefined
	if integraseFile != "":
		annotationIsDefined = True
		refFound = False
		# parse & store genotyping files   
		integraseStream = open( integraseFile,  "r" )
		for line in integraseStream:
			if line.startswith( " " ) or line.startswith( "Position" ) or line.startswith( "AA" ) or  len(line) < 10:
				continue
			
			if line.startswith( "#" ) :
				temp = line.strip().split( "#" )
				ref = temp[1]
				knownMutationTable[ref] = {}
				refFound = True
				continue
560
		
Yannis Duffourd's avatar
Yannis Duffourd committed
561 562 563 564 565 566 567 568 569 570
			if not refFound :
				logging.error( "Error : %s file is malformed. Please redo the analysis without it or correct the file (see doc at http://blabla.html)\n" % integraseFile )
				sys.exit( 1 )
				
			lineTable = line.strip().split( "\t" )
			index = lineTable[2] + lineTable[0] + lineTable[4]
			if loggingLevel >= 3:
				logging.info( "index : %s" % index )
			if lineTable[2] == lineTable[4]:
				continue
571
		
Yannis Duffourd's avatar
Yannis Duffourd committed
572 573 574 575 576 577
			knownMutationTable[ref][index] = lineTable[5]
		
		integraseStream.close()
		logging.info( "\tINTEGRASE : OK\n" )
	else:
		logging.info( "\tINTEGRASE : no file provided" )
578

Yannis Duffourd's avatar
Yannis Duffourd committed
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
	logging.info( "Starting %s parsing" % rtFile )
	if rtFile != "":
		annotationIsDefined = True
		refFound = False
		# parse & store genotyping files
		
		reverseTranscriptaseStream = open( rtFile,  "r" )
		for line in reverseTranscriptaseStream:
			if line.startswith( " " ) or line.startswith( "Position" ) or line.startswith( "AA" ) or  len(line) < 10:
				continue
			
			if line.startswith( "#" ) :
				temp = line.strip().split( "#" )
				ref = temp[1]
				knownMutationTable[ref] = {}
				refFound = True
				continue
			
			if not refFound :
				logging.error( "Error : %s file is malformed. Please redo the analysis without it or correct the file (see doc at http://blabla.html)\n" % rtFile )
				sys.exit( 1 )
			lineTable = line.strip().split( "\t" )
			index = lineTable[2] + lineTable[0] + lineTable[4]
			if loggingLevel >= 3:
				logging.info( "index : %s" % index )
			if lineTable[2] == lineTable[4]:
				continue
			knownMutationTable[ref][index] = lineTable[5]
		
		reverseTranscriptaseStream.close()
		logging.info( "\tREVERSETRANSCRIPTASE : OK\n" )
	else:
		logging.info( "\tREVERSETRANSCRIPTASE : no file provided\n" )
612

Yannis Duffourd's avatar
Yannis Duffourd committed
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
	logging.info( "Starting %s parsing" % proteaseFile )
	if proteaseFile != "":
		annotationIsDefined = True
		refFound = False
		# parse & store genotyping files
		
		proteaseStream = open( proteaseFile,  "r" )
		for line in proteaseStream:
			if line.startswith( " " ) or line.startswith( "Position" ) or line.startswith( "AA" ) or  len(line) < 10:
				continue
			
			if line.startswith( "#" ) :
				temp = line.strip().split( "#" )
				ref = temp[1]
				knownMutationTable[ref] = {}
				refFound = True
				continue
			
			if not refFound :
				logging.error( "Error : %s file is malformed. Please redo the analysis without it or correct the file (see doc at http://blabla.html)\n" % proteaseFile )
				sys.exit( 1 )
			lineTable = line.strip().split( "\t" )
			index = lineTable[2] + lineTable[0] + lineTable[4]
			if loggingLevel >= 3:
				logging.info( "index : %s" % index )
			if lineTable[2] == lineTable[4]:
				continue
			knownMutationTable[ref][index] = lineTable[5]
		
		proteaseStream.close()
		logging.info( "\tPROTEASE : OK\n" )
	else:
		logging.info( "\tPROTEASE : no file provided\n" )
	   
	logging.info( "Genotype tables parsing done\n" )
648

Yannis Duffourd's avatar
Yannis Duffourd committed
649 650
	resultTable = {}
	qualityTable = {}
651

Yannis Duffourd's avatar
Yannis Duffourd committed
652 653 654
	resultTable["ReverseTranscriptase"] = {}
	resultTable["Protease"] = {}
	resultTable["Integrase"] = {}
655

Yannis Duffourd's avatar
Yannis Duffourd committed
656 657 658
	qualityTable["ReverseTranscriptase"] = {}
	qualityTable["Protease"] = {}
	qualityTable["Integrase"] = {}
659 660

###### deal with inRunControlBam 
Yannis Duffourd's avatar
Yannis Duffourd committed
661 662 663 664 665 666 667 668 669 670
def read_inRunControl():
	global bamCodonReference
	logging.info( "Starting bam control file parsing : %s" % ( inRunControlBam ) )
	bamIterRef = pysam.AlignmentFile( inRunControlBam , "r" )
	bamCodonReference = {}
	# samStream = open( samFile , "r" )
	countLine = 0
	for line in bamIterRef:
		if ( countLine != 0 ) and (countLine % 200000 == 0 ):
			logging.info( "%s aln read\n" % countLine ) 
671 672
		
		
Yannis Duffourd's avatar
Yannis Duffourd committed
673 674 675 676 677 678 679
		if loggingLevel >= 3:
			logging.info('New read to parse : %s' % str(line) )
		# pass bad alignements
		if (line.is_unmapped == True ) or (line.is_secondary == True ) or (line.is_supplementary == True) or (int(line.mapping_quality) < 30) :
			if loggingLevel >= 3:
				logging.info('Passing sequence : bad quality ' )
			continue
680

Yannis Duffourd's avatar
Yannis Duffourd committed
681 682 683 684 685
		# get position and ref 
		ref = line.reference_name
		position = int( line.reference_start) + 1
		sequence = line.query_sequence
		quality = line.query_qualities
686
		
Yannis Duffourd's avatar
Yannis Duffourd committed
687 688 689 690 691
		# non aligned reads, theoritically unreachable because tested before
		if ref == "*" :
			if loggingLevel >= 3:
				logging.info('Passing sequence : not aligned : %s ' % ref )
			continue
692
			
Yannis Duffourd's avatar
Yannis Duffourd committed
693 694 695 696 697 698 699 700
				
		# test CIGAR string : if insertion or deletion, we skip the read
		cigar = line.cigarstring
		
		if "I" in cigar or "H" in cigar or "S" in cigar or "D" in cigar:
			if loggingLevel >= 3:
				logging.info('Passing sequence : CIGAR contains a special event : %s ' % cigar )
			continue
701
			
Yannis Duffourd's avatar
Yannis Duffourd committed
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
		currentPosition = position

		i = 0 
		countLine += 1
		# browse every codons, but need to determine if the first codon is complete or not
		while ( i < len(sequence) ) and (i + 3 <= len( sequence ) ) :
			complete = False
			for g in genes.keys():
				for start,end in zip(genes[g]["start"],genes[g]["end"]) :
					if currentPosition >= start and currentPosition <= end : 
						# manage new chr encounters 
						if not bamCodonReference.has_key( g ):
							logging.info('New gene found in data : %s' % g )
							bamCodonReference[g] = {}
						
						
718
			
Yannis Duffourd's avatar
Yannis Duffourd committed
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
						if protCodon[g].has_key( currentPosition ):
							complete =  True
							codon = sequence[i:i + 3]
							codon = codon.upper()
							if loggingLevel >= 3:
								logging.info('Adding a codon on ' + g + ' : pos on read : ' + str(i) + ' ; pos on ref : ' + str( currentPosition ) + ' ; codon : ' + codon + '(' + str(((currentPosition-start)/3)+1 ) + ')' )
							qualityCodon = quality[i:i+3]
							qualityScore = 0
							takeIt = 1
							for base in qualityCodon:
								qualityScore += int( base )
								if int(base) < 30 :
									takeIt = 0
								
								if takeIt == 1:
									if not bamCodonReference[g].has_key(((currentPosition-start)/3)+1 ):
										bamCodonReference[g][((currentPosition-start)/3)+1] = {}
									if not bamCodonReference[g][((currentPosition-start)/3)+1].has_key( codon ):
										bamCodonReference[g][((currentPosition-start)/3)+1][codon] = 0
									bamCodonReference[g][((currentPosition-start)/3)+1][codon] += 1
							
						else:
							complete = False
							
			if complete : 
				i += 3 
				currentPosition += 3 
			else:
				# codon is not complete
				if loggingLevel >= 3:
					logging.info('Not on a 1st base, passing to next base : pos on read : ' + str(i) + ' ; pos on ref : ' + str( currentPosition )  )
				i += 1
				currentPosition += 1 
752
			
Yannis Duffourd's avatar
Yannis Duffourd committed
753
	logging.info( "Parsing done with %s aln treated\n" % countLine )
754

Yannis Duffourd's avatar
Yannis Duffourd committed
755 756 757 758 759 760
def read_sample():
	############ deal with bam file
	logging.info( "Parsing bam file : %s ..." % ( samFile ) )
	# ~ logging.info( "Starting bam file parsing : %s" % ( samFile ) )
	bannedReadID = []
	countLine = 0
761

Yannis Duffourd's avatar
Yannis Duffourd committed
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
	bamIter = pysam.AlignmentFile( samFile , "r" )
	global bamCodon
	
	#samStream = open( samFile , "r" )

	for line in bamIter:
		if loggingLevel >= 3:
			logging.info('New read to parse : %s' % str(line) )
		# pass bad alignements
		if (line.is_unmapped == True ) or (line.is_secondary == True ) or (line.is_supplementary == True) or (int(line.mapping_quality) < 30) :
			if loggingLevel >= 3:
				logging.info('Passing sequence : bad quality ' )
			continue
		
		# pass stop pairs if activated
		if line.query_name in bannedReadID :
			# ~ sys.stderr.write( 'Passing sequence : stop in pair \n' ) 
			continue
780

Yannis Duffourd's avatar
Yannis Duffourd committed
781 782 783 784 785 786 787 788 789 790 791 792
		# get position and ref 
		ref = line.reference_name
		position = int( line.reference_start) + 1
		sequence = line.query_sequence
		quality = line.query_qualities
		
		# non aligned reads, theoritically unreachable because tested before
		if ref == "*" :
			if loggingLevel >= 3:
				logging.info('Passing sequence : not aligned : %s ' % ref )
			continue
		
793

Yannis Duffourd's avatar
Yannis Duffourd committed
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
		
		#~ sys.stderr.write( "%s\n" % refTable )
		
		# test CIGAR string : if insertion or deletion, we skip the read
		cigar = line.cigarstring
		
		if "I" in cigar or "H" in cigar or "S" in cigar or "D" in cigar:
			if loggingLevel >= 3:
				logging.info('Passing sequence : CIGAR contains a special event : %s ' % cigar )
			continue
		
		
		# manage deletion 
		# ~ positionOfDel = 0 
		# ~ lengthOfDel = 0
		# ~ if "D" in cigar:
			# ~ #logging.info('Passing sequence : Deletion detected : ' + cigar + " ; sequence : " + sequence )
			
			# ~ # get position of the del in the read and its size
			# ~ for elt in line.cigartuples:
				# ~ if elt[0] == 2 :
					# ~ lengthOfDel = elt[1]
					# ~ break
				# ~ if elt[0] == 0:
					# ~ positionOfDel += elt[1]
			
820

Yannis Duffourd's avatar
Yannis Duffourd committed
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
		currentPosition = position
		# extract codon sequences
		i = 1 
		
		# browse the sequence to look for stop codon if stop analysis detected 
		takeSequence = True
		
		## need a full rewamp of the stop detection ####
		# ~ if countStop:
			# ~ while i < len(sequence) :
				# ~ if i + 3 > len( sequence ):
					# ~ break
				# ~ if currentPosition % 3 == 0 or currentPosition == 1:
					# ~ codon = sequence[i:i + 3]
					# ~ codon = codon.upper()
					# ~ if isStop( codon ):
						# ~ takeSequence = False
						# ~ bannedReadID.append( line.query_name )
						# ~ break
					# ~ i += 3
					# ~ currentPosition += 3 
				# ~ else:
					# ~ i += 1
					# ~ currentPosition += 1 
		#################################################
		
		countLine += 1
		currentPosition = position
		# browse every codons, but need to determine if the first codon is complete or not
		if takeSequence :
			i = 0 
			# deal with end of sequence
			while ( i < len(sequence) ) and (i + 3 <= len( sequence ) ) :
				# detect the gene 
				complete = False
				for g in genes.keys():
					for start,end in zip(genes[g]["start"],genes[g]["end"]) :
						if currentPosition >= start and currentPosition <= end : 
							# manage new gene encounters 
							if not bamCodon.has_key( g ):
								logging.info('New reference found : %s' % g )
								bamCodon[g] = {}
									
							# codon is complete
							if protCodon[g].has_key( currentPosition ):
								complete = True
								codon = sequence[i:i + 3]
								codon = codon.upper()
								if loggingLevel >= 3:
									logging.info('Adding on ' + g + ' : pos on read : ' + str(i) + ' ; pos on ref : ' + str( currentPosition ) + ' ; codon : ' + codon + '(' + str(((currentPosition-start)/3)+1 ) + ')' )
								qualityCodon = quality[i:i+3]
								qualityScore = 0
								takeIt = 1
								for base in qualityCodon:
									qualityScore += int( base )
									if int(base) < 30 :
										takeIt = 0
								
								if takeIt == 1:
									if not bamCodon[g].has_key(((currentPosition-start)/3)+1 ):
										bamCodon[g][((currentPosition-start)/3)+1] = {}
									if not bamCodon[g][((currentPosition-start)/3)+1].has_key( codon ):
										bamCodon[g][((currentPosition-start)/3)+1][codon] = 0
									bamCodon[g][((currentPosition-start)/3)+1][codon] += 1
														
							else:
								# codon is not complete
								complete = False
								
				
				if complete :
					i += 3 
					currentPosition += 3 
				else:		
					if loggingLevel >= 3:
						logging.info('Not on a 1st base, passing to next base : pos on read : ' + str(i) + ' ; pos on ref : ' + str( currentPosition ) )
					i += 1
					currentPosition += 1 

	logging.info( " done with %s aln kept\n" % countLine )
	logging.info( "%s sequence discarded due to stop codon.\n" % len( bannedReadID ) )


def get_aa( g , ppos  ):
	gpos = 0 
	# get the genomic position 
	for elt in protCodon[g].keys():
		if ( protCodon[g][elt] == ppos ):
			gpos = elt
			break
			
	# verify
	if gpos == 0:
		logging.error( "Error : submitted position not in the reference. Please check data consistency\n" )
915
	
Yannis Duffourd's avatar
Yannis Duffourd committed
916 917
	# get the codon 
	codon = referenceCodon[g][gpos] 
918 919 920 921
	
	
	
	
Yannis Duffourd's avatar
Yannis Duffourd committed
922 923
	# get the aa
	aa = codonTable[codon] 
924 925
	
	
Yannis Duffourd's avatar
Yannis Duffourd committed
926 927 928 929
	# ~ sys.stderr.write( "Gene : %s ; genomic pos : %s ; proteic pos : %s ; codon : %s ; aa : %s\n" % ( g , gpos , ppos , codon , aa ) )
	
	
	return aa 
930 931

	
Yannis Duffourd's avatar
Yannis Duffourd committed
932 933 934 935
def get_gpos_from_ppos( g,  ppos ):
	for elt in protCodon[g].keys():
		if ( protCodon[g][elt] == ppos ):
			gpos = elt
936 937
			break
			
Yannis Duffourd's avatar
Yannis Duffourd committed
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
	# verify
	if gpos == 0:
		logging.error( "Error : submitted position not in the reference. Please check data consistency\n" )
	
	return gpos
	

# let's modelize the background noise
def modelize_noise():
	global bamCodon
	# count codons wich are not the reference
	logging.info( "Counting codons ... " )
	for ref in bamCodon.keys():
		# ~ sys.stderr.write( "\ton ref %s\n" % ref )
		outStream = open( sample + "/" + sample + "." + ref + ".percent.data" , "w" )
		noiseTable = {}
		for position in bamCodon[ref].keys():
			# ~ sys.stderr.write( "\t\ton p.pos %s\n" % position )
			totalOnPos = 0
			if not noiseTable.has_key( position ):
				noiseTable[position] = {}
959
			
Yannis Duffourd's avatar
Yannis Duffourd committed
960 961 962
			#  position is in prot. 
			# We need to convert to a g position
			refAA = get_aa( ref , position )
963
			
Yannis Duffourd's avatar
Yannis Duffourd committed
964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
			for codon in bamCodon[ref][position].keys():
				# ~ sys.stderr.write( "\t\t\ton codon %s\n" % codon )
				totalOnPos += bamCodon[ref][position][codon]
				obsAA = codonTable[ codon ]
				
				if obsAA != refAA:
					if not noiseTable[position].has_key( obsAA ):
						noiseTable[position][obsAA] = 0
					noiseTable[position][obsAA] += bamCodon[ref][position][codon]
				
		# we have all data for counting
			for aa in noiseTable[position].keys():
				noiseTable[position][aa] = noiseTable[position][aa] * 100 / float(totalOnPos)

		listofAA = list( set( codonTable.values() ) )
		outStream.write( "#position\t%s\n" % "\t".join( listofAA ) )
		for position in noiseTable.keys():
			outStream.write( "%s" % position )
			for a in listofAA : 
				if noiseTable[position].has_key( a ):
					outStream.write( "\t%s" % noiseTable[position][a] )
				else:
					outStream.write( "\t0" )
			outStream.write( "\n" )
		outStream.close()
	sys.stderr.write( " done\n " )
	
	# count codons wich are not the reference
	logging.info( "Modelizing background noise  ... " )

	for ref in bamCodon.keys():
		totalRefSequencedBase[ref] = 0
		totalAltSequencedBase[ref] = 0
		bigTotal = 0
		noiseTable = {}
		if not noiseTable.has_key( ref ):
			noiseTable[ref] = {}  
		outStream = open( sample + "/" + sample + "." + ref + ".value.data" , "w" )
		
		for position in bamCodon[ref].keys():
			totalOnPos = 0
			totalAltOnPos = 0
1006
			
Yannis Duffourd's avatar
Yannis Duffourd committed
1007 1008
			if not noiseTable[ref].has_key( position ):
				noiseTable[ref][position] = {}
1009
			
Yannis Duffourd's avatar
Yannis Duffourd committed
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
			refAA = get_aa( ref , position )
			for codon in bamCodon[ref][position].keys():
				totalOnPos += bamCodon[ref][position][codon]
				bigTotal += bamCodon[ref][position][codon]
				obsAA = codonTable[ codon ]
				
				if obsAA != refAA:
					if not noiseTable[ref][position].has_key( obsAA ):
						noiseTable[ref][position][obsAA] = 0
					noiseTable[ref][position][obsAA] += bamCodon[ref][position][codon]
					totalAltSequencedBase[ref] += bamCodon[ref][position][codon]
					totalAltOnPos += bamCodon[ref][position][codon]
1022
			
Yannis Duffourd's avatar
Yannis Duffourd committed
1023
			#~ sys.stderr.write( "Position : %s , Ref : %s ,  Alt : %s , Total : %s \n" % ( position , totalOnPos - totalAltOnPos , totalAltOnPos , totalOnPos ) )
1024
					
Yannis Duffourd's avatar
Yannis Duffourd committed
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
			totalRefSequencedBase[ref] += bigTotal - totalAltSequencedBase[ref]
		
		listofAA = list( set( codonTable.values() ) )
		outStream.write( "#position\t%s\n" % "\t".join( listofAA ) )
		for position in noiseTable[ref].keys():
			outStream.write( "%s" % position )
			for a in listofAA : 
				if noiseTable[ref][position].has_key( a ):
					outStream.write( "\t%s" % noiseTable[ref][position][a] )
				else:
					outStream.write( "\t0" )
			outStream.write( "\n" )
		outStream.close()
	logging.info( " done\n " )
1039

Yannis Duffourd's avatar
Yannis Duffourd committed
1040 1041 1042 1043 1044 1045 1046
# calculate distributions 
def compute_distribution():
	sys.stderr.write( "Computing distribution  ... " )
	for ref in bamCodon.keys():
		sys.stderr.write( "Calculating distribution for %s \n" % ref )
		incStream = open( sample + "/" + sample + "." + ref + ".value.data" , "r" )
		contingencyTable = {}
1047
		
Yannis Duffourd's avatar
Yannis Duffourd committed
1048 1049 1050 1051 1052
		for line in incStream : 
			#sys.stderr.write( "%s" % line )
			if line.startswith( "#position" ):
				continue
			myTable = line.split( "\t" )
1053
			
Yannis Duffourd's avatar
Yannis Duffourd committed
1054 1055 1056 1057 1058
			for elt in myTable[1:]:
				i_elt = int( elt )
				if not contingencyTable.has_key( i_elt ):
					contingencyTable[i_elt] = 0
				contingencyTable[i_elt] += 1
1059
		
Yannis Duffourd's avatar
Yannis Duffourd committed
1060 1061 1062
		totalSum = 0
		for elt in contingencyTable.keys():
			totalSum += contingencyTable[elt]
1063
		
Yannis Duffourd's avatar
Yannis Duffourd committed
1064 1065 1066 1067
		# calculate probabilities
		for elt in contingencyTable.keys():
			tmp = contingencyTable[elt]
			contingencyTable[elt] = tmp / float( totalSum )
1068 1069
		
		
Yannis Duffourd's avatar
Yannis Duffourd committed
1070 1071 1072 1073 1074
		outStream = open( sample + "/" + sample + "." + ref+".value.density" , "w" )
		outStream.write( "#value\tcount\n" )
		for elt in contingencyTable.keys():
			outStream.write( "%s\t%s\n" % ( elt , contingencyTable[elt] ) )
		outStream.close()
1075
		
Yannis Duffourd's avatar
Yannis Duffourd committed
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
	sys.stderr.write( " done\n " )


def variant_calling():
	global bamCodon
	global bamCodonReference
	# detect the potential background noise 
	a = 0
	b = 1
	turn = 1
	positionToDiscard = []
	bg = {}
	while b != 0:
		bg = {}
		bgEff = {}
		b = 0
1092
		
Yannis Duffourd's avatar
Yannis Duffourd committed
1093
		logging.info( "BG estimation : turn %s\n" % turn )
1094
		
Yannis Duffourd's avatar
Yannis Duffourd committed
1095 1096 1097 1098 1099 1100 1101 1102 1103
		# first : get data for chisquare test
		for ref in bamCodon.keys():
			if loggingLevel >= 3:
				logging.info( "\tOn ref : %s\n" % ref )
			altCount = []
			refCount = []
			if not bg.has_key( "ref" ):
				bg[ref] = []
				bgEff[ref] = []
1104

Yannis Duffourd's avatar
Yannis Duffourd committed
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
			
			for position in bamCodon[ref].keys():
				if loggingLevel >= 3:
					logging.info( "\t\tOn pos : %s\n" % position )
				positionAltCount = 0
				positionTotalCount = 0
				if position in positionToDiscard:
					logging.info( "discarded pos : %s Passing \n" % position ) 
					continue
				
1115
				
Yannis Duffourd's avatar
Yannis Duffourd committed
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
				for codon in bamCodon[ref][position].keys():
					positionTotalCount += bamCodon[ref][position][codon]
				# ~ sys.stderr.write( "On %s : pos %s , totalD : %s\n" % ( ref , position , positionTotalCount ) )

				for codon in bamCodon[ref][position].keys():
					if loggingLevel >= 3:
						logging.info( "\t\t\tOn codon : %s\n" % codon )
					gpos = get_gpos_from_ppos( ref, position )
					refCodon = referenceCodon[ref][gpos]
					if codon != refCodon :
						positionAltCount = bamCodon[ref][position][codon]
						if loggingLevel >= 3:
							logging.info( "On %s : pos %s , alt : %s ; %s vs %s \n" % ( ref , position , positionAltCount , refCodon , codon ) )
						bg[ref].append( positionAltCount / float( positionTotalCount ) )
						
				if positionAltCount > positionTotalCount :
					logging.critical( "Critical error : more alt allele than the total on position %s\n" % position )
					sys.exit( 1 )
					
				altCount.append( positionAltCount )
				refCount.append( positionTotalCount )
1137
			
Yannis Duffourd's avatar
Yannis Duffourd committed
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
		
		
		
		
			if len( altCount ) == 0 :
				logging.error( "Error : all position (alt) excluded on ref %s\n" % ref )
				continue
				
			if len( refCount ) == 0 :
				logging.error( "Error : all position (ref) excluded on ref %s\n" % ref )
1148 1149
				continue
			
Yannis Duffourd's avatar
Yannis Duffourd committed
1150 1151 1152
			bgEff[ref].append( sum( altCount ) / len( altCount ) )
			bgEff[ref].append( sum( refCount ) / len( refCount ) )
			logging.info( "%s : %s , %s\n" % ( ref , bgEff[ref][0] , bgEff[ref][1] ) )
1153
			
Yannis Duffourd's avatar
Yannis Duffourd committed
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
		# now redo a loop to find mutations
		for ref in bamCodon.keys():
			for position in bamCodon[ref].keys():
				positionAltCount = 0
				positionTotalCount = 0
				if position in positionToDiscard:
					continue

				for codon in bamCodon[ref][position].keys():
					positionTotalCount += bamCodon[ref][position][codon]
				
				
				for codon in bamCodon[ref][position].keys():
					gpos = get_gpos_from_ppos( ref , position )
					refCodon = referenceCodon[ref][gpos]
					if codon != refCodon :
						positionAltCount = bamCodon[ref][position][codon]
						# chisquare test to determine if position is significantly different from ref
						t,p = stats.chisquare( positionAltCount / float( positionTotalCount ) , bg[ref] )
						#~ sys.stderr.write( "Testing bg : %s , %s , %s, %s\n" % ( positionAltCount , positionTotalCount , ",".join( bg[ref] ) , p )  )
						if p < 0.01: 
							positionToDiscard.append( position )
							b += 1
							a += 1

		logging.info( "End of turn %s with %s new mutation found\n" % ( turn , b ) ) 
		turn += 1
		
1182 1183


Yannis Duffourd's avatar
Yannis Duffourd committed
1184 1185
	# background noise is estimated with a control sample.
	logging.info( "Calling variants ... \n" )
1186

Yannis Duffourd's avatar
Yannis Duffourd committed
1187 1188 1189 1190 1191 1192 1193 1194
	nbMutTotal = 0
	resultTable = {}
	
	
	if not os.path.isdir( sample ):
		os.makedirs( sample )
	codonFileResult = open( codonResultFile , "w" )
	codonFileResult.write( "#Reference\treferenceCodon\treferenceAA\tposition\tsequencedCodon\tsequencedAA\tcounts\tallelicratio\t\tctrlCounts\tctrlRatio\n" )
1195

Yannis Duffourd's avatar
Yannis Duffourd committed
1196
	mutationFileResult = open( hsh , "w" )
1197 1198 1199



Yannis Duffourd's avatar
Yannis Duffourd committed
1200
	testToPerform = []
1201

Yannis Duffourd's avatar
Yannis Duffourd committed
1202
	for ref in bamCodon.keys():
1203
		
Yannis Duffourd's avatar
Yannis Duffourd committed
1204
		resultTable[ref] = {}    
1205
		totalOnPos = 0
Yannis Duffourd's avatar
Yannis Duffourd committed
1206 1207 1208 1209 1210 1211
		logging.info( "ref : %s\n" % ref )
		for position in bamCodon[ref].keys():
			#~ logging.info( "ref : " + ref + " ; position : " + str( position ) )
			gpos = get_gpos_from_ppos( ref , position )
			refCodon = referenceCodon[ref][gpos]
			refAA = codonTable[refCodon]
1212
			
Yannis Duffourd's avatar
Yannis Duffourd committed
1213 1214 1215 1216
			totalOnPos = 0
			totalOnPosReference = 0
			for a in bamCodon[ref][position].keys():
				totalOnPos += bamCodon[ref][position][a]
1217
			
Yannis Duffourd's avatar
Yannis Duffourd committed
1218 1219 1220
			if not bamCodonReference.has_key( ref ) :
				logging.warning( "The in-run control sample hasn't any %s ref : passing \n" % ref )
				break
1221 1222
			
			
Yannis Duffourd's avatar
Yannis Duffourd committed
1223 1224 1225
			if bamCodonReference[ref].has_key( position ):
				for a in bamCodonReference[ref][position].keys():
					totalOnPosReference += bamCodonReference[ref][position][a]
1226
			
Yannis Duffourd's avatar
Yannis Duffourd committed
1227 1228 1229 1230 1231 1232 1233 1234 1235
				
			
			for codon in bamCodon[ref][position].keys():
				count = bamCodon[ref][position][codon]
				obsAA = codonTable[codon]
				
				if bamCodonReference[ref].has_key( position ):
					if bamCodonReference[ref][position].has_key( codon ):
						countCtrl = bamCodonReference[ref][position][codon]
1236
					else:
Yannis Duffourd's avatar
Yannis Duffourd committed
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
						countCtrl = 0
				else:
					countCtrl = 0
				
				ratioCtrl = 0
				ratio = 0
				if totalOnPos != 0:
					ratio = ( count * 100 ) / float(totalOnPos)
				
				if totalOnPosReference != 0:
					ratioCtrl = ( countCtrl * 100 ) / float(totalOnPosReference)
				
				codonFileResult.write( "%s\t%s\t%s\t%s\t%s\t%s\t%s/%s\t%s\t%s\t%s\n" % ( ref , refCodon , refAA , position , codon , obsAA , count , totalOnPos , ratio , countCtrl , ratioCtrl ) )
				 
				# output mutation		
				if obsAA != refAA and totalOnPos > 200 and count > 30  and  countCtrl < count :
					logging.info( "Testing position : %s on %s , AA : %s (ref %s ), depth : %s , ratio : %s" % ( position , ref , obsAA , refAA , totalOnPos , ratio  ) ) 
					
					# Fisher exact test to determine if different from the in run control  
					oddsratio,pValue = stats.fisher_exact([[count , totalOnPos] , [countCtrl , totalOnPosReference]] )
					logging.info( "\tFET p-value : %s" % pValue )
					if pValue < 0.01:  
						
						#  contingency chi 2 test vs background noise of the sample
						chi2, p, dof, ex = stats.chi2_contingency( [[count , totalOnPos ] , [ bgEff[ref][0] , bgEff[ref][1] ]] , correction=False)
						logging.info( "\tchi2 p-value : %s " % p )
						if p < 0.01:
							logging.info( "Writing in results %s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s" % ( ref , refCodon , refAA , position , codon , obsAA , count , totalOnPos , countCtrl , totalOnPosReference , pValue , p ) )
							mutationFileResult.write( "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" % ( ref , refCodon , refAA , position , codon , obsAA , count , totalOnPos , countCtrl , totalOnPosReference , pValue , p ))
						else:
							logging.info( "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s was different from control but in background noise\n" % ( ref , refCodon , refAA , position , codon , obsAA , count , totalOnPos , countCtrl , totalOnPosReference , pValue , p ) )
	logging.info( "Done, performing statistical tests ...\n" )


	codonFileResult.close()
	mutationFileResult.close()
1273 1274

# stats for graphics
Yannis Duffourd's avatar
Yannis Duffourd committed
1275 1276 1277
def compute_stats_for_graphics():
	statsForGraph = {}
	for ref in bamCodon.keys():
1278
		
Yannis Duffourd's avatar
Yannis Duffourd committed
1279
		statsForGraph[ref] = {}	
1280
		totalOnPos = 0
Yannis Duffourd's avatar
Yannis Duffourd committed
1281 1282 1283 1284 1285 1286
		logging.info( "ref : " + ref )
		for position in bamCodon[ref].keys():
			#~ logging.info( "ref : " + ref + " ; position : " + str( position ) )
			refCodon = referenceCodon[ref][position]
			refAA = codonTable[refCodon]
			statsForGraph[ref][position] = {}
1287
			
Yannis Duffourd's avatar
Yannis Duffourd committed
1288 1289
			
			totalOnPos = 0
1290
			totalOnPosReference = 0
Yannis Duffourd's avatar
Yannis Duffourd committed
1291 1292 1293 1294 1295 1296 1297 1298
			for a in bamCodon[ref][position].keys():
				totalOnPos += bamCodon[ref][position][a]
				
			if bamCodonReference[ref].has_key( position ) :
				for a in bamCodonReference[ref][position].keys():
					totalOnPosReference += bamCodonReference[ref][position][a]
			else:
				totalOnPosReference = 0
1299 1300
			
			
Yannis Duffourd's avatar
Yannis Duffourd committed
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
			for codon in bamCodon[ref][position].keys():
				statsForGraph[ref][position][codon] = {}
				
				count = bamCodon[ref][position][codon]
				obsAA = codonTable[codon]
				
				if bamCodonReference[ref].has_key( position ):
					if bamCodonReference[ref][position].has_key( codon ):
						countCtrl = bamCodonReference[ref][position][codon]
					else:
						countCtrl = 0
1312 1313
				else:
					countCtrl = 0
Yannis Duffourd's avatar
Yannis Duffourd committed
1314 1315 1316 1317 1318 1319 1320 1321 1322
				
				# FET
				oddsratio,pValue = stats.fisher_exact([[count , totalOnPos] , [countCtrl , totalOnPosReference]] )
				statsForGraph[ref][position][codon]['FET'] = pValue
				
				# chisquare
				chi2, p, dof, ex = stats.chi2_contingency( [[count , totalOnPos ] , [ bgEff[ref][0] , bgEff[ref][1] ]] , correction=False)
				statsForGraph[ref][position][codon]['CHI'] = p
				statsForGraph[ref][position][codon]['codonDepth'] = count
1323 1324


Yannis Duffourd's avatar
Yannis Duffourd committed
1325 1326 1327 1328 1329 1330
# writing final results after annotation
def write_results():
	global annotationIsDefined
	finalFileResult = open( outputFile , "w" )
	finalFileResult.write( "#Reference\taa Position\tReference Codon\tReference aa\tAlternative Codon\tAlternative aa\tDepth\tAlternative Allele Ratio\tFET ctrl p-value\tFET bg pValue\tAnnotation\n")
	mutationFileResult = open( hsh , "r" )
1331

Yannis Duffourd's avatar
Yannis Duffourd committed
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
	for line in mutationFileResult:
		lineTable = line.strip().split( "\t" )
		ref = lineTable[0]
		annotation = "No annotation found"
		
		if annotationIsDefined :
			index = lineTable[2] + lineTable[3] + lineTable[5]
			logging.info( "looking for annotation for %s\n" % index )
			if index in knownMutationTable[ref].keys():
				annotation = knownMutationTable[ref][index]
		
		depth = int( lineTable[7] )
		ratio = ( float( lineTable[6] ) *100 ) / depth 
		
		finalFileResult.write( "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s pct\t%s\t%s\t%s\n" % ( ref , lineTable[3] , lineTable[1] , lineTable[2] , lineTable[4] , lineTable[5] , depth , ratio , lineTable[10], lineTable[11] ,  annotation ) ) 
	mutationFileResult.close()
	finalFileResult.close()
1349 1350


Yannis Duffourd's avatar
Yannis Duffourd committed
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
# writing consensus sequence
def compute_consensus():
	global bamCodon
	consFile = open( csFile , "w" )
	for ref in bamCodon.keys():
		consFile.write( ">" + ref + "\n" )
		for position in sorted( bamCodon[ref].keys() ) :
			count = 0
			retainedCodon = ""
			for codon in bamCodon[ref][position].keys():
				if bamCodon[ref][position][codon] > count:
					count = bamCodon[ref][position][codon]
					retainedCodon = codon
			consFile.write( retainedCodon )
		consFile.write( "\n" )
	consFile.close()







# main 
def main( ):
	#verify_req()
	get_genome()
	get_genes()
	get_annotation()
	display_reference_codon()
	display_prot_codon()
	read_inRunControl()
	read_sample()
1384
	
Yannis Duffourd's avatar
Yannis Duffourd committed
1385 1386
	display_bam_codon()
	display_bam_ref_codon()
1387
	
Yannis Duffourd's avatar
Yannis Duffourd committed
1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
	modelize_noise()
	variant_calling()
	write_results()
	compute_consensus()
	
	
if __name__ == "__main__":
	main()











1407 1408 1409 1410 1411 1412