15 #include "SingleRead.h"
16 #include "SingleReadQ.h"
17 #include "PairedEndRead.h"
18 #include "PairedEndReadQ.h"
20 #include "SingleHit.h"
21 #include "PairedEndHit.h"
24 #include "SingleModel.h"
25 #include "SingleQModel.h"
26 #include "PairedEndModel.h"
27 #include "PairedEndQModel.h"
29 #include "Transcript.h"
30 #include "Transcripts.h"
33 #include "GroupInfo.h"
34 #include "HitContainer.h"
35 #include "ReadIndex.h"
36 #include "ReadReader.h"
38 #include "ModelParams.h"
40 #include "HitWrapper.h"
41 #include "BamWriter.h"
45 const double STOP_CRITERIA = 0.001;
46 const int MAX_ROUND = 10000;
47 const int MIN_ROUND = 20;
51 void *reader, *hitv, *ncpv, *mhp, *countv;
55 int m, M; // m genes, M isoforms
56 int N0, N1, N2, N_tot;
60 bool genBamF; // If user wants to generate bam file, true; otherwise, false.
61 bool updateModel, calcExpectedWeights;
62 bool genGibbsOut; // generate file for Gibbs sampler
64 char refName[STRLEN], outName[STRLEN];
65 char imdName[STRLEN], statName[STRLEN];
66 char refF[STRLEN], groupF[STRLEN], cntF[STRLEN], tiF[STRLEN];
67 char mparamsF[STRLEN], bmparamsF[STRLEN];
68 char modelF[STRLEN], thetaF[STRLEN];
71 char *pt_fn_list, *pt_chr_list;
72 char inpSamF[STRLEN], outBamF[STRLEN], fn_list[STRLEN], chr_list[STRLEN];
74 char out_for_gibbs_F[STRLEN];
76 vector<double> theta, eel; // eel : expected effective length
78 double *probv, **countvs;
82 Transcripts transcripts;
86 template<class ReadType, class HitType, class ModelType>
87 void init(ReadReader<ReadType> **&readers, HitContainer<HitType> **&hitvs, double **&ncpvs, ModelType **&mhps) {
88 int nReads, nHits, rt;
89 int nrLeft, nhT, curnr; // nrLeft : number of reads left, nhT : hit threshold per thread, curnr: current number of reads
93 char readFs[2][STRLEN];
94 ReadIndex *indices[2];
97 readers = new ReadReader<ReadType>*[nThreads];
98 genReadFileNames(imdName, 1, read_type, s, readFs);
99 for (int i = 0; i < s; i++) {
100 indices[i] = new ReadIndex(readFs[i]);
102 for (int i = 0; i < nThreads; i++) {
103 readers[i] = new ReadReader<ReadType>(s, readFs);
104 readers[i]->setIndices(indices);
107 hitvs = new HitContainer<HitType>*[nThreads];
108 for (int i = 0; i < nThreads; i++) {
109 hitvs[i] = new HitContainer<HitType>();
112 sprintf(datF, "%s.dat", imdName);
114 if (!fin.is_open()) { fprintf(stderr, "Cannot open %s! It may not exist.\n", datF); exit(-1); }
115 fin>>nReads>>nHits>>rt;
116 if (nReads != N1) { fprintf(stderr, "Number of alignable reads does not match!\n"); exit(-1); }
117 //assert(nReads == N1);
118 if (rt != read_type) { fprintf(stderr, "Data file (.dat) does not have the right read type!\n"); exit(-1); }
119 //assert(rt == read_type);
121 //A just so so strategy for paralleling
122 nhT = nHits / nThreads;
126 ncpvs = new double*[nThreads];
127 for (int i = 0; i < nThreads; i++) {
128 int ntLeft = nThreads - i - 1; // # of threads left
129 if (!readers[i]->locate(curnr)) { fprintf(stderr, "Read indices files do not match!\n"); exit(-1); }
130 //assert(readers[i]->locate(curnr));
132 while (nrLeft > ntLeft && (i == nThreads - 1 || hitvs[i]->getNHits() < nhT)) {
133 if (!hitvs[i]->read(fin)) { fprintf(stderr, "Cannot read alignments from .dat file!\n"); exit(-1); }
134 //assert(hitvs[i]->read(fin));
136 if (verbose && nrLeft % 1000000 == 0) { printf("DAT %d reads left!\n", nrLeft); }
138 ncpvs[i] = new double[hitvs[i]->getN()];
139 memset(ncpvs[i], 0, sizeof(double) * hitvs[i]->getN());
140 curnr += hitvs[i]->getN();
142 if (verbose) { printf("Thread %d : N = %d, NHit = %d\n", i, hitvs[i]->getN(), hitvs[i]->getNHits()); }
147 mhps = new ModelType*[nThreads];
148 for (int i = 0; i < nThreads; i++) {
149 mhps[i] = new ModelType(mparams, false); // just model helper
152 probv = new double[M + 1];
153 countvs = new double*[nThreads];
154 for (int i = 0; i < nThreads; i++) {
155 countvs[i] = new double[M + 1];
159 if (verbose) { printf("EM_init finished!\n"); }
162 template<class ReadType, class HitType, class ModelType>
163 void* E_STEP(void* arg) {
164 Params *params = (Params*)arg;
165 ModelType *model = (ModelType*)(params->model);
166 ReadReader<ReadType> *reader = (ReadReader<ReadType>*)(params->reader);
167 HitContainer<HitType> *hitv = (HitContainer<HitType>*)(params->hitv);
168 double *ncpv = (double*)(params->ncpv);
169 ModelType *mhp = (ModelType*)(params->mhp);
170 double *countv = (double*)(params->countv);
172 bool needCalcConPrb = model->getNeedCalcConPrb();
176 int N = hitv->getN();
178 vector<double> fracs; //to remove this, do calculation twice
181 if (needCalcConPrb || updateModel) { reader->reset(); }
182 if (updateModel) { mhp->init(); }
184 memset(countv, 0, sizeof(double) * (M + 1));
185 for (int i = 0; i < N; i++) {
186 if (needCalcConPrb || updateModel) {
187 if (!reader->next(read)) {
188 fprintf(stderr, "Can not load a read!\n");
191 //assert(reader->next(read));
193 fr = hitv->getSAt(i);
194 to = hitv->getSAt(i + 1);
195 fracs.resize(to - fr + 1);
199 if (needCalcConPrb) { ncpv[i] = model->getNoiseConPrb(read); }
200 fracs[0] = probv[0] * ncpv[i];
201 if (fracs[0] < EPSILON) fracs[0] = 0.0;
203 for (int j = fr; j < to; j++) {
204 HitType &hit = hitv->getHitAt(j);
205 if (needCalcConPrb) { hit.setConPrb(model->getConPrb(read, hit)); }
207 fracs[id] = probv[hit.getSid()] * hit.getConPrb();
208 if (fracs[id] < EPSILON) fracs[id] = 0.0;
212 if (sum >= EPSILON) {
214 countv[0] += fracs[0];
215 if (updateModel) { mhp->updateNoise(read, fracs[0]); }
216 if (calcExpectedWeights) { ncpv[i] = fracs[0]; }
217 for (int j = fr; j < to; j++) {
218 HitType &hit = hitv->getHitAt(j);
221 countv[hit.getSid()] += fracs[id];
222 if (updateModel) { mhp->update(read, hit, fracs[id]); }
223 if (calcExpectedWeights) { hit.setConPrb(fracs[id]); }
226 else if (calcExpectedWeights) {
228 for (int j = fr; j < to; j++) {
229 HitType &hit = hitv->getHitAt(j);
238 template<class ReadType, class HitType, class ModelType>
239 void* calcConProbs(void* arg) {
240 Params *params = (Params*)arg;
241 ModelType *model = (ModelType*)(params->model);
242 ReadReader<ReadType> *reader = (ReadReader<ReadType>*)(params->reader);
243 HitContainer<HitType> *hitv = (HitContainer<HitType>*)(params->hitv);
244 double *ncpv = (double*)(params->ncpv);
247 int N = hitv->getN();
250 assert(model->getNeedCalcConPrb());
253 for (int i = 0; i < N; i++) {
254 if (!reader->next(read)) {
255 fprintf(stderr, "Can not load a read!\n");
258 fr = hitv->getSAt(i);
259 to = hitv->getSAt(i + 1);
261 ncpv[i] = model->getNoiseConPrb(read);
262 for (int j = fr; j < to; j++) {
263 HitType &hit = hitv->getHitAt(j);
264 hit.setConPrb(model->getConPrb(read, hit));
271 template<class ModelType>
272 void calcExpectedEffectiveLengths(ModelType& model) {
274 double *pdf = NULL, *cdf = NULL, *clen = NULL; // clen[i] = sigma_{j=1}^{i}pdf[i]*(lb+i)
276 model.getGLD().copyTo(pdf, cdf, lb, ub, span);
277 clen = new double[span + 1];
279 for (int i = 1; i <= span; i++) {
280 clen[i] = clen[i - 1] + pdf[i] * (lb + i);
284 eel.resize(M + 1, 0.0);
285 for (int i = 1; i <= M; i++) {
286 int totLen = refs.getRef(i).getTotLen();
287 int fullLen = refs.getRef(i).getFullLen();
288 int pos1 = max(min(totLen - fullLen + 1, ub) - lb, 0);
289 int pos2 = max(min(totLen, ub) - lb, 0);
291 if (pos2 == 0) { eel[i] = 0.0; continue; }
293 eel[i] = fullLen * cdf[pos1] + ((cdf[pos2] - cdf[pos1]) * (totLen + 1) - (clen[pos2] - clen[pos1]));
295 if (eel[i] < MINEEL) { eel[i] = 0.0; }
303 template<class ModelType>
304 void writeResults(ModelType& model, double* counts) {
309 sprintf(modelF, "%s.model", statName);
312 //calculate tau values
313 double *tau = new double[M + 1];
314 memset(tau, 0, sizeof(double) * (M + 1));
317 for (int i = 1; i <= M; i++)
318 if (eel[i] >= EPSILON) {
319 tau[i] = theta[i] / eel[i];
322 if (denom <= 0) { fprintf(stderr, "No alignable reads?!\n"); exit(-1); }
324 for (int i = 1; i <= M; i++) {
328 //isoform level results
329 sprintf(outF, "%s.iso_res", imdName);
330 fo = fopen(outF, "w");
331 for (int i = 1; i <= M; i++) {
332 const Transcript& transcript = transcripts.getTranscriptAt(i);
333 fprintf(fo, "%s%c", transcript.getTranscriptID().c_str(), (i < M ? '\t' : '\n'));
335 for (int i = 1; i <= M; i++)
336 fprintf(fo, "%.2f%c", counts[i], (i < M ? '\t' : '\n'));
337 for (int i = 1; i <= M; i++)
338 fprintf(fo, "%.15g%c", tau[i], (i < M ? '\t' : '\n'));
339 for (int i = 1; i <= M; i++) {
340 const Transcript& transcript = transcripts.getTranscriptAt(i);
341 fprintf(fo, "%s%c", transcript.getLeft().c_str(), (i < M ? '\t' : '\n'));
346 sprintf(outF, "%s.gene_res", imdName);
347 fo = fopen(outF, "w");
348 for (int i = 0; i < m; i++) {
349 const string& gene_id = transcripts.getTranscriptAt(gi.spAt(i)).getGeneID();
350 fprintf(fo, "%s%c", gene_id.c_str(), (i < m - 1 ? '\t' : '\n'));
352 for (int i = 0; i < m; i++) {
353 double sumC = 0.0; // sum of counts
354 int b = gi.spAt(i), e = gi.spAt(i + 1);
355 for (int j = b; j < e; j++) sumC += counts[j];
356 fprintf(fo, "%.2f%c", sumC, (i < m - 1 ? '\t' : '\n'));
358 for (int i = 0; i < m; i++) {
359 double sumT = 0.0; // sum of tau values
360 int b = gi.spAt(i), e = gi.spAt(i + 1);
361 for (int j = b; j < e; j++) sumT += tau[j];
362 fprintf(fo, "%.15g%c", sumT, (i < m - 1 ? '\t' : '\n'));
364 for (int i = 0; i < m; i++) {
365 int b = gi.spAt(i), e = gi.spAt(i + 1);
366 for (int j = b; j < e; j++) {
367 fprintf(fo, "%s%c", transcripts.getTranscriptAt(j).getTranscriptID().c_str(), (j < e - 1 ? ',' : (i < m - 1 ? '\t' :'\n')));
374 if (verbose) { printf("Expression Results are written!\n"); }
377 template<class ReadType, class HitType, class ModelType>
378 void release(ReadReader<ReadType> **readers, HitContainer<HitType> **hitvs, double **ncpvs, ModelType **mhps) {
380 for (int i = 0; i < nThreads; i++) {
385 for (int i = 0; i < nThreads; i++) {
397 inline bool doesUpdateModel(int ROUND) {
398 //return false; // never update, for debugging only
399 return ROUND <= 20 || ROUND % 100 == 0;
402 //Including initialize, algorithm and results saving
403 template<class ReadType, class HitType, class ModelType>
410 double bChange = 0.0, change = 0.0; // bChange : biggest change
413 ModelType model(mparams); //master model
414 ReadReader<ReadType> **readers;
415 HitContainer<HitType> **hitvs;
417 ModelType **mhps; //model helpers
419 Params fparams[nThreads];
420 pthread_t threads[nThreads];
426 //initialize boolean variables
427 updateModel = calcExpectedWeights = false;
430 theta.resize(M + 1, 0.0);
431 init<ReadType, HitType, ModelType>(readers, hitvs, ncpvs, mhps);
433 //set initial parameters
435 theta[0] = max(N0 * 1.0 / (N_tot - N2), 1e-8);
436 double val = (1.0 - theta[0]) / M;
437 for (int i = 1; i <= M; i++) theta[i] = val;
439 model.estimateFromReads(imdName);
441 for (int i = 0; i < nThreads; i++) {
442 fparams[i].model = (void*)(&model);
444 fparams[i].reader = (void*)readers[i];
445 fparams[i].hitv = (void*)hitvs[i];
446 fparams[i].ncpv = (void*)ncpvs[i];
447 fparams[i].mhp = (void*)mhps[i];
448 fparams[i].countv = (void*)countvs[i];
451 /* set thread attribute to be joinable */
452 pthread_attr_init(&attr);
453 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
459 updateModel = doesUpdateModel(ROUND);
461 for (int i = 0; i <= M; i++) probv[i] = theta[i];
464 for (int i = 0; i < nThreads; i++) {
465 rc = pthread_create(&threads[i], &attr, E_STEP<ReadType, HitType, ModelType>, (void*)(&fparams[i]));
466 if (rc != 0) { fprintf(stderr, "Cannot create thread %d at ROUND %d! (numbered from 0)\n", i, ROUND); exit(-1); }
470 for (int i = 0; i < nThreads; i++) {
471 rc = pthread_join(threads[i], &status);
472 if (rc != 0) { fprintf(stderr, "Cannot join thread %d at ROUND %d! (numbered from 0)\n", i, ROUND); exit(-1); }
476 model.setNeedCalcConPrb(false);
478 for (int i = 1; i < nThreads; i++) {
479 for (int j = 0; j <= M; j++) {
480 countvs[0][j] += countvs[i][j];
489 for (int i = 0; i <= M; i++) sum += countvs[0][i];
490 assert(sum >= EPSILON);
491 for (int i = 0; i <= M; i++) theta[i] = countvs[0][i] / sum;
495 for (int i = 0; i < nThreads; i++) { model.collect(*mhps[i]); }
500 bChange = 0.0; totNum = 0;
501 for (int i = 0; i <= M; i++)
502 if (probv[i] >= 1e-7) {
503 change = fabs(theta[i] - probv[i]) / probv[i];
504 if (change >= STOP_CRITERIA) ++totNum;
505 if (bChange < change) bChange = change;
508 if (verbose) printf("ROUND = %d, SUM = %.15g, bChange = %f, totNum = %d\n", ROUND, sum, bChange, totNum);
509 } while (ROUND < MIN_ROUND || totNum > 0 && ROUND < MAX_ROUND);
510 //while (ROUND < MAX_ROUND);
512 if (totNum > 0) fprintf(stderr, "Warning: RSEM reaches %d iterations before meeting the convergence criteria.\n", MAX_ROUND);
514 //generate output file used by Gibbs sampler
516 if (model.getNeedCalcConPrb()) {
517 for (int i = 0; i < nThreads; i++) {
518 rc = pthread_create(&threads[i], &attr, calcConProbs<ReadType, HitType, ModelType>, (void*)(&fparams[i]));
519 if (rc != 0) { fprintf(stderr, "Cannot create thread %d when generate files for Gibbs sampler! (numbered from 0)\n", i); exit(-1); }
521 for (int i = 0; i < nThreads; i++) {
522 rc = pthread_join(threads[i], &status);
523 if (rc != 0) { fprintf(stderr, "Cannot join thread %d when generate files for Gibbs sampler! (numbered from 0)\n", i); exit(-1); }
526 model.setNeedCalcConPrb(false);
528 sprintf(out_for_gibbs_F, "%s.ofg", imdName);
529 fo = fopen(out_for_gibbs_F, "w");
530 fprintf(fo, "%d %d\n", M, N0);
531 for (int i = 0; i < nThreads; i++) {
532 int numN = hitvs[i]->getN();
533 for (int j = 0; j < numN; j++) {
534 int fr = hitvs[i]->getSAt(j);
535 int to = hitvs[i]->getSAt(j + 1);
538 if (ncpvs[i][j] >= EPSILON) { ++totNum; fprintf(fo, "%d %.15g ", 0, ncpvs[i][j]); }
539 for (int k = fr; k < to; k++) {
540 HitType &hit = hitvs[i]->getHitAt(k);
541 if (hit.getConPrb() >= EPSILON) {
543 fprintf(fo, "%d %.15g ", hit.getSid(), hit.getConPrb());
547 if (totNum > 0) { fprintf(fo, "\n"); }
553 sprintf(thetaF, "%s.theta", statName);
554 fo = fopen(thetaF, "w");
555 fprintf(fo, "%d\n", M + 1);
558 for (int i = 0; i < M; i++) fprintf(fo, "%.15g ", theta[i]);
559 fprintf(fo, "%.15g\n", theta[M]);
561 //calculate expected effective lengths for each isoform
562 calcExpectedEffectiveLengths<ModelType>(model);
564 //correct theta vector
566 for (int i = 1; i <= M; i++)
567 if (eel[i] < EPSILON) { theta[i] = 0.0; }
568 else sum += theta[i];
569 if (sum < EPSILON) { fprintf(stderr, "No Expected Effective Length is no less than %.6g?!\n", MINEEL); exit(-1); }
570 for (int i = 0; i <= M; i++) theta[i] /= sum;
572 //calculate expected weights and counts using learned parameters
573 updateModel = false; calcExpectedWeights = true;
574 for (int i = 0; i < nThreads; i++) {
575 rc = pthread_create(&threads[i], &attr, E_STEP<ReadType, HitType, ModelType>, (void*)(&fparams[i]));
576 if (rc != 0) { fprintf(stderr, "Cannot create thread %d when calculate expected weights! (numbered from 0)\n", i); exit(-1); }
579 for (int i = 0; i < nThreads; i++) {
580 rc = pthread_join(threads[i], &status);
581 if (rc != 0) { fprintf(stderr, "Cannot join thread %d! (numbered from 0) when calculate expected weights!\n", i); exit(-1); }
584 model.setNeedCalcConPrb(false);
585 for (int i = 1; i < nThreads; i++) {
586 for (int j = 0; j <= M; j++) {
587 countvs[0][j] += countvs[i][j];
592 /* destroy attribute */
593 pthread_attr_destroy(&attr);
595 //convert theta' to theta
596 double *mw = model.getMW();
598 for (int i = 0; i <= M; i++) {
599 theta[i] = (mw[i] < EPSILON ? 0.0 : theta[i] / mw[i]);
602 assert(sum >= EPSILON);
603 for (int i = 0; i <= M; i++) theta[i] /= sum;
606 for (int i = 0; i < M; i++) fprintf(fo, "%.15g ", theta[i]);
607 fprintf(fo, "%.15g\n", theta[M]);
611 writeResults<ModelType>(model, countvs[0]);
614 sprintf(outBamF, "%s.bam", outName);
615 if (transcripts.getType() == 0) {
616 sprintf(chr_list, "%s.chrlist", refName);
617 pt_chr_list = (char*)(&chr_list);
620 BamWriter writer(inpSamType, inpSamF, pt_fn_list, outBamF, pt_chr_list);
621 HitWrapper<HitType> wrapper(nThreads, hitvs);
622 writer.work(wrapper, transcripts);
625 release<ReadType, HitType, ModelType>(readers, hitvs, ncpvs, mhps);
628 int main(int argc, char* argv[]) {
633 printf("Usage : rsem-run-em refName read_type sampleName sampleToken [-p #Threads] [-b samInpType samInpF has_fn_list_? [fn_list]] [-q] [--gibbs-out]\n\n");
634 printf(" refName: reference name\n");
635 printf(" read_type: 0 single read without quality score; 1 single read with quality score; 2 paired-end read without quality score; 3 paired-end read with quality score.\n");
636 printf(" samplePath: sample path.\n");
637 printf(" sampleName: sample name.\n");
638 printf(" -p: number of threads which user wants to use. (default: 1)\n");
639 printf(" -b: produce bam format output file. (default: off)\n");
640 printf(" -q: set it quiet\n");
641 printf(" --gibbs-out: generate output file use by Gibbs sampler. (default: off)\n");
642 printf("// model parameters should be in imdName.mparams.\n");
646 time_t a = time(NULL);
648 strcpy(refName, argv[1]);
649 read_type = atoi(argv[2]);
650 strcpy(outName, argv[3]);
651 sprintf(imdName, "%s.temp/%s", argv[3], argv[4]);
652 sprintf(statName, "%s.stat/%s", argv[3], argv[4]);
658 pt_fn_list = pt_chr_list = NULL;
660 for (int i = 5; i < argc; i++) {
661 if (!strcmp(argv[i], "-p")) { nThreads = atoi(argv[i + 1]); }
662 if (!strcmp(argv[i], "-b")) {
664 inpSamType = argv[i + 1][0];
665 strcpy(inpSamF, argv[i + 2]);
666 if (atoi(argv[i + 3]) == 1) {
667 strcpy(fn_list, argv[i + 4]);
668 pt_fn_list = (char*)(&fn_list);
671 if (!strcmp(argv[i], "-q")) { quiet = true; }
672 if (!strcmp(argv[i], "--gibbs-out")) { genGibbsOut = true; }
674 if (nThreads <= 0) { fprintf(stderr, "Number of threads should be bigger than 0!\n"); exit(-1); }
675 //assert(nThreads > 0);
680 sprintf(refF, "%s.seq", refName);
683 sprintf(groupF, "%s.grp", refName);
687 sprintf(tiF, "%s.ti", refName);
688 transcripts.readFrom(tiF);
690 sprintf(cntF, "%s.cnt", statName);
692 if (!fin.is_open()) { fprintf(stderr, "Cannot open %s! It may not exist.\n", cntF); exit(-1); }
693 fin>>N0>>N1>>N2>>N_tot;
696 if (N1 <= 0) { fprintf(stderr, "There are no alignable reads!\n"); exit(-1); }
698 if (nThreads > N1) nThreads = N1;
700 //set model parameters
702 mparams.N[0] = N0; mparams.N[1] = N1; mparams.N[2] = N2;
703 mparams.refs = &refs;
705 sprintf(mparamsF, "%s.mparams", imdName);
707 if (!fin.is_open()) { fprintf(stderr, "Cannot open %s! It may not exist.\n", mparamsF); exit(-1); }
708 fin>> mparams.minL>> mparams.maxL>> mparams.probF;
709 int val; // 0 or 1 , for estRSPD
711 mparams.estRSPD = (val != 0);
712 fin>> mparams.B>> mparams.mate_minL>> mparams.mate_maxL>> mparams.mean>> mparams.sd;
713 fin>> mparams.seedLen;
718 case 0 : EM<SingleRead, SingleHit, SingleModel>(); break;
719 case 1 : EM<SingleReadQ, SingleHit, SingleQModel>(); break;
720 case 2 : EM<PairedEndRead, PairedEndHit, PairedEndModel>(); break;
721 case 3 : EM<PairedEndReadQ, PairedEndHit, PairedEndQModel>(); break;
722 default : fprintf(stderr, "Unknown Read Type!\n"); exit(-1);
725 time_t b = time(NULL);