]> git.donarmstrong.com Git - rsem.git/blob - SingleModel.h
Fixed a bug in perl scripts for printing error messages
[rsem.git] / SingleModel.h
1 #ifndef SINGLEMODEL_H_
2 #define SINGLEMODEL_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 "SingleHit.h"
26 #include "ReadReader.h"
27
28 #include "simul.h"
29
30 class SingleModel {
31 public:
32         SingleModel(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                 mld = NULL;
42                 rspd = new RSPD(estRSPD);
43                 pro = new Profile();
44                 npro = new NoiseProfile();
45
46                 mean = -1.0; sd = 0.0;
47                 mw = NULL;
48
49                 seedLen = 0;
50         }
51
52         //If it is not a master node, only init & update can be used!
53         SingleModel(ModelParams& params, bool isMaster = true) {
54                 M = params.M;
55                 memcpy(N, params.N, sizeof(params.N));
56                 refs = params.refs;
57                 estRSPD = params.estRSPD;
58                 mean = params.mean; sd = params.sd;
59                 seedLen = params.seedLen;
60                 needCalcConPrb = true;
61
62                 ori = NULL; gld = NULL; mld = NULL; rspd = NULL; pro = NULL; npro = NULL;
63                 mw = NULL;
64
65                 if (isMaster) {
66                         gld = new LenDist(params.minL, params.maxL);
67                         if (mean >= EPSILON) {
68                                 mld = new LenDist(params.mate_minL, params.mate_maxL);
69                         }
70                         if (!estRSPD) { rspd = new RSPD(estRSPD); }
71                 }
72
73                 ori = new Orientation(params.probF);
74                 if (estRSPD) { rspd = new RSPD(estRSPD, params.B); }
75                 pro = new Profile(params.maxL);
76                 npro = new NoiseProfile();
77         }
78
79         ~SingleModel() {
80                 refs = NULL;
81                 if (ori != NULL) delete ori;
82                 if (gld != NULL) delete gld;
83                 if (mld != NULL) delete mld;
84                 if (rspd != NULL) delete rspd;
85                 if (pro != NULL) delete pro;
86                 if (npro != NULL) delete npro;
87                 if (mw != NULL) delete[] mw;
88                 /* delete[] p1, p2 */
89         }
90
91         void estimateFromReads(const char*);
92
93         //if prob is too small, just make it 0
94         double getConPrb(const SingleRead& read, const SingleHit& hit) {
95                 if (read.isLowQuality()) return 0.0;
96
97                 double prob;
98                 int sid = hit.getSid();
99                 RefSeq &ref = refs->getRef(sid);
100                 int fullLen = ref.getFullLen();
101                 int totLen = ref.getTotLen();
102                 int dir = hit.getDir();
103                 int pos = hit.getPos();
104                 int readLen = read.getReadLength();
105                 int fpos = (dir == 0 ? pos : totLen - pos - readLen); // the aligned position reported in SAM file, should be a coordinate in forward strand
106
107                 general_assert(fpos >= 0, "The alignment of read " + read.getName() + " to transcript " + itos(sid) + " starts at " + itos(fpos) + \
108                                 " from the forward direction, which should be a non-negative number! " + \
109                                 "It is possible that the aligner you use gave different read lengths for a same read in SAM file.");
110                 general_assert(fpos + readLen <= totLen,"Read " + read.getName() + " is hung over the end of transcript " + itos(sid) + "! " \
111                                 + "It is possible that the aligner you use gave different read lengths for a same read in SAM file.");
112                 general_assert(readLen <= totLen, "Read " + read.getName() + " has length " + itos(readLen) + ", but it is aligned to transcript " \
113                                 + itos(sid) + ", whose length (" + itos(totLen) + ") is shorter than the read's length!");
114
115                 int seedPos = (dir == 0 ? pos : totLen - pos - seedLen); // the aligned position of the seed in forward strand coordinates
116                 if (seedPos >= fullLen || ref.getMask(seedPos)) return 0.0;
117
118                 int effL;
119                 double value;
120
121                 if (mld != NULL) {
122                         int minL = std::max(readLen, gld->getMinL());
123                         int maxL = std::min(totLen - pos, gld->getMaxL());
124                         int pfpos; // possible fpos for fragment
125                         value = 0.0;
126                         for (int fragLen = minL; fragLen <= maxL; fragLen++) {
127                                 pfpos = (dir == 0 ? pos : totLen - pos - fragLen);
128                                 effL = std::min(fullLen, totLen - fragLen + 1);
129                                 value += gld->getAdjustedProb(fragLen, totLen) * rspd->getAdjustedProb(pfpos, effL, fullLen) * mld->getAdjustedProb(readLen, fragLen);
130                         }
131                 }
132                 else {
133                         effL = std::min(fullLen, totLen - readLen + 1);
134                         value = gld->getAdjustedProb(readLen, totLen) * rspd->getAdjustedProb(fpos, effL, fullLen);
135                 }
136
137                 prob = ori->getProb(dir) * value * pro->getProb(read.getReadSeq(), ref, pos, dir);
138
139                 if (prob < EPSILON) { prob = 0.0; }
140
141
142                 prob = (mw[sid] < EPSILON ? 0.0 : prob / mw[sid]);
143
144                 return prob;
145         }
146
147         double getNoiseConPrb(const SingleRead& read) {
148                 if (read.isLowQuality()) return 0.0;
149                 double prob = mld != NULL ? mld->getProb(read.getReadLength()) : gld->getProb(read.getReadLength());
150                 prob *= npro->getProb(read.getReadSeq());
151                 if (prob < EPSILON) { prob = 0.0; }
152
153                 prob = (mw[0] < EPSILON ? 0.0 : prob / mw[0]);
154
155                 return prob;
156         }
157
158         double getLogP() { return npro->getLogP(); }
159
160         void init();
161
162         void update(const SingleRead& read, const SingleHit& hit, double frac) {
163                 if (read.isLowQuality() || frac < EPSILON) return;
164
165                 RefSeq& ref = refs->getRef(hit.getSid());
166                 int dir = hit.getDir();
167                 int pos = hit.getPos();
168
169                 if (estRSPD) {
170                         int fullLen = ref.getFullLen();
171
172                         // Only use one strand to estimate RSPD
173                         if (ori->getProb(0) >= ORIVALVE && dir == 0) {
174                                 rspd->update(pos, fullLen, frac);
175                         }
176
177                         if (ori->getProb(0) < ORIVALVE && dir == 1) {
178                                 int totLen = ref.getTotLen();
179                                 int readLen = read.getReadLength();
180
181                                 int pfpos, effL; 
182
183                                 if (mld != NULL) {
184                                         int minL = std::max(readLen, gld->getMinL());
185                                         int maxL = std::min(totLen - pos, gld->getMaxL());
186                                         double sum = 0.0;
187                                         assert(maxL >= minL);
188                                         std::vector<double> frag_vec(maxL - minL + 1, 0.0);
189
190                                         for (int fragLen = minL; fragLen <= maxL; fragLen++) {
191                                                 pfpos = totLen - pos - fragLen;
192                                                 effL = std::min(fullLen, totLen - fragLen + 1);
193                                                 frag_vec[fragLen - minL] = gld->getAdjustedProb(fragLen, totLen) * rspd->getAdjustedProb(pfpos, effL, fullLen) * mld->getAdjustedProb(readLen, fragLen);
194                                                 sum += frag_vec[fragLen - minL];
195                                         }
196                                         assert(sum >= EPSILON);
197                                         for (int fragLen = minL; fragLen <= maxL; fragLen++) {
198                                                 pfpos = totLen - pos - fragLen;
199                                                 rspd->update(pfpos, fullLen, frac * (frag_vec[fragLen - minL] / sum));
200                                         }
201                                 }
202                                 else {
203                                         rspd->update(totLen - pos - readLen, fullLen, frac);
204                                 }
205                         }
206                 }
207                 pro->update(read.getReadSeq(), ref, pos, dir, frac);
208         }
209
210         void updateNoise(const SingleRead& read, double frac) {
211                 if (read.isLowQuality() || frac < EPSILON) return;
212
213                 npro->update(read.getReadSeq(), frac);
214         }
215
216         void finish();
217
218         void collect(const SingleModel&);
219
220         bool getNeedCalcConPrb() { return needCalcConPrb; }
221         void setNeedCalcConPrb(bool value) { needCalcConPrb = value; }
222
223         //void calcP1();
224         //void calcP2();
225         //double* getP1() { return p1; }
226         //double* getP2() { return p2; }
227
228         void read(const char*);
229         void write(const char*);
230
231         const LenDist& getGLD() { return *gld; }
232
233         void startSimulation(simul*, double*);
234         bool simulate(READ_INT_TYPE, SingleRead&, int&);
235         void finishSimulation();
236
237         double* getMW() { 
238           assert(mw != NULL);
239           return mw;
240         }
241
242         int getModelType() const { return model_type; }
243
244 private:
245         static const int model_type = 0;
246         static const int read_type = 0;
247
248         int M;
249         READ_INT_TYPE N[3];
250         Refs *refs;
251         double mean, sd;
252         int seedLen;
253         //double *p1, *p2; P_i' & P_i''
254
255         bool estRSPD; // true if estimate RSPD
256         bool needCalcConPrb; // true need, false does not need
257
258         Orientation *ori;
259         LenDist *gld, *mld;
260         RSPD *rspd;
261         Profile *pro;
262         NoiseProfile *npro;
263
264         simul *sampler; // for simulation
265         double *theta_cdf; // for simulation
266
267         double *mw; // for masking
268
269         void calcMW();
270 };
271
272 void SingleModel::estimateFromReads(const char* readFN) {
273         int s;
274         char readFs[2][STRLEN];
275         SingleRead read;
276
277         mld != NULL ? mld->init() : gld->init();
278         for (int i = 0; i < 3; i++)
279                 if (N[i] > 0) {
280                         genReadFileNames(readFN, i, read_type, s, readFs);
281                         ReadReader<SingleRead> reader(s, readFs, refs->hasPolyA(), seedLen); // allow calculation of calc_lq() function
282
283                         READ_INT_TYPE cnt = 0;
284                         while (reader.next(read)) {
285                                 if (!read.isLowQuality()) {
286                                         mld != NULL ? mld->update(read.getReadLength(), 1.0) : gld->update(read.getReadLength(), 1.0);
287                                         if (i == 0) { npro->updateC(read.getReadSeq()); }
288                                 }
289                                 else if (verbose && read.getReadLength() < seedLen) {
290                                         std::cout<< "Warning: Read "<< read.getName()<< " is ignored due to read length "<< read.getReadLength()<< " < seed length "<< seedLen<< "!"<< std::endl;
291                                 }
292                                 
293                                 ++cnt;
294                                 if (verbose && cnt % 1000000 == 0) { std::cout<< cnt<< " READS PROCESSED"<< std::endl; }
295                         }
296
297                         if (verbose) { std::cout<< "estimateFromReads, N"<< i<< " finished."<< std::endl; }
298                 }
299
300         mld != NULL ? mld->finish() : gld->finish();
301         //mean should be > 0
302         if (mean >= EPSILON) { 
303           assert(mld->getMaxL() <= gld->getMaxL());
304           gld->setAsNormal(mean, sd, std::max(mld->getMinL(), gld->getMinL()), gld->getMaxL());
305         }
306         npro->calcInitParams();
307
308         mw = new double[M + 1];
309         calcMW();
310 }
311
312 void SingleModel::init() {
313         if (estRSPD) rspd->init();
314         pro->init();
315         npro->init();
316 }
317
318 void SingleModel::finish() {
319         if (estRSPD) rspd->finish();
320         pro->finish();
321         npro->finish();
322         needCalcConPrb = true;
323         if (estRSPD) calcMW();
324 }
325
326 void SingleModel::collect(const SingleModel& o) {
327         if (estRSPD) rspd->collect(*(o.rspd));
328         pro->collect(*(o.pro));
329         npro->collect(*(o.npro));
330 }
331
332 //Only master node can call
333 void SingleModel::read(const char* inpF) {
334         int val;
335         FILE *fi = fopen(inpF, "r");
336         if (fi == NULL) { fprintf(stderr, "Cannot open %s! It may not exist.\n", inpF); exit(-1); }
337
338         assert(fscanf(fi, "%d", &val) == 1);
339         assert(val == model_type);
340
341         ori->read(fi);
342         gld->read(fi);
343         assert(fscanf(fi, "%d", &val) == 1);
344         if (val > 0) {
345                 if (mld == NULL) mld = new LenDist();
346                 mld->read(fi);
347         }
348         rspd->read(fi);
349         pro->read(fi);
350         npro->read(fi);
351
352         if (fscanf(fi, "%d", &val) == 1) {
353                 if (M == 0) M = val;
354                 if (M == val) {
355                         mw = new double[M + 1];
356                         for (int i = 0; i <= M; i++) assert(fscanf(fi, "%lf", &mw[i]) == 1);
357                 }
358         }
359
360         fclose(fi);
361 }
362
363 //Only master node can call. Only be called at EM.cpp
364 void SingleModel::write(const char* outF) {
365         FILE *fo = fopen(outF, "w");
366
367         fprintf(fo, "%d\n", model_type);
368         fprintf(fo, "\n");
369
370         ori->write(fo);  fprintf(fo, "\n");
371         gld->write(fo);  fprintf(fo, "\n");
372         if (mld != NULL) {
373                 fprintf(fo, "1\n");
374                 mld->write(fo);
375         }
376         else { fprintf(fo, "0\n"); }
377         fprintf(fo, "\n");
378         rspd->write(fo); fprintf(fo, "\n");
379         pro->write(fo);  fprintf(fo, "\n");
380         npro->write(fo);
381
382         if (mw != NULL) {
383           fprintf(fo, "\n%d\n", M);
384           for (int i = 0; i < M; i++) {
385             fprintf(fo, "%.15g ", mw[i]);
386           }
387           fprintf(fo, "%.15g\n", mw[M]);
388         }
389
390         fclose(fo);
391 }
392
393 void SingleModel::startSimulation(simul* sampler, double* theta) {
394         this->sampler = sampler;
395
396         theta_cdf = new double[M + 1];
397         for (int i = 0; i <= M; i++) {
398                 theta_cdf[i] = theta[i];
399                 if (i > 0) theta_cdf[i] += theta_cdf[i - 1];
400         }
401
402         rspd->startSimulation(M, refs);
403         pro->startSimulation();
404         npro->startSimulation();
405 }
406
407 bool SingleModel::simulate(READ_INT_TYPE rid, SingleRead& read, int& sid) {
408         int dir, pos, readLen, fragLen;
409         std::string name;
410         std::string readseq;
411         std::ostringstream strout;
412
413         sid = sampler->sample(theta_cdf, M + 1);
414
415         if (sid == 0) {
416                 dir = pos = 0;
417                 readLen = (mld != NULL ? mld->simulate(sampler, -1) : gld->simulate(sampler, -1));
418                 readseq = npro->simulate(sampler, readLen);
419         }
420         else {
421                 RefSeq &ref = refs->getRef(sid);
422                 dir = ori->simulate(sampler);
423                 fragLen = gld->simulate(sampler, ref.getTotLen());
424                 if (fragLen < 0) return false;
425                 int effL = std::min(ref.getFullLen(), ref.getTotLen() - fragLen + 1);
426                 pos = rspd->simulate(sampler, sid, effL);
427                 if (pos < 0) return false;
428                 if (dir > 0) pos = ref.getTotLen() - pos - fragLen;
429
430                 if (mld != NULL) {
431                         readLen = mld->simulate(sampler, fragLen);
432                         if (readLen < 0) return false;
433                         readseq = pro->simulate(sampler, readLen, pos, dir, ref);
434                 }
435                 else {
436                         readseq = pro->simulate(sampler, fragLen, pos, dir, ref);
437                 }
438         }
439
440         strout<<rid<<"_"<<dir<<"_"<<sid<<"_"<<pos;
441         name = strout.str();
442
443         read = SingleRead(name, readseq);
444
445         return true;
446 }
447
448 void SingleModel::finishSimulation() {
449         delete[] theta_cdf;
450
451         rspd->finishSimulation();
452         pro->finishSimulation();
453         npro->finishSimulation();
454 }
455
456 void SingleModel::calcMW() {
457         double probF, probR;
458
459         assert((mld == NULL ? gld->getMinL() : mld->getMinL()) >= seedLen);
460   
461         memset(mw, 0, sizeof(double) * (M + 1));
462         mw[0] = 1.0;
463
464         probF = ori->getProb(0);
465         probR = ori->getProb(1);
466
467         for (int i = 1; i <= M; i++) {
468                 RefSeq& ref = refs->getRef(i);
469                 int totLen = ref.getTotLen();
470                 int fullLen = ref.getFullLen();
471                 double value = 0.0;
472                 int minL, maxL;
473                 int effL, pfpos;
474                 int end = std::min(fullLen, totLen - seedLen + 1);
475                 double factor;
476
477                 for (int seedPos = 0; seedPos < end; seedPos++)
478                         if (ref.getMask(seedPos)) {
479                                 //forward
480                                 minL = gld->getMinL();
481                                 maxL = std::min(gld->getMaxL(), totLen - seedPos);
482                                 pfpos = seedPos;
483                                 for (int fragLen = minL; fragLen <= maxL; fragLen++) {
484                                         effL = std::min(fullLen, totLen - fragLen + 1);
485                                         factor = (mld == NULL ? 1.0 : mld->getAdjustedCumulativeProb(std::min(mld->getMaxL(), fragLen), fragLen));
486                                         value += probF * gld->getAdjustedProb(fragLen, totLen) * rspd->getAdjustedProb(pfpos, effL, fullLen) * factor;
487                                 }
488                                 //reverse
489                                 minL = gld->getMinL();
490                                 maxL = std::min(gld->getMaxL(), seedPos + seedLen);
491                                 for (int fragLen = minL; fragLen <= maxL; fragLen++) {
492                                         pfpos = seedPos - (fragLen - seedLen);
493                                         effL = std::min(fullLen, totLen - fragLen + 1);
494                                         factor = (mld == NULL ? 1.0 : mld->getAdjustedCumulativeProb(std::min(mld->getMaxL(), fragLen), fragLen));
495                                         value += probR * gld->getAdjustedProb(fragLen, totLen) * rspd->getAdjustedProb(pfpos, effL, fullLen) * factor;
496                                 }
497                         }
498     
499                 //for reverse strand masking
500                 for (int seedPos = end; seedPos <= totLen - seedLen; seedPos++) {
501                         minL = std::max(gld->getMinL(), seedPos + seedLen - fullLen + 1);
502                         maxL = std::min(gld->getMaxL(), seedPos + seedLen);
503                         for (int fragLen = minL; fragLen <= maxL; fragLen++) {
504                                 pfpos = seedPos - (fragLen - seedLen);
505                                 effL = std::min(fullLen, totLen - fragLen + 1);
506                                 factor = (mld == NULL ? 1.0 : mld->getAdjustedCumulativeProb(std::min(mld->getMaxL(), fragLen), fragLen));
507                                 value += probR * gld->getAdjustedProb(fragLen, totLen) * rspd->getAdjustedProb(pfpos, effL, fullLen) * factor;
508                         }
509                 }
510
511                 mw[i] = 1.0 - value;
512
513                 if (mw[i] < 1e-8) {
514                         //      fprintf(stderr, "Warning: %dth reference sequence is masked for almost all positions!\n", i);
515                         mw[i] = 0.0;
516                 }
517         }
518 }
519
520 #endif /* SINGLEMODEL_H_ */