| •1 |
|
| 2 |
""" |
| 3 |
Created on Fri Aug 31 2012 14:05 |
| 4 |
|
| 5 |
Copyright (c) 2012, Martin S. Lindner and Maximilian Kollock, |
| 6 |
Robert Koch-Institut, Germany, |
| 7 |
All rights reserved. |
| 8 |
|
| 9 |
Redistribution and use in source and binary forms, with or without |
| 10 |
modification, are permitted provided that the following conditions are met: |
| 11 |
* Redistributions of source code must retain the above copyright |
| 12 |
notice, this list of conditions and the following disclaimer. |
| 13 |
* Redistributions in binary form must reproduce the above copyright |
| 14 |
notice, this list of conditions and the following disclaimer in the |
| 15 |
documentation and/or other materials provided with the distribution. |
| 16 |
* The name of the author may not be used to endorse or promote products |
| 17 |
derived from this software without specific prior written permission. |
| 18 |
|
| 19 |
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND |
| 20 |
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED |
| 21 |
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE |
| 22 |
DISCLAIMED. IN NO EVENT SHALL MARTIN S. LINDNER OR MAXIMILIAN KOLLOCK BE LIABLE |
| 23 |
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
| 24 |
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR |
| 25 |
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
| 26 |
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
| 27 |
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS |
| 28 |
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 29 |
""" |
| 30 |
|
| 31 |
usage = """ |
| 32 |
%prog [options] NAME |
| 33 |
|
| •34 |
Help on python3 script fitGCP.py |
| 35 |
|
| 36 |
Fits mixtures of probability distributions to genome coverage profiles using an |
| 37 |
EM-like iterative algorithm. |
| 38 |
|
| 39 |
The script uses a SAM file as input and parses the mapping information and |
| 40 |
creates a Genome Coverage Profile (GCP). The GCP is written to a file, such that |
| 41 |
this step can be skipped the next time. |
| 42 |
The user provides a mixture model that is fitted to the GCP. Furthermore, the |
| 43 |
user may specify initial parameters for each model. |
| 44 |
|
| 45 |
As output, the script generates a text file containing the final set of fit |
| 46 |
parameters and additional information about the fitting process. A log file |
| 47 |
contains the the current set of parameters in each step of the iteration. If |
| 48 |
requested, a plot of the GCP and the fitted distributions can be created. |
| 49 |
|
| 50 |
PARAMETER: |
| 51 |
|
| 52 |
NAME: Name of SAM file to analyze. |
| 53 |
""" |
| 54 |
|
| 55 |
|
| 56 |
import pysam |
| 57 |
import numpy as np |
| 58 |
import scipy.stats as stats |
| 59 |
import sys |
| 60 |
import os |
| 61 |
from collections import namedtuple |
| 62 |
import time |
| •63 |
import pickle |
| 64 |
from optparse import OptionParser |
| 65 |
from scipy.special import digamma, betainc |
| 66 |
from scipy.optimize import newton |
| 67 |
|
| 68 |
|
| 69 |
"""---------------------------------------------------------------------------- |
| 70 |
Define the distributions |
| 71 |
----------------------------------------------------------------------------""" |
| 72 |
|
| 73 |
class Distribution: |
| 74 |
_p1 = None |
| 75 |
_p2 = None |
| 76 |
_name = "General Distribution" |
| 77 |
_dof = 0 |
| 78 |
|
| 79 |
alpha = 1. |
| 80 |
def __str__(self): |
| 81 |
""" return the name of the distribution """ |
| 82 |
return self._name |
| 83 |
|
| 84 |
def set_par(self,p1=None, p2=None): |
| 85 |
""" explicitly set a parameter """ |
| 86 |
if p1 != None: |
| 87 |
self._p1 = p1 |
| 88 |
if p2 != None: |
| 89 |
self._p2 = p2 |
| 90 |
|
| 91 |
def pmf(self, x): |
| 92 |
""" return the value of the probability mass function at x """ |
| 93 |
return x*0. |
| 94 |
|
| 95 |
def estimate_par(self, data=None, weights=None): |
| 96 |
""" estimate the distribution parameters from the data and the weights |
| 97 |
(if provided) """ |
| 98 |
pass |
| 99 |
|
| 100 |
def init_par(self, mean=None, var=None): |
| 101 |
""" estimate initial distribution parameters given the mean and |
| 102 |
variance of the data""" |
| 103 |
pass |
| 104 |
|
| 105 |
def report_stats(self, width=20): |
| 106 |
""" return a string that reports information about the distribution """ |
| 107 |
return str(self._name).ljust(width) + str(self.alpha).ljust(width) + \ |
| 108 |
str(self._p1).ljust(width) + str(self._p2).ljust(width) |
| 109 |
|
| 110 |
|
| 111 |
class Zero(Distribution): |
| 112 |
_name = "Zero" |
| 113 |
_dof = 1 |
| 114 |
|
| 115 |
def pmf(self,x): |
| 116 |
if isinstance(x,np.ndarray): |
| •117 |
return (x==0).astype(float) |
| 118 |
else: |
| 119 |
return float(x==0) |
| 120 |
|
| 121 |
|
| 122 |
class NBinom(Distribution): |
| 123 |
_name = "NBinom" |
| 124 |
_dof = 3 |
| 125 |
_use_MOM = False |
| 126 |
|
| 127 |
def pmf(self, x): |
| 128 |
return stats.nbinom.pmf(x,self._p1,self._p2) |
| 129 |
|
| 130 |
def estimate_par(self, data, weights=None): |
| •131 |
if weights is None: |
| 132 |
weights = data*0. + 1. |
| 133 |
norm = np.sum(weights) |
| 134 |
mean = np.sum(data*weights)/(norm + 10**(-25)) |
| 135 |
var = np.sum((data - mean)**2 * weights) / (norm + 10**(-25)) |
| 136 |
|
| 137 |
if self._use_MOM: |
| 138 |
if var < mean: |
| •139 |
print("Warning: var < mean") |
| 140 |
var = 1.01*mean |
| 141 |
self._p1 = mean**2 / (var - mean) |
| 142 |
self._p2 = mean / var |
| 143 |
else: |
| 144 |
def dp1_llnbinom(param,obs,obs_w): |
| 145 |
|
| 146 |
|
| 147 |
|
| 148 |
N = np.sum(obs_w) |
| 149 |
data_mean = np.sum(obs*obs_w)/(N) |
| 150 |
return np.sum(digamma(obs+param)*obs_w) - N*digamma(param) + \ |
| 151 |
N*np.log(data_mean/(param+data_mean)) |
| 152 |
try: |
| 153 |
self._p1 = newton(dp1_llnbinom,self._p1, args=(data,weights), |
| 154 |
maxiter=10000) |
| 155 |
self._p2 = (self._p1)/(self._p1+mean) |
| 156 |
except: |
| •157 |
print("Warning: MLE for negative binomial failed. Using MOM.") |
| 158 |
if var < mean: |
| •159 |
print("Warning: var < mean") |
| 160 |
var = 1.01*mean |
| 161 |
self._p1 = mean**2 / (var - mean) |
| 162 |
self._p2 = mean / var |
| 163 |
|
| 164 |
|
| 165 |
|
| 166 |
def report_stats(self, width=20): |
| 167 |
""" return a string that reports information about the distribution """ |
| 168 |
return str(self._name).ljust(width) + str(self.alpha).ljust(width) + \ |
| 169 |
str(self._p1).ljust(width) + str(self._p2).ljust(width) + \ |
| 170 |
str(stats.nbinom.mean(self._p1,self._p2)).ljust(width) |
| 171 |
|
| 172 |
|
| 173 |
|
| 174 |
class Poisson(Distribution): |
| 175 |
_name = "Poisson" |
| 176 |
_dof = 2 |
| 177 |
|
| 178 |
def pmf(self,x): |
| 179 |
return stats.poisson.pmf(x,self._p1) |
| 180 |
|
| 181 |
def estimate_par(self, data, weights=None): |
| 182 |
mean = np.sum(data*weights) / (np.sum(weights) ) |
| 183 |
self._p1 = mean |
| 184 |
|
| 185 |
|
| 186 |
|
| 187 |
class TailDistribution(Distribution): |
| 188 |
_name = "Tail" |
| 189 |
_dof = 1 |
| 190 |
_norm = False |
| 191 |
_parent = None |
| 192 |
_active = True |
| 193 |
|
| 194 |
def set_par(self,p1=None, p2=None): |
| 195 |
""" explicitly set a parameter """ |
| 196 |
if p1 != None: |
| 197 |
self._p1 = p1 |
| 198 |
if p2 != None: |
| 199 |
self._p2 = p2 |
| 200 |
self._norm = False |
| 201 |
|
| 202 |
def estimate_par(self, data=None, weights=None): |
| 203 |
""" Do not estimate parameters, but obtain parameters from parent |
| 204 |
distribution """ |
| 205 |
self._p1 = self._parent._p1 |
| 206 |
self._p2 = self._parent._p2 |
| 207 |
self._norm = False |
| 208 |
|
| 209 |
|
| 210 |
|
| 211 |
class NbTail(TailDistribution): |
| 212 |
_name = "Tail" |
| 213 |
_dof = 1 |
| 214 |
def __init__(self, nbinom): |
| 215 |
""" NbTail distribution must be connected to a negative binomial""" |
| 216 |
if isinstance(nbinom, NBinom): |
| 217 |
self._parent = nbinom |
| 218 |
else: |
| •219 |
raise Exception |
| 220 |
|
| 221 |
def pmf(self, x): |
| 222 |
if np.isscalar(x) and x == 0: |
| 223 |
return 0. |
| 224 |
|
| 225 |
if self._active == False: |
| 226 |
return 0*x |
| 227 |
if stats.nbinom.mean(self._p1, self._p2) < 1.: |
| 228 |
self._active = False |
| 229 |
|
| 230 |
def betaincreg(x,p1,p2): |
| 231 |
return 1-betainc(p1,x+1,p2) |
| 232 |
|
| 233 |
|
| 234 |
if not self._norm: |
| 235 |
ks = int(max(2,stats.nbinom.ppf(0.999999,self._p1,self._p2))) |
| 236 |
norm = np.sum(betaincreg(np.arange(1,ks),self._p1,self._p2)) |
| 237 |
else: |
| 238 |
norm = self._norm |
| 239 |
|
| 240 |
ret = betaincreg(x,self._p1,self._p2) / norm |
| 241 |
if not np.isscalar(x): |
| 242 |
ret[np.where(x==0)] = 0. |
| 243 |
return ret |
| 244 |
|
| 245 |
|
| 246 |
|
| 247 |
class PoissonTail(TailDistribution): |
| 248 |
_name = "Tail of Poisson" |
| 249 |
_dof = 1 |
| 250 |
def __init__(self, poisson): |
| 251 |
""" PoissonTail distribution must be connected to a poisson |
| 252 |
distribution """ |
| 253 |
if isinstance(poisson, Poisson): |
| 254 |
self._parent = poisson |
| 255 |
else: |
| •256 |
raise Exception |
| 257 |
|
| 258 |
def pmf(self, x): |
| 259 |
if self._p1 < 1.: |
| 260 |
self._active = False |
| 261 |
if self._active == False: |
| 262 |
return 0*x |
| 263 |
|
| 264 |
if np.isscalar(x) and x == 0: |
| 265 |
return 0. |
| 266 |
|
| 267 |
xmax = int(max(np.max(x),5,stats.poisson.ppf(0.999999,self._p1)))+1 |
| •268 |
xs = np.arange(0,xmax, dtype=float) |
| 269 |
|
| 270 |
tx = np.cumsum((stats.poisson.pmf(xs, self._p1)/xs)[::-1])[::-1] |
| 271 |
tx[0] = 0 |
| 272 |
tx /= np.sum(tx) |
| 273 |
return tx[x] |
| 274 |
|
| 275 |
|
| 276 |
def build_mixture_model(dist_str): |
| 277 |
""" Build a mixture model from a string """ |
| 278 |
num_dist = len(dist_str) |
| 279 |
mm = np.array([Zero()]*num_dist) |
| 280 |
it = 0 |
| 281 |
for dist in dist_str: |
| 282 |
if dist == "z": |
| 283 |
it += 1 |
| 284 |
elif dist=="n": |
| 285 |
mm[it] = NBinom() |
| 286 |
mm[it]._use_MOM = True |
| 287 |
it += 1 |
| 288 |
elif dist=="N": |
| 289 |
mm[it] = NBinom() |
| 290 |
mm[it]._use_MOM = False |
| 291 |
it += 1 |
| 292 |
elif dist == "t": |
| 293 |
if it > 0 and isinstance(mm[it-1], NBinom): |
| 294 |
mm[it] = NbTail(mm[it-1]) |
| 295 |
it += 1 |
| 296 |
elif it > 0 and isinstance(mm[it-1], Poisson): |
| 297 |
mm[it] = PoissonTail(mm[it-1]) |
| 298 |
it += 1 |
| 299 |
else: |
| 300 |
raise Exception("Error: wrong input '%s'. A Tail distribution " |
| 301 |
"(t) must follow a Negative Binomial (n|N) or " |
| 302 |
"Poisson (p)."%dist_str) |
| 303 |
elif dist == "p": |
| 304 |
mm[it] = Poisson() |
| 305 |
it+=1 |
| 306 |
else: |
| 307 |
raise Exception("Input Error: distribution %s not recognized!"%dist) |
| 308 |
|
| 309 |
|
| 310 |
alpha = 1./len(mm) |
| 311 |
for dist in mm: |
| 312 |
dist.alpha = alpha |
| 313 |
|
| 314 |
return mm |
| 315 |
|
| 316 |
|
| 317 |
def init_gamma(mixture_model, dataset): |
| 318 |
""" create initial responsibilities gamma. The probability that a coverage |
| 319 |
belongs to a distribution is equal for all distributions.""" |
| 320 |
N_mm = len(mixture_model) |
| 321 |
N_cov = len(dataset.cov) |
| 322 |
|
| 323 |
return np.array([[1./N_mm for d in mixture_model] for i in range(N_cov)]) |
| 324 |
|
| 325 |
|
| 326 |
|
| 327 |
"""---------------------------------------------------------------------------- |
| 328 |
Define DataSet to store all relevant information (incl. GCP) |
| 329 |
----------------------------------------------------------------------------""" |
| 330 |
|
| 331 |
class DataSet: |
| 332 |
fname = "" |
| •333 |
cov = np.array([],dtype=int) |
| 334 |
count = np.array([],dtype=int) |
| 335 |
rlen = 0 |
| 336 |
rds = 0 |
| 337 |
glen = 0 |
| 338 |
|
| 339 |
def read_from_pickle(self,filename): |
| 340 |
""" read a genome coverage profile from a pickle file. """ |
| •341 |
data = pickle.load(open(filename,'rb')) |
| 342 |
|
| •343 |
self.cov = np.array(data[0],dtype=int) |
| 344 |
self.count = np.array(data[1],dtype=int) |
| 345 |
self.rlen = data[2] |
| 346 |
self.rds = data[3] |
| 347 |
self.glen = data[4] |
| 348 |
if len(data) == 6: |
| 349 |
self.fname = data[5] |
| 350 |
|
| 351 |
|
| 352 |
def read_from_sam(self, filename): |
| 353 |
""" extract a genome coverage profile from a sam file. """ |
| 354 |
sf = pysam.Samfile(filename,'r') |
| 355 |
|
| 356 |
cov = np.zeros((sum(sf.lengths),)) |
| 357 |
start_pos = np.zeros((len(sf.lengths),)) |
| 358 |
start_pos[1:] = np.cumsum(sf.lengths[:-1]) |
| 359 |
|
| 360 |
read_length = 0 |
| 361 |
num_reads = 0 |
| 362 |
for read in sf: |
| 363 |
if not read.is_unmapped: |
| 364 |
r_start = start_pos[read.tid] + read.pos |
| 365 |
r_end = start_pos[read.tid] + read.pos + read.qlen |
| •366 |
cov[int(r_start):int(r_end)] += 1 |
| 367 |
num_reads += 1 |
| 368 |
read_length += r_end-r_start |
| 369 |
self.fname = filename |
| 370 |
self.rds = num_reads |
| 371 |
self.rlen = read_length/float(num_reads) |
| 372 |
self.glen = len(cov) |
| 373 |
self.cov = np.unique(cov) |
| 374 |
self.count = np.array( [np.sum(cov==ucov) for ucov in self.cov] ) |
| 375 |
|
| 376 |
def write_to_pickle(self, filename): |
| 377 |
""" store dataset in a pickle file. """ |
| •378 |
return pickle.dump([self.cov, self.count, self.rlen, self.rds, |
| •379 |
self.glen, self.fname], open(filename,'wb')) |
| 380 |
|
| 381 |
|
| 382 |
|
| 383 |
"""---------------------------------------------------------------------------- |
| 384 |
Iterative Method function definitions |
| 385 |
----------------------------------------------------------------------------""" |
| 386 |
|
| 387 |
|
| 388 |
def update_gamma(data_set, mixture_model, gamma): |
| 389 |
""" Update the probability gamma_i(x), that a position with coverage x |
| 390 |
belongs to distribution i |
| 391 |
""" |
| 392 |
num_dist = len(mixture_model) |
| 393 |
for it in range(len(data_set.cov)): |
| 394 |
|
| 395 |
prob = [dist.alpha*dist.pmf(data_set.cov[it]) for dist in mixture_model] |
| 396 |
if sum(prob) <= 0: |
| 397 |
gamma[it,:] = 0. |
| 398 |
else: |
| 399 |
gamma[it,:] = np.array([prob[i]/sum(prob) for i in range(num_dist)]) |
| 400 |
|
| 401 |
return 1 |
| 402 |
|
| 403 |
|
| 404 |
def update_alpha(data_set, mixture_model, gamma): |
| 405 |
""" Update alpha_i, the proportion of data that belongs to |
| 406 |
distribution i """ |
| 407 |
|
| 408 |
for i in range(len(mixture_model)-1): |
| 409 |
w_probs = np.array([p*w for p,w in zip(gamma[:,i],data_set.count)]) |
| 410 |
mixture_model[i].alpha = np.sum(w_probs) / np.sum(data_set.count) |
| 411 |
|
| 412 |
mixture_model[-1].alpha = 1 - sum([d.alpha for d in mixture_model[:-1]]) |
| 413 |
|
| 414 |
return 1 |
| 415 |
|
| 416 |
|
| 417 |
def iterative_fitting(data_set, mixture_model, gamma, iterations): |
| 418 |
""" Generator fuction to run the iterative method. Operates directly on the |
| 419 |
data structures mixture_model and gamma. """ |
| 420 |
|
| 421 |
for i in range(iterations): |
| 422 |
|
| 423 |
update_gamma(data_set, mixture_model, gamma) |
| 424 |
|
| 425 |
|
| 426 |
old_p1 = np.array([d._p1 or 0 for d in mixture_model]) |
| 427 |
old_p2 = np.array([d._p2 or 0 for d in mixture_model]) |
| 428 |
old_alpha = np.array([d.alpha for d in mixture_model]) |
| 429 |
|
| 430 |
|
| 431 |
for j,dist in enumerate(mixture_model): |
| 432 |
dist_weights = gamma[:,j]*data_set.count |
| 433 |
dist.estimate_par(data_set.cov, dist_weights) |
| 434 |
update_alpha(data_set, mixture_model, gamma) |
| 435 |
|
| 436 |
|
| 437 |
new_p1 = np.array([d._p1 or 0 for d in mixture_model]) |
| 438 |
new_p2 = np.array([d._p2 or 0 for d in mixture_model]) |
| 439 |
new_alpha = np.array([d.alpha for d in mixture_model]) |
| 440 |
|
| 441 |
rel_p1 = np.max(np.abs(new_p1-old_p1) / (new_p1 + 1e-20)) |
| 442 |
rel_p2 = np.max(np.abs(new_p2-old_p2) / (new_p2 + 1e-20)) |
| 443 |
rel_alpha = np.max(np.abs(new_alpha-old_alpha) / (new_alpha + 1e-20)) |
| 444 |
|
| 445 |
max_change = np.max([rel_p1, rel_p2, rel_alpha]) |
| 446 |
|
| 447 |
|
| 448 |
xs = np.arange(np.max(data_set.cov)+1) |
| •449 |
ref_pdf = np.zeros((int(np.max(data_set.cov))+1,)) |
| 450 |
for dist in mixture_model: |
| 451 |
ref_pdf += dist.pmf(xs)*dist.alpha |
| 452 |
|
| •453 |
obs_pdf = np.zeros((int(np.max(data_set.cov))+1,)) |
| •454 |
obs_pdf[data_set.cov.astype(int)] = data_set.count/float(np.sum(data_set.count)) |
| 455 |
max_cdf_diff = np.max(np.abs(np.cumsum(ref_pdf)-np.cumsum(obs_pdf))) |
| 456 |
|
| 457 |
yield i, max_change, max_cdf_diff |
| 458 |
|
| 459 |
|
| 460 |
"""---------------------------------------------------------------------------- |
| 461 |
Auxiliary code |
| 462 |
----------------------------------------------------------------------------""" |
| 463 |
|
| 464 |
class Logger: |
| 465 |
""" simple logger class """ |
| 466 |
log_file = None |
| 467 |
def __init__(self, filename=None): |
| 468 |
if filename: |
| 469 |
self.log_file = open(filename,'w') |
| 470 |
|
| 471 |
def log(self, s, c=True): |
| 472 |
""" write string s to log file and print to console (if c) """ |
| 473 |
if c: |
| •474 |
print(s) |
| 475 |
if self.log_file: |
| 476 |
self.log_file.write(s+'\n') |
| 477 |
|
| 478 |
|
| 479 |
def create_plot(ds, mm, filename): |
| 480 |
""" create a plot showing the data and the fitted distributions """ |
| 481 |
plt.figure() |
| 482 |
xmax = np.max(ds.cov)+1 |
| 483 |
plotXs = np.arange(xmax) |
| 484 |
plt.plot(ds.cov[np.where(ds.cov<xmax)],ds.count[np.where(ds.cov<xmax)]/ |
| 485 |
float(ds.glen),'k', lw=2, label="GCP") |
| 486 |
plotY_total = np.zeros((len(plotXs),)) |
| 487 |
for dist in mm: |
| 488 |
if isinstance(dist,Poisson): |
| 489 |
format_string = "--" |
| 490 |
color = 'r' |
| 491 |
elif isinstance(dist,NBinom): |
| 492 |
format_string = "-." |
| 493 |
color = 'b' |
| 494 |
elif isinstance(dist,TailDistribution): |
| 495 |
format_string = ":" |
| 496 |
color = 'Purple' |
| 497 |
elif isinstance(dist,Zero): |
| 498 |
format_string = "-" |
| 499 |
color = 'YellowGreen' |
| 500 |
|
| 501 |
plotYs = dist.pmf(plotXs)*dist.alpha |
| 502 |
plotY_total += plotYs |
| 503 |
plt.plot(plotXs,plotYs, format_string, color=color, lw=2, label=dist._name) |
| 504 |
plt.plot(plotXs,plotY_total,'--',color='gray',lw=2, label="Mixture") |
| 505 |
plt.xlabel('coverage') |
| 506 |
plt.ylabel('') |
| 507 |
plt.xlim(xmin=0, xmax=xmax) |
| 508 |
plt.legend() |
| 509 |
plt.savefig(filename, dpi=300, bbox_inches='tight') |
| 510 |
|
| 511 |
|
| 512 |
|
| 513 |
"""---------------------------------------------------------------------------- |
| 514 |
Main function |
| 515 |
----------------------------------------------------------------------------""" |
| 516 |
|
| 517 |
if __name__ == "__main__": |
| 518 |
|
| 519 |
|
| 520 |
parser = OptionParser(usage=usage) |
| 521 |
|
| 522 |
parser.add_option("-d", "--distributions", dest="dist", |
| 523 |
help="Distributions to fit. z->zero; n: nbinom (MOM); N: nbinom (MLE); " |
| 524 |
"p:binom; t: tail. Default: %default", default="zn") |
| 525 |
|
| 526 |
parser.add_option("-i", "--iterations", dest="steps", type='int', |
| 527 |
help="Maximum number of iterations. Default: %default", default=50) |
| 528 |
|
| 529 |
parser.add_option("-t", "--threshold", dest="thr", type='float', help="Set" |
| 530 |
" the convergence threshold for the iteration. Stop if the change between " |
| 531 |
"two iterations is less than THR. Default: %default", default=0.01) |
| 532 |
|
| 533 |
parser.add_option("-c", "--cutoff", dest="cutoff", type='float', |
| 534 |
help="Specifies a coverage cutoff quantile such that only coverage values" |
| 535 |
" below this quantile are considered. Default: %default", default=0.95) |
| 536 |
|
| 537 |
parser.add_option("-p", "--plot", action="store_true", dest="plot", |
| 538 |
help="Create a plot of the fitted mixture model. Default: %default", |
| 539 |
default=False) |
| 540 |
|
| 541 |
parser.add_option("-m", "--means", dest="mean", type='float', |
| 542 |
action="append", help="Specifies the initial values for the mean of each " |
| 543 |
"Poisson or Negative Binomial distribution. Usage: -m 12.4 -m 16.1 will " |
| 544 |
"specify the means for the first two non-zero/tail distributions. The " |
| 545 |
"default is calculated from the data.", default=None) |
| 546 |
|
| 547 |
parser.add_option("-a", "--alpha", dest="alpha", action="append", |
| 548 |
help="Specifies the initial values for the proportion alpha of each " |
| 549 |
"distribution. Usage: For three distributions -a 0.3 -a 0.3 specifies the " |
| 550 |
"proportions 0.3, 0.3 and 0.4. The default is " |
| 551 |
"equal proportions for all distributions.", default=None) |
| 552 |
|
| 553 |
parser.add_option("-l", "--log", action="store_true", dest="log", |
| 554 |
help="Enable logging. Default: %default", default=False) |
| 555 |
|
| 556 |
parser.add_option("--view", action="store_true", dest="view", |
| 557 |
help="Only view the GCP. Do not fit any distribution. Respects cutoff " |
| 558 |
"(-c). Default: %default", default=False) |
| 559 |
|
| 560 |
(options, args) = parser.parse_args() |
| 561 |
|
| 562 |
if len(args) != 1: |
| 563 |
parser.print_help() |
| 564 |
sys.exit(1) |
| 565 |
|
| 566 |
|
| 567 |
|
| 568 |
|
| 569 |
|
| 570 |
name = args[0] |
| 571 |
if not os.path.exists(name): |
| 572 |
raise Exception("Could not find file with name '%s'."%name) |
| 573 |
if name.endswith('.sam'): |
| 574 |
name = name[:-4] |
| 575 |
|
| 576 |
|
| 577 |
|
| 578 |
if options.log and not options.view: |
| 579 |
logfile = name + '_%s_log.txt'%options.dist |
| 580 |
else: |
| 581 |
logfile = None |
| 582 |
lg = Logger(logfile) |
| 583 |
|
| 584 |
|
| 585 |
|
| 586 |
DS = DataSet() |
| 587 |
if os.path.exists(name+'.pcl'): |
| •588 |
print('found pickle file') |
| 589 |
DS.read_from_pickle(name+'.pcl') |
| 590 |
else: |
| 591 |
DS.read_from_sam(name+'.sam') |
| 592 |
DS.write_to_pickle(name+'.pcl') |
| 593 |
|
| 594 |
|
| 595 |
|
| 596 |
try: |
| 597 |
cutoff = max(int(np.max(DS.cov[np.where(np.cumsum(DS.count)<= \ |
| 598 |
options.cutoff*DS.glen)])+1),10) |
| 599 |
except: |
| 600 |
cutoff = np.max(DS.cov)+1 |
| 601 |
lg.log("Using coverage cutoff: %i"%cutoff) |
| 602 |
|
| 603 |
DS.count = DS.count[np.where(DS.cov < cutoff)] |
| 604 |
DS.cov = DS.cov[np.where(DS.cov < cutoff)] |
| 605 |
num_unique = len(DS.cov) |
| 606 |
DS.glen = np.sum(DS.count) |
| •607 |
mean_cov = np.sum(DS.cov*DS.count)/np.sum(DS.count).astype(float) |
| 608 |
|
| 609 |
|
| 610 |
|
| 611 |
if options.view: |
| 612 |
try: |
| 613 |
import matplotlib.pyplot as plt |
| 614 |
except: |
| 615 |
raise Exception("Error: could not import matplotlib.") |
| 616 |
|
| 617 |
|
| 618 |
MM = np.array([]) |
| 619 |
create_plot(DS,MM,name+'.png') |
| •620 |
print("Wrote GCP plot to file %s."%(name+'.png')) |
| 621 |
sys.exit(0) |
| 622 |
|
| 623 |
|
| 624 |
|
| 625 |
plot = options.plot |
| 626 |
if plot: |
| 627 |
try: |
| 628 |
import matplotlib.pyplot as plt |
| 629 |
except: |
| 630 |
lg.log("Warning: could not import matplotlib. Plotting disabled.") |
| 631 |
plot = False |
| 632 |
|
| 633 |
|
| 634 |
if options.dist.count('z') > 1: |
| 635 |
raise Exception("Error: only one Zero disribution is allowed!") |
| 636 |
|
| 637 |
if options.dist.count("t") > 1: |
| 638 |
lg.log("Warning: more than one tail distribution may yield inaccurate " |
| 639 |
"estimates!") |
| 640 |
|
| 641 |
MM = build_mixture_model(options.dist) |
| 642 |
num_dist = len(MM) |
| 643 |
the_zero = options.dist.find('z') |
| 644 |
|
| 645 |
if options.alpha != None: |
| 646 |
if len(options.alpha) >= num_dist: |
| 647 |
raise Exception("Error: the number of alpha values (%i) exceeds " |
| 648 |
"the number of distributions (%i)!"%(len(options.alpha,num_dist))) |
| 649 |
|
| 650 |
|
| 651 |
|
| 652 |
if options.alpha: |
| 653 |
alpha = options.alpha |
| 654 |
if len(options.alpha) < len(MM): |
| 655 |
rest_alpha = 1. - sum(options.alpha) |
| 656 |
rest_models = len(MM) - len(options.alpha) |
| 657 |
alpha.append([rest_alpha / rest_models] * rest_models) |
| 658 |
|
| 659 |
for dist,a in zip(MM,alpha): |
| 660 |
dist.alpha = float(a) |
| 661 |
|
| 662 |
|
| 663 |
n_dist = options.dist.count('n') + options.dist.count('N') + \ |
| 664 |
options.dist.count('p') |
| 665 |
factors = np.linspace(-n_dist,n_dist,n_dist) |
| 666 |
data_mean = np.power(np.abs(factors),np.sign(factors))*np.mean(DS.cov[1:]*\ |
| 667 |
DS.count[1:]/np.mean(DS.count)) |
| 668 |
|
| 669 |
if options.mean: |
| 670 |
|
| 671 |
for i,m in enumerate(options.mean): |
| 672 |
data_mean[i] = m |
| 673 |
|
| 674 |
data_var = np.array([np.sum((DS.cov-m)**2*DS.count)/DS.glen \ |
| 675 |
for m in data_mean]) |
| 676 |
|
| 677 |
it = 0 |
| 678 |
for dist in MM: |
| 679 |
if isinstance(dist,Zero) or isinstance(dist,NbTail) \ |
| 680 |
or isinstance(dist,PoissonTail): |
| 681 |
dist.estimate_par() |
| 682 |
continue |
| 683 |
if isinstance(dist,NBinom): |
| 684 |
m,v = data_mean[it],data_var[it] |
| 685 |
if m > v: |
| 686 |
v = 1.01*m |
| 687 |
dist.set_par(m**2 / (v - m) , m / v ) |
| 688 |
it += 1 |
| 689 |
continue |
| 690 |
if isinstance(dist,Poisson): |
| 691 |
dist.set_par(data_mean[it]) |
| 692 |
it += 1 |
| 693 |
|
| 694 |
|
| 695 |
|
| 696 |
GAMMA = init_gamma(MM,DS) |
| 697 |
|
| 698 |
|
| 699 |
|
| 700 |
lg.log('Initial values',False) |
| 701 |
lg.log('distribution'.ljust(20)+'alpha'.ljust(20)+'parameter 1'.ljust(20)+ |
| 702 |
'parameter 2',False) |
| 703 |
for i in range(num_dist): |
| 704 |
lg.log(str(MM[i]).ljust(20)+str(MM[i].alpha).ljust(20)+ |
| 705 |
str(MM[i]._p1).ljust(20)+str(MM[i]._p2),False) |
| 706 |
lg.log('\n',False) |
| 707 |
|
| 708 |
|
| 709 |
|
| 710 |
|
| 711 |
t_start = time.time() |
| 712 |
for i,change,diff in iterative_fitting(DS, MM, GAMMA, options.steps): |
| •713 |
print(i) |
| 714 |
t_step = time.time() - t_start |
| 715 |
lg.log(('step#: '+str(i+1)).ljust(20)+'time: '+str(round(t_step,1))+'s' |
| 716 |
+'\n',False) |
| 717 |
lg.log('distribution'.ljust(20)+'alpha'.ljust(20)+ |
| 718 |
'parameter 1'.ljust(20)+'parameter 2',False) |
| 719 |
for d in MM: |
| 720 |
lg.log(d.report_stats(20),False) |
| 721 |
lg.log('Max. CDF diff:'.ljust(20)+'%f'%diff,False) |
| 722 |
lg.log('\n',False) |
| 723 |
|
| 724 |
if change < options.thr: |
| 725 |
break |
| 726 |
t_start = time.time() |
| 727 |
|
| 728 |
|
| 729 |
|
| 730 |
|
| 731 |
|
| 732 |
zero_frac = MM[the_zero].alpha |
| 733 |
tail = False |
| 734 |
for dist in MM: |
| 735 |
if isinstance(dist,PoissonTail) and dist.alpha > 0: |
| 736 |
p_tail = dist.alpha |
| 737 |
p_parent = dist._parent.alpha |
| 738 |
part_cov = dist._parent._p1 |
| 739 |
elif isinstance(dist,NbTail) and dist.alpha > 0: |
| 740 |
p_tail = dist.alpha |
| 741 |
p_parent = dist._parent.alpha |
| 742 |
part_cov = stats.nbinom.mean(dist._parent._p1,dist._parent._p2) |
| 743 |
else: |
| 744 |
continue |
| 745 |
|
| 746 |
tail=True |
| 747 |
gfrag = DS.glen/(1.+p_parent/p_tail)/2./DS.rlen*(p_parent+p_tail) |
| 748 |
|
| 749 |
start_prob = 1. - stats.poisson.cdf(0,part_cov/float(DS.rlen)) |
| 750 |
zero_corr = (2*gfrag-1)*(min(stats.nbinom.mean(1,start_prob),DS.rlen) |
| 751 |
- start_prob/3.*4./9.) |
| 752 |
zero_est = DS.glen*MM[the_zero].alpha |
| 753 |
zero_frac = (zero_est-zero_corr)/float(DS.glen) |
| 754 |
|
| 755 |
|
| 756 |
|
| 757 |
res = open(name+'_'+str(options.dist)+'_results.txt','w') |
| 758 |
res.write('Genome length: %i\n'%DS.glen) |
| 759 |
res.write('Number of reads: %i\n'%DS.rds) |
| 760 |
res.write('Average read length: %i\n'%DS.rlen) |
| 761 |
|
| 762 |
res.write('Max. CDF difference: %f\n\n'%diff) |
| 763 |
res.write('Distribution'.ljust(20)+'alpha'.ljust(20)+ |
| 764 |
'parameter 1'.ljust(20)+'parameter 2'.ljust(20)+'[Mean]\n') |
| 765 |
for d in MM: |
| 766 |
res.write(d.report_stats(20)+'\n') |
| 767 |
|
| 768 |
if tail: |
| 769 |
res.write('\nNum. Fragments:'.ljust(20)+'%.01f'%gfrag+'\n') |
| 770 |
res.write('Observed Zeros:'.ljust(20)+ |
| 771 |
'%.04f'%(zero_est/float(DS.glen))+'\n') |
| 772 |
res.write('Corrected Zeros:'.ljust(20)+ |
| 773 |
'%.04f'%((zero_est-zero_corr)/float(DS.glen))+'\n') |
| 774 |
res.close() |
| 775 |
|
| 776 |
lg.log('\nFinal Results:\n') |
| 777 |
|
| 778 |
lg.log('Max. CDF difference: %f\n'%diff) |
| 779 |
lg.log('Distribution'.ljust(20)+'alpha'.ljust(20)+'parameter 1'.ljust(20)+ |
| 780 |
'parameter 2'.ljust(20)+'[Mean]') |
| 781 |
for d in MM: |
| 782 |
lg.log(d.report_stats(20)) |
| 783 |
|
| 784 |
if tail: |
| 785 |
lg.log('Num. Fragments:'.ljust(20)+'%.01f'%gfrag) |
| 786 |
lg.log('Observed Zeros:'.ljust(20)+'%.04f'%(zero_est/float(DS.glen))) |
| 787 |
lg.log('Corrected Zeros:'.ljust(20)+'%.04f'%((zero_est-zero_corr)/ |
| 788 |
float(DS.glen))) |
| 789 |
|
| 790 |
|
| 791 |
|
| 792 |
if plot: |
| 793 |
create_plot(DS,MM,name+'_'+options.dist+'.png') |
| 794 |
|
| •795 |
print("\nFinished.") |