1 #ifndef SINGLEQMODEL_H_
2 #define SINGLEQMODEL_H_
14 #include "my_assert.h"
15 #include "Orientation.h"
20 #include "NoiseQProfile.h"
22 #include "ModelParams.h"
25 #include "SingleReadQ.h"
26 #include "SingleHit.h"
27 #include "ReadReader.h"
33 SingleQModel(Refs* refs = NULL) {
35 M = (refs != NULL ? refs->getM() : 0);
36 memset(N, 0, sizeof(N));
38 needCalcConPrb = true;
40 ori = new Orientation();
43 rspd = new RSPD(estRSPD);
45 qpro = new QProfile();
46 nqpro = new NoiseQProfile();
48 mean = -1.0; sd = 0.0;
54 //If it is not a master node, only init & update can be used!
55 SingleQModel(ModelParams& params, bool isMaster = true) {
57 memcpy(N, params.N, sizeof(params.N));
59 estRSPD = params.estRSPD;
60 mean = params.mean; sd = params.sd;
61 seedLen = params.seedLen;
62 needCalcConPrb = true;
64 ori = NULL; gld = NULL; mld = NULL; rspd = NULL; qd = NULL; qpro = NULL; nqpro = NULL;
68 gld = new LenDist(params.minL, params.maxL);
69 if (mean >= EPSILON) {
70 mld = new LenDist(params.mate_minL, params.mate_maxL);
72 if (!estRSPD) { rspd = new RSPD(estRSPD); }
76 ori = new Orientation(params.probF);
77 if (estRSPD) { rspd = new RSPD(estRSPD, params.B); }
78 qpro = new QProfile();
79 nqpro = new NoiseQProfile();
84 if (ori != NULL) delete ori;
85 if (gld != NULL) delete gld;
86 if (mld != NULL) delete mld;
87 if (rspd != NULL) delete rspd;
88 if (qd != NULL) delete qd;
89 if (qpro != NULL) delete qpro;
90 if (nqpro != NULL) delete nqpro;
91 if (mw != NULL) delete[] mw;
95 //SingleQModel& operator=(const SingleQModel&);
97 void estimateFromReads(const char*);
99 //if prob is too small, just make it 0
100 double getConPrb(const SingleReadQ& read, const SingleHit& hit) const {
101 if (read.isLowQuality()) return 0.0;
104 int sid = hit.getSid();
105 RefSeq &ref = refs->getRef(sid);
106 int fullLen = ref.getFullLen();
107 int totLen = ref.getTotLen();
108 int dir = hit.getDir();
109 int pos = hit.getPos();
110 int readLen = read.getReadLength();
111 int fpos = (dir == 0 ? pos : totLen - pos - readLen); // the aligned position reported in SAM file, should be a coordinate in forward strand
113 general_assert(fpos >= 0, "The alignment of read " + read.getName() + " to transcript " + itos(sid) + " starts at " + itos(fpos) + \
114 " from the forward direction, which should be a non-negative number! " + \
115 "It is possible that the aligner you use gave different read lengths for a same read in SAM file.");
116 general_assert(fpos + readLen <= totLen,"Read " + read.getName() + " is hung over the end of transcript " + itos(sid) + "! " \
117 + "It is possible that the aligner you use gave different read lengths for a same read in SAM file.");
118 general_assert(readLen <= totLen, "Read " + read.getName() + " has length " + itos(readLen) + ", but it is aligned to transcript " \
119 + itos(sid) + ", whose length (" + itos(totLen) + ") is shorter than the read's length!");
121 int seedPos = (dir == 0 ? pos : totLen - pos - seedLen); // the aligned position of the seed in forward strand coordinates
122 if (seedPos >= fullLen || ref.getMask(seedPos)) return 0.0;
128 int minL = std::max(readLen, gld->getMinL());
129 int maxL = std::min(totLen - pos, gld->getMaxL());
130 int pfpos; // possible fpos for fragment
132 for (int fragLen = minL; fragLen <= maxL; fragLen++) {
133 pfpos = (dir == 0 ? pos : totLen - pos - fragLen);
134 effL = std::min(fullLen, totLen - fragLen + 1);
135 value += gld->getAdjustedProb(fragLen, totLen) * rspd->getAdjustedProb(pfpos, effL, fullLen) * mld->getAdjustedProb(readLen, fragLen);
139 effL = std::min(fullLen, totLen - readLen + 1);
140 value = gld->getAdjustedProb(readLen, totLen) * rspd->getAdjustedProb(fpos, effL, fullLen);
143 prob = ori->getProb(dir) * value * qpro->getProb(read.getReadSeq(), read.getQScore(), ref, pos, dir);
145 if (prob < EPSILON) { prob = 0.0; }
147 prob = (mw[sid] < EPSILON ? 0.0 : prob / mw[sid]);
152 double getNoiseConPrb(const SingleReadQ& read) {
153 if (read.isLowQuality()) return 0.0;
154 double prob = mld != NULL ? mld->getProb(read.getReadLength()) : gld->getProb(read.getReadLength());
155 prob *= nqpro->getProb(read.getReadSeq(), read.getQScore());
156 if (prob < EPSILON) { prob = 0.0; }
158 prob = (mw[0] < EPSILON ? 0.0 : prob / mw[0]);
163 double getLogP() { return nqpro->getLogP(); }
167 void update(const SingleReadQ& read, const SingleHit& hit, double frac) {
168 if (read.isLowQuality() || frac < EPSILON) return;
170 const RefSeq& ref = refs->getRef(hit.getSid());
172 int dir = hit.getDir();
173 int pos = hit.getPos();
176 int fullLen = ref.getFullLen();
178 // Only use one strand to estimate RSPD
179 if (ori->getProb(0) >= ORIVALVE && dir == 0) {
180 rspd->update(pos, fullLen, frac);
183 if (ori->getProb(0) < ORIVALVE && dir == 1) {
184 int totLen = ref.getTotLen();
185 int readLen = read.getReadLength();
190 int minL = std::max(readLen, gld->getMinL());
191 int maxL = std::min(totLen - pos, gld->getMaxL());
193 assert(maxL >= minL);
194 std::vector<double> frag_vec(maxL - minL + 1, 0.0);
196 for (int fragLen = minL; fragLen <= maxL; fragLen++) {
197 pfpos = totLen - pos - fragLen;
198 effL = std::min(fullLen, totLen - fragLen + 1);
199 frag_vec[fragLen - minL] = gld->getAdjustedProb(fragLen, totLen) * rspd->getAdjustedProb(pfpos, effL, fullLen) * mld->getAdjustedProb(readLen, fragLen);
200 sum += frag_vec[fragLen - minL];
202 assert(sum >= EPSILON);
203 for (int fragLen = minL; fragLen <= maxL; fragLen++) {
204 pfpos = totLen - pos - fragLen;
205 rspd->update(pfpos, fullLen, frac * (frag_vec[fragLen - minL] / sum));
209 rspd->update(totLen - pos - readLen, fullLen, frac);
213 qpro->update(read.getReadSeq(), read.getQScore(), ref, pos, dir, frac);
216 void updateNoise(const SingleReadQ& read, double frac) {
217 if (read.isLowQuality() || frac < EPSILON) return;
219 nqpro->update(read.getReadSeq(), read.getQScore(), frac);
224 void collect(const SingleQModel&);
226 //void copy(const SingleQModel&);
228 bool getNeedCalcConPrb() { return needCalcConPrb; }
229 void setNeedCalcConPrb(bool value) { needCalcConPrb = value; }
233 //double* getP1() { return p1; }
234 //double* getP2() { return p2; }
236 void read(const char*);
237 void write(const char*);
239 const LenDist& getGLD() { return *gld; }
241 void startSimulation(simul*, double*);
242 bool simulate(READ_INT_TYPE, SingleReadQ&, int&);
243 void finishSimulation();
245 //Use it after function 'read' or 'estimateFromReads'
251 int getModelType() const { return model_type; }
254 static const int model_type = 1;
255 static const int read_type = 1;
262 //double *p1, *p2; P_i' & P_i'';
264 bool estRSPD; // true if estimate RSPD
265 bool needCalcConPrb; //true need, false does not need
272 NoiseQProfile *nqpro;
274 simul *sampler; // for simulation
275 double *theta_cdf; // for simulation
277 double *mw; // for masking
282 void SingleQModel::estimateFromReads(const char* readFN) {
284 char readFs[2][STRLEN];
287 mld != NULL ? mld->init() : gld->init();
288 for (int i = 0; i < 3; i++)
290 genReadFileNames(readFN, i, read_type, s, readFs);
291 ReadReader<SingleReadQ> reader(s, readFs, refs->hasPolyA(), seedLen); // allow calculation of calc_lq() function
293 READ_INT_TYPE cnt = 0;
294 while (reader.next(read)) {
295 if (!read.isLowQuality()) {
296 mld != NULL ? mld->update(read.getReadLength(), 1.0) : gld->update(read.getReadLength(), 1.0);
297 qd->update(read.getQScore());
298 if (i == 0) { nqpro->updateC(read.getReadSeq(), read.getQScore()); }
300 else if (verbose && read.getReadLength() < seedLen) {
301 std::cout<< "Warning: Read "<< read.getName()<< " is ignored due to read length "<< read.getReadLength()<< " < seed length "<< seedLen<< "!"<< std::endl;
305 if (verbose && cnt % 1000000 == 0) { std::cout<< cnt<< " READS PROCESSED"<< std::endl; }
308 if (verbose) { std::cout<< "estimateFromReads, N"<< i<< " finished."<< std::endl; }
311 mld != NULL ? mld->finish() : gld->finish();
314 if (mean >= EPSILON) {
315 assert(mld->getMaxL() <= gld->getMaxL());
316 gld->setAsNormal(mean, sd, std::max(mld->getMinL(), gld->getMinL()), gld->getMaxL());
319 nqpro->calcInitParams();
321 mw = new double[M + 1];
325 void SingleQModel::init() {
326 if (estRSPD) rspd->init();
331 void SingleQModel::finish() {
332 if (estRSPD) rspd->finish();
335 needCalcConPrb = true;
336 if (estRSPD) calcMW();
339 void SingleQModel::collect(const SingleQModel& o) {
340 if (estRSPD) rspd->collect(*(o.rspd));
341 qpro->collect(*(o.qpro));
342 nqpro->collect(*(o.nqpro));
345 //Only master node can call
346 void SingleQModel::read(const char* inpF) {
348 FILE *fi = fopen(inpF, "r");
349 if (fi == NULL) { fprintf(stderr, "Cannot open %s! It may not exist.\n", inpF); exit(-1); }
351 assert(fscanf(fi, "%d", &val) == 1);
352 assert(val == model_type);
356 assert(fscanf(fi, "%d", &val) == 1);
358 if (mld == NULL) mld = new LenDist();
366 if (fscanf(fi, "%d", &val) == 1) {
369 mw = new double[M + 1];
370 for (int i = 0; i <= M; i++) assert(fscanf(fi, "%lf", &mw[i]) == 1);
377 //Only master node can call. Only be called at EM.cpp
378 void SingleQModel::write(const char* outF) {
379 FILE *fo = fopen(outF, "w");
381 fprintf(fo, "%d\n", model_type);
384 ori->write(fo); fprintf(fo, "\n");
385 gld->write(fo); fprintf(fo, "\n");
390 else { fprintf(fo, "0\n"); }
392 rspd->write(fo); fprintf(fo, "\n");
393 qd->write(fo); fprintf(fo, "\n");
394 qpro->write(fo); fprintf(fo, "\n");
398 fprintf(fo, "\n%d\n", M);
399 for (int i = 0; i < M; i++) {
400 fprintf(fo, "%.15g ", mw[i]);
402 fprintf(fo, "%.15g\n", mw[M]);
408 void SingleQModel::startSimulation(simul* sampler, double* theta) {
409 this->sampler = sampler;
411 theta_cdf = new double[M + 1];
412 for (int i = 0; i <= M; i++) {
413 theta_cdf[i] = theta[i];
414 if (i > 0) theta_cdf[i] += theta_cdf[i - 1];
417 rspd->startSimulation(M, refs);
418 qd->startSimulation();
419 qpro->startSimulation();
420 nqpro->startSimulation();
423 bool SingleQModel::simulate(READ_INT_TYPE rid, SingleReadQ& read, int& sid) {
424 int dir, pos, readLen, fragLen;
426 std::string qual, readseq;
427 std::ostringstream strout;
429 sid = sampler->sample(theta_cdf, M + 1);
433 readLen = (mld != NULL ? mld->simulate(sampler, -1) : gld->simulate(sampler, -1));
434 qual = qd->simulate(sampler, readLen);
435 readseq = nqpro->simulate(sampler, readLen, qual);
438 RefSeq &ref = refs->getRef(sid);
439 dir = ori->simulate(sampler);
440 fragLen = gld->simulate(sampler, ref.getTotLen());
441 if (fragLen < 0) return false;
443 int effL = std::min(ref.getFullLen(), ref.getTotLen() - fragLen + 1);
444 pos = rspd->simulate(sampler, sid, effL);
445 if (pos < 0) return false;
446 if (dir > 0) pos = ref.getTotLen() - pos - fragLen;
449 readLen = mld->simulate(sampler, fragLen);
450 if (readLen < 0) return false;
451 qual = qd->simulate(sampler, readLen);
452 readseq = qpro->simulate(sampler, readLen, pos, dir, qual, ref);
455 qual = qd->simulate(sampler, fragLen);
456 readseq = qpro->simulate(sampler, fragLen, pos, dir, qual, ref);
460 strout<<rid<<"_"<<dir<<"_"<<sid<<"_"<<pos;
463 read = SingleReadQ(name, readseq, qual);
468 void SingleQModel::finishSimulation() {
471 rspd->finishSimulation();
472 qd->finishSimulation();
473 qpro->finishSimulation();
474 nqpro->finishSimulation();
477 void SingleQModel::calcMW() {
480 assert((mld == NULL ? gld->getMinL() : mld->getMinL()) >= seedLen);
482 memset(mw, 0, sizeof(double) * (M + 1));
485 probF = ori->getProb(0);
486 probR = ori->getProb(1);
488 for (int i = 1; i <= M; i++) {
489 RefSeq& ref = refs->getRef(i);
490 int totLen = ref.getTotLen();
491 int fullLen = ref.getFullLen();
495 int end = std::min(fullLen, totLen - seedLen + 1);
498 for (int seedPos = 0; seedPos < end; seedPos++)
499 if (ref.getMask(seedPos)) {
501 minL = gld->getMinL();
502 maxL = std::min(gld->getMaxL(), totLen - seedPos);
504 for (int fragLen = minL; fragLen <= maxL; fragLen++) {
505 effL = std::min(fullLen, totLen - fragLen + 1);
506 factor = (mld == NULL ? 1.0 : mld->getAdjustedCumulativeProb(std::min(mld->getMaxL(), fragLen), fragLen));
507 value += probF * gld->getAdjustedProb(fragLen, totLen) * rspd->getAdjustedProb(pfpos, effL, fullLen) * factor;
510 minL = gld->getMinL();
511 maxL = std::min(gld->getMaxL(), seedPos + seedLen);
512 for (int fragLen = minL; fragLen <= maxL; fragLen++) {
513 pfpos = seedPos - (fragLen - seedLen);
514 effL = std::min(fullLen, totLen - fragLen + 1);
515 factor = (mld == NULL ? 1.0 : mld->getAdjustedCumulativeProb(std::min(mld->getMaxL(), fragLen), fragLen));
516 value += probR * gld->getAdjustedProb(fragLen, totLen) * rspd->getAdjustedProb(pfpos, effL, fullLen) * factor;
520 //for reverse strand masking
521 for (int seedPos = end; seedPos <= totLen - seedLen; seedPos++) {
522 minL = std::max(gld->getMinL(), seedPos + seedLen - fullLen + 1);
523 maxL = std::min(gld->getMaxL(), seedPos + seedLen);
524 for (int fragLen = minL; fragLen <= maxL; fragLen++) {
525 pfpos = seedPos - (fragLen - seedLen);
526 effL = std::min(fullLen, totLen - fragLen + 1);
527 factor = (mld == NULL ? 1.0 : mld->getAdjustedCumulativeProb(std::min(mld->getMaxL(), fragLen), fragLen));
528 value += probR * gld->getAdjustedProb(fragLen, totLen) * rspd->getAdjustedProb(pfpos, effL, fullLen) * factor;
535 // fprintf(stderr, "Warning: %dth reference sequence is masked for almost all positions!\n", i);
541 #endif /* SINGLEQMODEL_H_ */