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