]> git.donarmstrong.com Git - rsem.git/blob - PairedEndQModel.h
rsem-plot-model updated
[rsem.git] / PairedEndQModel.h
1 #ifndef PAIREDENDQMODEL_H_
2 #define PAIREDENDQMODEL_H_
3
4 #include<cmath>
5 #include<cstdio>
6 #include<cassert>
7 #include<cstring>
8 #include<string>
9 #include<algorithm>
10 #include<sstream>
11
12 #include "utils.h"
13 #include "Orientation.h"
14 #include "LenDist.h"
15 #include "RSPD.h"
16 #include "QualDist.h"
17 #include "QProfile.h"
18 #include "NoiseQProfile.h"
19
20 #include "ModelParams.h"
21 #include "RefSeq.h"
22 #include "Refs.h"
23 #include "SingleReadQ.h"
24 #include "PairedEndReadQ.h"
25 #include "PairedEndHit.h"
26 #include "ReadReader.h"
27
28 #include "simul.h"
29
30 class PairedEndQModel {
31 public:
32         PairedEndQModel(Refs* refs = NULL) {
33                 this->refs = refs;
34                 M = (refs != NULL ? refs->getM() : 0);
35                 memset(N, 0, sizeof(N));
36                 estRSPD = false;
37                 needCalcConPrb = true;
38
39                 ori = new Orientation();
40                 gld = new LenDist();
41                 rspd = new RSPD(estRSPD);
42                 qd = new QualDist();
43                 qpro = new QProfile();
44                 nqpro = new NoiseQProfile();
45                 mld = new LenDist();
46
47                 mw = NULL;
48                 seedLen = 0;
49         }
50
51         //If it is not a master node, only init & update can be used!
52         PairedEndQModel(ModelParams& params, bool isMaster = true) {
53                 M = params.M;
54                 memcpy(N, params.N, sizeof(params.N));
55                 refs = params.refs;
56                 estRSPD = params.estRSPD;
57                 seedLen = params.seedLen;
58                 needCalcConPrb = true;
59
60                 ori = NULL; gld = NULL; rspd = NULL; qd = NULL; qpro = NULL; nqpro = NULL; mld = NULL;
61                 mw = NULL;
62
63                 if (isMaster) {
64                         if (!estRSPD) rspd = new RSPD(estRSPD);
65                         qd = new QualDist();
66                         mld = new LenDist(params.mate_minL, params.mate_maxL);
67                 }
68
69                 ori = new Orientation(params.probF);
70                 gld = new LenDist(params.minL, params.maxL);
71                 if (estRSPD) rspd = new RSPD(estRSPD, params.B);
72                 qpro = new QProfile();
73                 nqpro = new NoiseQProfile();
74         }
75
76         ~PairedEndQModel() {
77                 refs = NULL;
78                 if (ori != NULL) delete ori;
79                 if (gld != NULL) delete gld;
80                 if (rspd != NULL) delete rspd;
81                 if (qd != NULL) delete qd;
82                 if (qpro != NULL) delete qpro;
83                 if (nqpro != NULL) delete nqpro;
84                 if (mld != NULL) delete mld;
85                 if (mw != NULL) delete mw;
86         }
87
88         void estimateFromReads(const char*);
89
90         //if prob is too small, just make it 0
91         double getConPrb(const PairedEndReadQ& read, const PairedEndHit& hit) {
92                 if (read.isLowQuality()) return 0.0;
93
94                 double prob;
95                 int sid = hit.getSid();
96                 RefSeq &ref = refs->getRef(sid);
97                 int dir = hit.getDir();
98                 int pos = hit.getPos();
99                 int fullLen = ref.getFullLen();
100                 int totLen = ref.getTotLen();
101                 int insertLen = hit.getInsertL();
102
103                 int fpos = (dir == 0 ? pos : totLen - pos - insertLen); // the aligned position reported in SAM file, should be a coordinate in forward strand
104                 int effL = std::min(fullLen, totLen - insertLen + 1);
105
106                 assert(fpos >= 0 && fpos + insertLen <= totLen && insertLen <= totLen);
107                 if (fpos >= fullLen || ref.getMask(fpos)) return 0.0; // For paired-end model, fpos is the seedPos
108
109                 prob = ori->getProb(dir) * gld->getAdjustedProb(insertLen, totLen) *
110                        rspd->getAdjustedProb(fpos, effL, fullLen);
111
112                 const SingleReadQ& mate1 = read.getMate1();
113                 prob *= mld->getAdjustedProb(mate1.getReadLength(), insertLen) *
114                         qpro->getProb(mate1.getReadSeq(), mate1.getQScore(), ref, pos, dir);
115
116                 const SingleReadQ& mate2 = read.getMate2();
117                 int m2pos = totLen - pos - insertLen;
118                 int m2dir = !dir;
119                 prob *= mld->getAdjustedProb(mate2.getReadLength(), hit.getInsertL()) *
120                         qpro->getProb(mate2.getReadSeq(), mate2.getQScore(), ref, m2pos, m2dir);
121
122                 if (prob < EPSILON) { prob = 0.0; }
123
124                 prob = (mw[sid] < EPSILON ? 0.0 : prob / mw[sid]);
125
126                 return prob;
127         }
128
129         double getNoiseConPrb(const PairedEndReadQ& read) {
130                 if (read.isLowQuality()) return 0.0;
131
132                 double prob;
133                 const SingleReadQ& mate1 = read.getMate1();
134                 const SingleReadQ& mate2 = read.getMate2();
135
136                 prob = mld->getProb(mate1.getReadLength()) * nqpro->getProb(mate1.getReadSeq(), mate1.getQScore());
137                 prob *= mld->getProb(mate2.getReadLength()) * nqpro->getProb(mate2.getReadSeq(), mate2.getQScore());
138
139                 if (prob < EPSILON) { prob = 0.0; }
140
141                 prob = (mw[0] < EPSILON ? 0.0: prob / mw[0]);
142
143                 return prob;
144         }
145
146         double getLogP() { return nqpro->getLogP(); }
147
148         void init();
149
150         void update(const PairedEndReadQ& read, const PairedEndHit& hit, double frac) {
151                 if (read.isLowQuality() || frac < EPSILON) return;
152
153                 RefSeq& ref = refs->getRef(hit.getSid());
154                 const SingleReadQ& mate1 = read.getMate1();
155                 const SingleReadQ& mate2 = read.getMate2();
156
157                 gld->update(hit.getInsertL(), frac);
158                 if (estRSPD) {
159                         int fpos = (hit.getDir() == 0 ? hit.getPos() : ref.getTotLen() - hit.getPos() - hit.getInsertL());
160                         rspd->update(fpos, ref.getFullLen(), frac);
161                 }
162                 qpro->update(mate1.getReadSeq(), mate1.getQScore(), ref, hit.getPos(), hit.getDir(), frac);
163
164                 int m2pos = ref.getTotLen() - hit.getPos() - hit.getInsertL();
165                 int m2dir = !hit.getDir();
166                 qpro->update(mate2.getReadSeq(), mate2.getQScore(), ref, m2pos, m2dir, frac);
167         }
168
169         void updateNoise(const PairedEndReadQ& read, double frac) {
170                 if (read.isLowQuality() || frac < EPSILON) return;
171
172                 const SingleReadQ& mate1 = read.getMate1();
173                 const SingleReadQ& mate2 = read.getMate2();
174
175                 nqpro->update(mate1.getReadSeq(), mate1.getQScore(), frac);
176                 nqpro->update(mate2.getReadSeq(), mate2.getQScore(), frac);
177         }
178
179         void finish();
180
181         void collect(const PairedEndQModel&);
182
183         bool getNeedCalcConPrb() { return needCalcConPrb; }
184         void setNeedCalcConPrb(bool value) { needCalcConPrb = value; }
185
186         void read(const char*);
187         void write(const char*);
188
189         const LenDist& getGLD() { return *gld; }
190
191         void startSimulation(simul*, double*);
192         bool simulate(int, PairedEndReadQ&, int&);
193         void finishSimulation();
194
195         //Use it after function 'read' or 'estimateFromReads'
196         double* getMW() { 
197           assert(mw != NULL);
198           return mw;
199         }
200
201         int getModelType() const { return model_type; }
202  
203 private:
204         static const int model_type = 3;
205         static const int read_type = 3;
206
207         int M;
208         int N[3];
209         Refs *refs;
210         int seedLen;
211
212         bool estRSPD;
213         bool needCalcConPrb; //true need, false does not need
214
215         Orientation *ori;
216         LenDist *gld, *mld; //mld1 mate_length_dist
217         RSPD *rspd;
218         QualDist *qd;
219         QProfile *qpro;
220         NoiseQProfile *nqpro;
221
222         simul *sampler; // for simulation
223         double *theta_cdf; // for simulation
224
225         double *mw; // for masking
226
227         void calcMW();
228 };
229
230 void PairedEndQModel::estimateFromReads(const char* readFN) {
231         int s;
232         char readFs[2][STRLEN];
233     PairedEndReadQ read;
234
235     mld->init();
236     for (int i = 0; i < 3; i++)
237         if (N[i] > 0) {
238                 genReadFileNames(readFN, i, read_type, s, readFs);
239                 ReadReader<PairedEndReadQ> reader(s, readFs);
240
241                 int cnt = 0;
242                 while (reader.next(read)) {
243                         SingleReadQ mate1 = read.getMate1();
244                         SingleReadQ mate2 = read.getMate2();
245
246                         mld->update(mate1.getReadLength(), 1.0);
247                         mld->update(mate2.getReadLength(), 1.0);
248
249                         qd->update(mate1.getQScore());
250                         qd->update(mate2.getQScore());
251
252                         if (i == 0) {
253                                 nqpro->updateC(mate1.getReadSeq(), mate1.getQScore());
254                                 nqpro->updateC(mate2.getReadSeq(), mate2.getQScore());
255                         }
256
257                         ++cnt;
258                         if (verbose && cnt % 1000000 == 0) { printf("%d READS PROCESSED\n", cnt); }
259                 }
260
261                 if (verbose) { printf("estimateFromReads, N%d finished.\n", i); }
262         }
263
264     mld->finish();
265     qd->finish();
266     nqpro->calcInitParams();
267
268     mw = new double[M + 1];
269     calcMW();
270 }
271
272 void PairedEndQModel::init() {
273         gld->init();
274         if (estRSPD) rspd->init();
275         qpro->init();
276         nqpro->init();
277 }
278
279 void PairedEndQModel::finish() {
280         gld->finish();
281         if (estRSPD) rspd->finish();
282         qpro->finish();
283         nqpro->finish();
284         needCalcConPrb = true;
285         calcMW();
286 }
287
288 void PairedEndQModel::collect(const PairedEndQModel& o) {
289         gld->collect(*(o.gld));
290         if (estRSPD) rspd->collect(*(o.rspd));
291         qpro->collect(*(o.qpro));
292         nqpro->collect(*(o.nqpro));
293 }
294
295 //Only master node can call
296 void PairedEndQModel::read(const char* inpF) {
297         int val;
298         FILE *fi = fopen(inpF, "r");
299         if (fi == NULL) { fprintf(stderr, "Cannot open %s! It may not exist.\n", inpF); exit(-1); }
300
301         fscanf(fi, "%d", &val);
302         assert(val == model_type);
303
304         ori->read(fi);
305         gld->read(fi);
306         mld->read(fi);
307         rspd->read(fi);
308         qd->read(fi);
309         qpro->read(fi);
310         nqpro->read(fi);
311
312         if (fscanf(fi, "%d", &val) == 1) {
313                 if (M == 0) M = val;
314                 if (M == val) {
315                         mw = new double[M + 1];
316                         for (int i = 0; i <= M; i++) fscanf(fi, "%lf", &mw[i]);
317                 }
318         }
319
320
321         fclose(fi);
322 }
323
324 //Only master node can call. Only be called at EM.cpp
325 void PairedEndQModel::write(const char* outF) {
326         FILE *fo = fopen(outF, "w");
327
328         fprintf(fo, "%d\n", model_type);
329         fprintf(fo, "\n");
330
331         ori->write(fo);  fprintf(fo, "\n");
332         gld->write(fo);  fprintf(fo, "\n");
333         mld->write(fo);  fprintf(fo, "\n");
334         rspd->write(fo); fprintf(fo, "\n");
335         qd->write(fo);   fprintf(fo, "\n");
336         qpro->write(fo); fprintf(fo, "\n");
337         nqpro->write(fo);
338
339         if (mw != NULL) {
340           fprintf(fo, "\n%d\n", M);
341           for (int i = 0; i < M; i++) {
342             fprintf(fo, "%.15g ", mw[i]);
343           }
344           fprintf(fo, "%.15g\n", mw[M]);
345         }
346
347         fclose(fo);
348 }
349
350 void PairedEndQModel::startSimulation(simul* sampler, double* theta) {
351         this->sampler = sampler;
352
353         theta_cdf = new double[M + 1];
354         for (int i = 0; i <= M; i++) {
355                 theta_cdf[i] = theta[i];
356                 if (i > 0) theta_cdf[i] += theta_cdf[i - 1];
357         }
358
359         rspd->startSimulation(M, refs);
360         qd->startSimulation();
361         qpro->startSimulation();
362         nqpro->startSimulation();
363 }
364
365 bool PairedEndQModel::simulate(int rid, PairedEndReadQ& read, int& sid) {
366         int dir, pos;
367         int insertL, mateL1, mateL2;
368         std::string name;
369         std::string qual1, qual2, readseq1, readseq2;
370         std::ostringstream strout;
371
372         sid = sampler->sample(theta_cdf, M + 1);
373
374         if (sid == 0) {
375                 dir = pos = insertL = 0;
376                 mateL1 = mld->simulate(sampler, -1);
377                 qual1 = qd->simulate(sampler, mateL1);
378                 readseq1 = nqpro->simulate(sampler, mateL1, qual1);
379
380                 mateL2 = mld->simulate(sampler, -1);
381                 qual2 = qd->simulate(sampler, mateL2);
382                 readseq2 = nqpro->simulate(sampler, mateL2, qual2);
383         }
384         else {
385                 RefSeq &ref = refs->getRef(sid);
386                 dir = ori->simulate(sampler);
387                 insertL = gld->simulate(sampler, ref.getTotLen());
388                 if (insertL < 0) return false;
389                 int effL = std::min(ref.getFullLen(), ref.getTotLen() - insertL + 1);
390                 pos = rspd->simulate(sampler, sid, effL);
391                 if (pos < 0) return false;
392                 if (dir > 0) pos = ref.getTotLen() - pos - insertL;
393
394                 mateL1 = mld->simulate(sampler, insertL);
395                 qual1 = qd->simulate(sampler, mateL1);
396                 readseq1 = qpro->simulate(sampler, mateL1, pos, dir, qual1, ref);
397
398                 int m2pos = ref.getTotLen() - pos - insertL;
399                 int m2dir = !dir;
400
401                 mateL2 = mld->simulate(sampler, insertL);
402                 qual2 = qd->simulate(sampler, mateL2);
403                 readseq2 = qpro->simulate(sampler, mateL2, m2pos, m2dir, qual2, ref);
404         }
405
406         strout<<rid<<"_"<<dir<<"_"<<sid<<"_"<<pos<<"_"<<insertL;
407         name = strout.str();
408
409         read = PairedEndReadQ(SingleReadQ(name + "/1", readseq1, qual1), SingleReadQ(name + "/2", readseq2, qual2));
410
411         return true;
412 }
413
414 void PairedEndQModel::finishSimulation() {
415         delete[] theta_cdf;
416
417         rspd->finishSimulation();
418         qd->finishSimulation();
419         qpro->finishSimulation();
420         nqpro->finishSimulation();
421 }
422
423
424 void PairedEndQModel::calcMW() {
425   assert(seedLen >= OLEN && mld->getMinL() >= seedLen);
426
427   memset(mw, 0, sizeof(double) * (M + 1));
428   mw[0] = 1.0;
429
430   for (int i = 1; i <= M; i++) { 
431     RefSeq& ref = refs->getRef(i);
432     int totLen = ref.getTotLen();
433     int fullLen = ref.getFullLen();
434     int end = std::min(fullLen, totLen - gld->getMinL() + 1);
435     double value = 0.0;
436     int minL, maxL;
437     int effL, pfpos;
438
439     //seedPos is fpos here
440     for (int seedPos = 0; seedPos < end; seedPos++) 
441       if (ref.getMask(seedPos)) {
442         minL = gld->getMinL();
443         maxL = std::min(gld->getMaxL(), totLen - seedPos);
444         pfpos = seedPos;
445         for (int fragLen = minL; fragLen <= maxL; fragLen++) {
446           effL = std::min(fullLen, totLen - fragLen + 1); 
447           value += gld->getAdjustedProb(fragLen, totLen) * rspd->getAdjustedProb(pfpos, effL, fullLen); 
448         }
449       }
450     
451     mw[i] = 1.0 - value;
452
453     if (mw[i] < 1e-8) { 
454       //      fprintf(stderr, "Warning: %dth reference sequence is masked for almost all positions!\n", i);
455       mw[i] = 0.0;
456     }
457   }
458 }
459
460 #endif /* PAIREDENDQMODEL_H_ */