]> git.donarmstrong.com Git - rsem.git/blob - calcCI.cpp
99ce14858825c989216dbd6ab309562218a8ae62
[rsem.git] / calcCI.cpp
1 #include<ctime>
2 #include<cstdio>
3 #include<cstring>
4 #include<cstdlib>
5 #include<cassert>
6 #include<fstream>
7 #include<algorithm>
8 #include<vector>
9 #include<pthread.h>
10
11 #include "utils.h"
12 #include "my_assert.h"
13 #include "sampling.h"
14
15 #include "Model.h"
16 #include "SingleModel.h"
17 #include "SingleQModel.h"
18 #include "PairedEndModel.h"
19 #include "PairedEndQModel.h"
20
21 #include "Refs.h"
22 #include "GroupInfo.h"
23
24 #include "Buffer.h"
25 using namespace std;
26
27 struct Params {
28         int no;
29         FILE *fi;
30         engine_type *engine;
31         double *mw;
32 };
33
34 struct CIType {
35         float lb, ub; // the interval is [lb, ub]
36
37         CIType() { lb = ub = 0.0; }
38 };
39
40 struct CIParams {
41         int no;
42         int start_gene_id, end_gene_id;
43 };
44
45 int model_type;
46
47 int nMB;
48 double confidence;
49 int nCV, nSpC, nSamples; // nCV: number of count vectors; nSpC: number of theta vectors sampled per count vector; nSamples: nCV * nSpC
50 int nThreads;
51 int cvlen;
52
53 char cvsF[STRLEN], tmpF[STRLEN], command[STRLEN];
54
55 CIType *iso_tau, *gene_tau;
56
57 int M, m;
58 Refs refs;
59 GroupInfo gi;
60 char imdName[STRLEN], statName[STRLEN];
61 char modelF[STRLEN], groupF[STRLEN], refF[STRLEN];
62
63 vector<double> eel; //expected effective lengths
64
65 Buffer *buffer;
66
67 bool quiet;
68
69 Params *paramsArray;
70 pthread_t *threads;
71 pthread_attr_t attr;
72 void *status;
73 int rc;
74
75 CIParams *ciParamsArray;
76
77 template<class ModelType>
78 void calcExpectedEffectiveLengths(ModelType& model) {
79         int lb, ub, span;
80         double *pdf = NULL, *cdf = NULL, *clen = NULL; // clen[i] = \sigma_{j=1}^{i}pdf[i]*(lb+i)
81   
82         model.getGLD().copyTo(pdf, cdf, lb, ub, span);
83         clen = new double[span + 1];
84         clen[0] = 0.0;
85         for (int i = 1; i <= span; i++) {
86                 clen[i] = clen[i - 1] + pdf[i] * (lb + i);
87         }
88
89         eel.assign(M + 1, 0.0);
90         for (int i = 1; i <= M; i++) {
91                 int totLen = refs.getRef(i).getTotLen();
92                 int fullLen = refs.getRef(i).getFullLen();
93                 int pos1 = max(min(totLen - fullLen + 1, ub) - lb, 0);
94                 int pos2 = max(min(totLen, ub) - lb, 0);
95
96                 if (pos2 == 0) { eel[i] = 0.0; continue; }
97     
98                 eel[i] = fullLen * cdf[pos1] + ((cdf[pos2] - cdf[pos1]) * (totLen + 1) - (clen[pos2] - clen[pos1]));
99                 assert(eel[i] >= 0);
100                 if (eel[i] < MINEEL) { eel[i] = 0.0; }
101         }
102   
103         delete[] pdf;
104         delete[] cdf;
105         delete[] clen;
106 }
107
108 void* sample_theta_from_c(void* arg) {
109
110         int *cvec;
111         double *theta;
112         gamma_dist **gammas;
113         gamma_generator **rgs;
114
115         Params *params = (Params*)arg;
116         FILE *fi = params->fi;
117         double *mw = params->mw;
118
119         cvec = new int[cvlen];
120         theta = new double[cvlen];
121         gammas = new gamma_dist*[cvlen];
122         rgs = new gamma_generator*[cvlen];
123
124         float **vecs = new float*[nSpC];
125         for (int i = 0; i < nSpC; i++) vecs[i] = new float[cvlen];
126
127         int cnt = 0;
128         while (fscanf(fi, "%d", &cvec[0]) == 1) {
129                 for (int j = 1; j < cvlen; j++) assert(fscanf(fi, "%d", &cvec[j]) == 1);
130
131                 ++cnt;
132
133                 for (int j = 0; j < cvlen; j++) {
134                         gammas[j] = new gamma_dist(cvec[j]);
135                         rgs[j] = new gamma_generator(*(params->engine), *gammas[j]);
136                 }
137
138                 for (int i = 0; i < nSpC; i++) {
139                         double sum = 0.0;
140                         for (int j = 0; j < cvlen; j++) {
141                                 theta[j] = ((j == 0 || eel[j] >= EPSILON) ? (*rgs[j])() : 0.0);
142                                 sum += theta[j];
143                         }
144                         assert(sum >= EPSILON);
145                         for (int j = 0; j < cvlen; j++) theta[j] /= sum;
146
147                         sum = 0.0;
148                         for (int j = 0; j < cvlen; j++) {
149                                 theta[j] = (mw[j] < EPSILON ? 0.0 : theta[j] / mw[j]);
150                                 sum += theta[j];
151                         }
152                         assert(sum >= EPSILON);
153                         for (int j = 0; j < cvlen; j++) theta[j] /= sum;
154
155
156                         sum = 0.0;
157                         vecs[i][0] = theta[0];
158                         for (int j = 1; j < cvlen; j++)
159                                 if (eel[j] >= EPSILON) {
160                                         vecs[i][j] = theta[j] / eel[j];
161                                         sum += vecs[i][j];
162                                 }
163                                 else assert(theta[j] < EPSILON);
164
165                         assert(sum >= EPSILON);
166                         for (int j = 1; j < cvlen; j++) vecs[i][j] /= sum;
167                 }
168
169                 buffer->write(nSpC, vecs);
170
171                 for (int j = 0; j < cvlen; j++) {
172                         delete gammas[j];
173                         delete rgs[j];
174                 }
175
176                 if (verbose && cnt % 100 == 0) { printf("Thread %d, %d count vectors are processed!\n", params->no, cnt); }
177         }
178
179         delete[] cvec;
180         delete[] theta;
181         delete[] gammas;
182         delete[] rgs;
183
184         for (int i = 0; i < nSpC; i++) delete[] vecs[i];
185         delete[] vecs;
186
187         return NULL;
188 }
189
190 template<class ModelType>
191 void sample_theta_vectors_from_count_vectors() {
192         ModelType model;
193         model.read(modelF);
194         calcExpectedEffectiveLengths<ModelType>(model);
195
196
197         int num_threads = min(nThreads, nCV);
198
199         buffer = new Buffer(nMB, nSamples, cvlen, tmpF);
200
201         paramsArray = new Params[num_threads];
202         threads = new pthread_t[num_threads];
203
204         char inpF[STRLEN];
205         for (int i = 0; i < num_threads; i++) {
206                 paramsArray[i].no = i;
207                 sprintf(inpF, "%s%d", cvsF, i);
208                 paramsArray[i].fi = fopen(inpF, "r");
209                 paramsArray[i].engine = engineFactory::new_engine();
210                 paramsArray[i].mw = model.getMW();
211         }
212
213         /* set thread attribute to be joinable */
214         pthread_attr_init(&attr);
215         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
216
217         for (int i = 0; i < num_threads; i++) {
218                 rc = pthread_create(&threads[i], &attr, &sample_theta_from_c, (void*)(&paramsArray[i]));
219                 pthread_assert(rc, "pthread_create", "Cannot create thread " + itos(i) + " (numbered from 0) in sample_theta_vectors_from_count_vectors!");
220         }
221         for (int i = 0; i < num_threads; i++) {
222                 rc = pthread_join(threads[i], &status);
223                 pthread_assert(rc, "pthread_join", "Cannot join thread " + itos(i) + " (numbered from 0) in sample_theta_vectors_from_count_vectors!");
224         }
225
226         /* destroy attribute */
227         pthread_attr_destroy(&attr);
228         delete[] threads;
229
230         for (int i = 0; i < num_threads; i++) {
231                 fclose(paramsArray[i].fi);
232                 delete paramsArray[i].engine;
233         }
234         delete[] paramsArray;
235
236         delete buffer; // Must delete here, force the content left in the buffer be written into the disk
237
238         if (verbose) { printf("Sampling is finished!\n"); }
239 }
240
241 void calcCI(int nSamples, float *samples, float &lb, float &ub) {
242         int p, q; // p pointer for lb, q pointer for ub;
243         int newp, newq;
244         int threshold = nSamples - (int(confidence * nSamples - 1e-8) + 1);
245         int nOutside = 0;
246
247         sort(samples, samples + nSamples);
248
249         p = 0; q = nSamples - 1;
250         newq = nSamples - 1;
251         do {
252                 q = newq;
253                 while (newq > 0 && samples[newq - 1] == samples[newq]) newq--;
254                 newq--;
255         } while (newq >= 0 && nSamples - (newq + 1) <= threshold);
256
257         nOutside = nSamples - (q + 1);
258
259         lb = -1e30; ub = 1e30;
260         do {
261                 if (samples[q] - samples[p] < ub - lb) {
262                         lb = samples[p];
263                         ub = samples[q];
264                 }
265
266                 newp = p;
267                 while (newp < nSamples - 1 && samples[newp] == samples[newp + 1]) newp++;
268                 newp++;
269                 if (newp <= threshold) {
270                         nOutside += newp - p;
271                         p = newp;
272                         while (nOutside > threshold && q < nSamples - 1) {
273                                 newq = q + 1;
274                                 while (newq < nSamples - 1 && samples[newq] == samples[newq + 1]) newq++;
275                                 nOutside -= newq - q;
276                                 q = newq;
277                         }
278                         assert(nOutside <= threshold);
279                 }
280                 else p = newp;
281         } while (p <= threshold);
282 }
283
284 void* calcCI_batch(void* arg) {
285         float *itsamples, *gtsamples;
286         ifstream fin;
287         CIParams *ciParams = (CIParams*)arg;
288
289         itsamples = new float[nSamples];
290         gtsamples = new float[nSamples];
291
292         fin.open(tmpF, ios::binary);
293         streampos pos = streampos(gi.spAt(ciParams->start_gene_id)) * nSamples * FLOATSIZE;
294         fin.seekg(pos, ios::beg);
295
296         int cnt = 0;
297         for (int i = ciParams->start_gene_id; i < ciParams->end_gene_id; i++) {
298                 int b = gi.spAt(i), e = gi.spAt(i + 1);
299                 memset(gtsamples, 0, FLOATSIZE * nSamples);
300                 for (int j = b; j < e; j++) {
301                         for (int k = 0; k < nSamples; k++) {
302                                 fin.read((char*)(&itsamples[k]), FLOATSIZE);
303                                 gtsamples[k] += itsamples[k];
304                         }
305                         calcCI(nSamples, itsamples, iso_tau[j].lb, iso_tau[j].ub);
306                 }
307                 calcCI(nSamples, gtsamples, gene_tau[i].lb, gene_tau[i].ub);
308
309                 ++cnt;
310                 if (verbose && cnt % 1000 == 0) { printf("In thread %d, %d genes are processed for CI calculation!\n", ciParams->no, cnt); }
311         }
312
313         fin.close();
314
315         delete[] itsamples;
316         delete[] gtsamples;
317
318         return NULL;
319 }
320
321 void calculate_credibility_intervals(char* imdName) {
322         FILE *fo;
323         char outF[STRLEN];
324         int num_threads = nThreads;
325
326         iso_tau = new CIType[M + 1];
327         gene_tau = new CIType[m];
328
329         assert(M > 0);
330         int quotient = M / num_threads;
331         if (quotient < 1) { num_threads = M; quotient = 1; }
332         int cur_gene_id = 0;
333         int num_isoforms = 0;
334
335         // A just so so strategy for paralleling
336         ciParamsArray = new CIParams[num_threads];
337         for (int i = 0; i < num_threads; i++) {
338                 ciParamsArray[i].no = i;
339                 ciParamsArray[i].start_gene_id = cur_gene_id;
340                 num_isoforms = 0;
341
342                 while ((m - cur_gene_id > num_threads - i - 1) && (i == num_threads - 1 || num_isoforms < quotient)) {
343                         num_isoforms += gi.spAt(cur_gene_id + 1) - gi.spAt(cur_gene_id);
344                         ++cur_gene_id;
345                 }
346
347                 ciParamsArray[i].end_gene_id = cur_gene_id;
348         }
349
350         threads = new pthread_t[num_threads];
351
352         /* set thread attribute to be joinable */
353         pthread_attr_init(&attr);
354         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
355
356         // paralleling
357         for (int i = 0; i < num_threads; i++) {
358                 rc = pthread_create(&threads[i], &attr, &calcCI_batch, (void*)(&ciParamsArray[i]));
359                 pthread_assert(rc, "pthread_create", "Cannot create thread " + itos(i) + " (numbered from 0) in calculate_credibility_intervals!");
360         }
361         for (int i = 0; i < num_threads; i++) {
362                 rc = pthread_join(threads[i], &status);
363                 pthread_assert(rc, "pthread_join", "Cannot join thread " + itos(i) + " (numbered from 0) in calculate_credibility_intervals!");
364         }
365
366         // releasing resources
367
368         /* destroy attribute */
369         pthread_attr_destroy(&attr);
370         delete[] threads;
371
372         delete[] ciParamsArray;
373
374         //isoform level results
375         sprintf(outF, "%s.iso_res", imdName);
376         fo = fopen(outF, "a");
377         for (int i = 1; i <= M; i++)
378                 fprintf(fo, "%.6g%c", iso_tau[i].lb, (i < M ? '\t' : '\n'));
379         for (int i = 1; i <= M; i++)
380                 fprintf(fo, "%.6g%c", iso_tau[i].ub, (i < M ? '\t' : '\n'));
381         fclose(fo);
382
383         //gene level results
384         sprintf(outF, "%s.gene_res", imdName);
385         fo = fopen(outF, "a");
386         for (int i = 0; i < m; i++)
387                 fprintf(fo, "%.6g%c", gene_tau[i].lb, (i < m - 1 ? '\t' : '\n'));
388         for (int i = 0; i < m; i++)
389                 fprintf(fo, "%.6g%c", gene_tau[i].ub, (i < m - 1 ? '\t' : '\n'));
390         fclose(fo);
391
392         delete[] iso_tau;
393         delete[] gene_tau;
394
395         if (verbose) { printf("All credibility intervals are calculated!\n"); }
396 }
397
398 int main(int argc, char* argv[]) {
399         if (argc < 8) {
400                 printf("Usage: rsem-calculate-credibility-intervals reference_name imdName statName confidence nCV nSpC nMB [-p #Threads] [-q]\n");
401                 exit(-1);
402         }
403
404         strcpy(imdName, argv[2]);
405         strcpy(statName, argv[3]);
406
407         confidence = atof(argv[4]);
408         nCV = atoi(argv[5]);
409         nSpC = atoi(argv[6]);
410         nMB = atoi(argv[7]);
411
412         nThreads = 1;
413         quiet = false;
414         for (int i = 8; i < argc; i++) {
415                 if (!strcmp(argv[i], "-p")) nThreads = atoi(argv[i + 1]);
416                 if (!strcmp(argv[i], "-q")) quiet = true;
417         }
418         verbose = !quiet;
419
420         sprintf(refF, "%s.seq", argv[1]);
421         refs.loadRefs(refF, 1);
422         M = refs.getM();
423         sprintf(groupF, "%s.grp", argv[1]);
424         gi.load(groupF);
425         m = gi.getm();
426
427         nSamples = nCV * nSpC;
428         cvlen = M + 1;
429         assert(nSamples > 0 && cvlen > 1); // for Buffter.h: (bufsize_type)nSamples
430
431         sprintf(tmpF, "%s.tmp", imdName);
432         sprintf(cvsF, "%s.countvectors", imdName);
433
434         sprintf(modelF, "%s.model", statName);
435         FILE *fi = fopen(modelF, "r");
436         general_assert(fi != NULL, "Cannot open " + cstrtos(modelF) + "!");
437         assert(fscanf(fi, "%d", &model_type) == 1);
438         fclose(fi);
439
440         // Phase I
441         switch(model_type) {
442         case 0 : sample_theta_vectors_from_count_vectors<SingleModel>(); break;
443         case 1 : sample_theta_vectors_from_count_vectors<SingleQModel>(); break;
444         case 2 : sample_theta_vectors_from_count_vectors<PairedEndModel>(); break;
445         case 3 : sample_theta_vectors_from_count_vectors<PairedEndQModel>(); break;
446         }
447
448         // Phase II
449         calculate_credibility_intervals(imdName);
450
451         /*
452         sprintf(command, "rm -f %s", tmpF);
453         int status = system(command);
454         if (status != 0) {
455                 fprintf(stderr, "Cannot delete %s!\n", tmpF);
456                 exit(-1);
457         }
458         */
459
460         return 0;
461 }