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