-
Notifications
You must be signed in to change notification settings - Fork 21
/
starcode.c
2539 lines (2218 loc) · 66.2 KB
/
starcode.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
** Copyright 2014 Guillaume Filion, Eduard Valera Zorita and Pol Cusco.
**
** File authors:
** Guillaume Filion (guillaume.filion@gmail.com)
** Eduard Valera Zorita (eduardvalera@gmail.com)
**
** License:
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
**
*/
#define _GNU_SOURCE
#include <ctype.h>
#include <errno.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "trie.h"
#include "starcode.h"
#define alert() fprintf(stderr, "error `%s' in %s() (%s:%d)\n",\
strerror(errno), __func__, __FILE__, __LINE__)
#define MAX_K_FOR_LOOKUP 14
#define BISECTION_START 1
#define BISECTION_END -1
#define TRIE_FREE 0
#define TRIE_BUSY 1
#define TRIE_DONE 2
#define STRATEGY_EQUAL 1
#define STRATEGY_PREFIX 99
#define str(a) (char *)(a)
#define min(a,b) (((a) < (b)) ? (a) : (b))
#define max(a,b) (((a) > (b)) ? (a) : (b))
static const int valid_DNA_char[256] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,1,0,1,0,0,0,1,0,0,0,0,0,0,1,0,
0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,
0,1,0,1,0,0,0,1,0,0,0,0,0,0,1,0,
0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
};
static const char capitalize[128] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,123,124,125,126,127
};
struct useq_t;
struct match_t;
typedef enum {
FASTA,
FASTQ,
RAW,
PE_FASTQ,
UNSET,
} format_t;
typedef struct useq_t useq_t;
typedef struct match_t match_t;
typedef struct mtplan_t mtplan_t;
typedef struct mttrie_t mttrie_t;
typedef struct mtjob_t mtjob_t;
typedef struct lookup_t lookup_t;
typedef struct propt_t propt_t;
typedef struct idstack_t idstack_t;
typedef struct sortargs_t sortargs_t;
// The field 'seqid' is either an id number for
// the unique sequence or a pointer to a struct
// containing information about the matches. This
// creates some confusion in the code at times.
// See function 'transfer_useq_ids()'.
struct useq_t {
int count; // Number of sequences
unsigned int nids; // Number of associated sequence IDs
int sphere_c; // Centroid: Size of the sphere.
int sphere_d; // Distance to current sphere centroid. / MP: Ambiguous flag.
char * seq; // Sequence
char * info; // Multi-function text field
gstack_t ** matches; // Matches stratified by distance
struct useq_t * canonical; // Pointer to canonical sequence
int * seqid; // Unique ID / pointer (see above).
};
struct lookup_t {
int slen;
int kmers;
int * klen;
unsigned char * lut[];
};
struct sortargs_t {
useq_t ** buf0;
useq_t ** buf1;
int size;
int b;
int thread;
int repeats;
};
struct mtplan_t {
char active;
int ntries;
int jobsdone;
struct mttrie_t * tries;
pthread_mutex_t * mutex;
pthread_cond_t * monitor;
};
struct mttrie_t {
char flag;
int currentjob;
int njobs;
struct mtjob_t * jobs;
};
struct mtjob_t {
int start;
int end;
int tau;
int build;
int queryid;
int trieid;
gstack_t * useqS;
trie_t * trie;
node_t * node_pos;
lookup_t * lut;
pthread_mutex_t * mutex;
pthread_cond_t * monitor;
int * jobsdone;
char * trieflag;
char * active;
};
struct propt_t {
char first[5];
int pe_fastq;
int showclusters;
int showids;
};
struct idstack_t {
size_t pos;
size_t max;
int * elm;
};
int size_order (const void *a, const void *b);
int addmatch (useq_t*, useq_t*, int, int);
int bisection (int, int, char *, useq_t **, int, int);
int canonical_order (const void*, const void*);
int cluster_count (const void *, const void *);
gstack_t * compute_clusters (gstack_t *);
void connected_components (useq_t *, gstack_t **);
long int count_trie_nodes (useq_t **, int, int);
int sphere_size_order (const void *, const void *);
int count_order (const void *, const void *);
int count_order_spheres (const void *, const void *);
void destroy_useq (useq_t *);
void destroy_lookup (lookup_t *);
void * do_query (void*);
void idstack_free(idstack_t *);
idstack_t* idstack_new(size_t);
void idstack_push(int *, size_t, idstack_t *);
int int_ascending (const void*, const void*);
void krash (void) __attribute__ ((__noreturn__));
int lut_insert (lookup_t *, useq_t *);
int lut_search (lookup_t *, useq_t *);
void message_passing_clustering (gstack_t*);
void mp_resolve_ambiguous(useq_t*);
lookup_t * new_lookup (int, int, int);
useq_t * new_useq (int, char *, char *);
int pad_useq (gstack_t*, int*);
mtplan_t * plan_mt (int, int, int, int, gstack_t *);
void sort_and_print_ids (idstack_t *);
void run_plan (mtplan_t *, int, int);
gstack_t * read_rawseq (FILE *, gstack_t *);
gstack_t * read_fasta (FILE *, gstack_t *);
gstack_t * read_fastq (FILE *, gstack_t *);
gstack_t * read_file (FILE *, FILE *, int);
gstack_t * read_PE_fastq (FILE *, FILE *, gstack_t *);
int seq2id (char *, int);
gstack_t * seq2useq (gstack_t*, int);
int seqsort (useq_t **, int, int);
void sphere_clustering (gstack_t *);
void transfer_counts_and_update_canonicals (useq_t*);
void transfer_sorted_useq_ids (useq_t *, useq_t *);
void transfer_useq_ids (useq_t *, useq_t *);
void unpad_useq (gstack_t*);
void * nukesort (void *);
// Global variables //
static FILE * OUTPUTF1 = NULL; // output file 1
static FILE * OUTPUTF2 = NULL; // output file 2
static format_t FORMAT = UNSET; // input format
static output_t OUTPUTT = DEFAULT_OUTPUT; // output type
static cluster_t CLUSTERALG = MP_CLUSTER; // cluster algorithm
static double CLUSTER_RATIO = 5.0; // min parent/child ratio
// to link clusters
void
head_default
(
useq_t * u,
propt_t propt
)
{
useq_t * cncal = u->canonical;
char * seq = propt.pe_fastq ? cncal->info : cncal->seq;
fprintf(OUTPUTF1, "%s%s\t%d",
propt.first, seq, cncal->count);
if (propt.showclusters) {
char * seq = propt.pe_fastq ? u->info : u->seq;
fprintf(OUTPUTF1, "\t%s", seq);
}
}
void
members_mp_default
(
useq_t * u,
propt_t propt
)
{
if (!propt.showclusters) return;
char * seq = propt.pe_fastq ? u->info : u->seq;
fprintf(OUTPUTF1, ",%s", seq);
}
void
members_sc_default
(
useq_t * u,
propt_t propt
)
{
// Nothing to print if clusters are not shown, or
// if this sequence has no match.
if (!propt.showclusters || u->matches == NULL) return;
gstack_t *hits;
for (int j = 0 ; (hits = u->matches[j]) != TOWER_TOP ; j++) {
for (int k = 0 ; k < hits->nitems ; k++) {
useq_t *match = (useq_t *) hits->items[k];
if (match->canonical != u) continue;
char *seq = propt.pe_fastq ? match->seq : u->seq;
fprintf(OUTPUTF1, ",%s", seq);
}
}
}
void
sort_and_print_ids
(
idstack_t * stack
)
{
// Sort sequence of integers.
qsort(stack->elm, stack->pos, sizeof(int), int_ascending);
// Print ids.
fprintf(OUTPUTF1, "\t%u", stack->elm[0]);
for (unsigned int k = 1; k < stack->pos; k++) {
fprintf(OUTPUTF1, ",%u", stack->elm[k]);
}
}
void
print_nr_raw
(
useq_t * u
)
{
fprintf(OUTPUTF1, "%s\n", u->seq);
}
void
print_nr_fasta
(
useq_t * u
)
{
fprintf(OUTPUTF1, "%s\n%s\n", u->info, u->seq);
}
void
print_nr_fastq
(
useq_t * u
)
{
char header[M] = {0};
char quality[M] = {0};
sscanf(u->info, "%s\n%s", header, quality);
fprintf(OUTPUTF1, "%s\n%s\n+\n%s\n",
header, u->seq, quality);
}
void
print_nr_pe_fastq
(
useq_t * u
)
{
char head1[M] = {0};
char head2[M] = {0};
char qual1[M] = {0};
char qual2[M] = {0};
char seq1[M] = {0};
char seq2[M] = {0};
// Split the sequences.
char *c = strrchr(u->seq, '-');
if (c == NULL || c - u->seq > MAXBRCDLEN) return;
strncpy(seq1, u->seq, c - u->seq - STARCODE_MAX_TAU);
strncpy(seq2, c+1, MAXBRCDLEN);
// Split the info field.
{
char *c = u->info;
strncpy(head1, strsep(&c, "\n"), MAXBRCDLEN);
strncpy(qual1, strsep(&c, "\n"), MAXBRCDLEN);
strncpy(head2, strsep(&c, "\n"), MAXBRCDLEN);
strncpy(qual2, strsep(&c, "\n"), MAXBRCDLEN);
}
// Print to separate files.
fprintf(OUTPUTF1, "%s\n%s\n+\n%s\n",
head1, seq1, qual1);
fprintf(OUTPUTF2, "%s\n%s\n+\n%s\n",
head2, seq2, qual2);
}
int
starcode
(
FILE *inputf1,
FILE *inputf2,
FILE *outputf1,
FILE *outputf2,
int tau,
const int verbose,
int thrmax,
const int clusteralg,
double parent_to_child,
const int showclusters,
const int showids,
const int outputt
)
{
OUTPUTF1 = outputf1;
OUTPUTF2 = outputf2;
OUTPUTT = outputt;
CLUSTERALG = clusteralg;
CLUSTER_RATIO = parent_to_child;
if (verbose) {
fprintf(stderr, "running starcode with %d thread%s\n",
thrmax, thrmax > 1 ? "s" : "");
fprintf(stderr, "reading input files\n");
}
gstack_t *uSQ = read_file(inputf1, inputf2, verbose);
if (uSQ == NULL || uSQ->nitems < 1) {
fprintf(stderr, "input file empty\n");
return 1;
}
// Sort/reduce.
if (verbose) fprintf(stderr, "sorting\n");
uSQ->nitems = seqsort((useq_t **) uSQ->items, uSQ->nitems, thrmax);
// Get number of tries.
int ntries = 3 * thrmax + (thrmax % 2 == 0);
if (uSQ->nitems < ntries) {
ntries = 1;
thrmax = 1;
}
// Pad sequences (and return the median size).
// Compute 'tau' from it in "auto" mode.
int med = -1;
int height = pad_useq(uSQ, &med);
if (tau < 0) {
tau = med > 160 ? 8 : 2 + med/30;
if (verbose) {
fprintf(stderr, "setting dist to %d\n", tau);
}
}
// Make multithreading plan.
mtplan_t *mtplan = plan_mt(tau, height, med, ntries, uSQ);
// Run the query.
run_plan(mtplan, verbose, thrmax);
if (verbose) fprintf(stderr, "progress: 100.00%%\n");
// Remove padding characters.
unpad_useq(uSQ);
//
// MESSAGE PASSING ALGORITHM
//
propt_t propt = {
.first = {0},
.showclusters = showclusters,
.showids = showids,
.pe_fastq = PE_FASTQ == FORMAT,
};
if (CLUSTERALG == MP_CLUSTER) {
if (verbose) fprintf(stderr, "message passing clustering\n");
// Cluster the pairs.
message_passing_clustering(uSQ);
// Sort in canonical order.
qsort(uSQ->items, uSQ->nitems, sizeof(useq_t *), canonical_order);
if (OUTPUTT == DEFAULT_OUTPUT) {
useq_t *first = (useq_t *) uSQ->items[0];
useq_t *canonical = first->canonical;
// If the first canonical is NULL, then they all are.
if (first->canonical == NULL) return 0;
head_default(first, propt);
// Use newline separator.
memcpy(propt.first, "\n", 3);
// Store sequence ids for the current cluster in a stack.
idstack_t * idstack = NULL;
if (showids) {
idstack = idstack_new(64);
idstack_push(first->seqid, first->nids, idstack);
}
// Run through the clustered items.
for (int i = 1 ; i < uSQ->nitems ; i++) {
useq_t *u = (useq_t *) uSQ->items[i];
if (u->canonical == NULL) {
break;
}
if (u->canonical != canonical) {
// Print cluster seqIDs of previous canonical.
if (showids) sort_and_print_ids(idstack);
// Update canonical and print.
canonical = u->canonical;
head_default(u, propt);
// Reset seq_id stack.
if (showids)
idstack->pos = 0;
}
else {
members_mp_default(u, propt);
}
// Update seqid list.
if (showids)
idstack_push(u->seqid, u->nids, idstack);
}
// Print last cluster seqIDs.
if (showids) {
sort_and_print_ids(idstack);
idstack_free(idstack);
}
fprintf(OUTPUTF1, "\n");
}
//
// SPHERES ALGORITHM
//
} else if (CLUSTERALG == SPHERES_CLUSTER) {
if (verbose) fprintf(stderr, "spheres clustering\n");
// Cluster the pairs.
sphere_clustering(uSQ);
// Sort in count order.
qsort(uSQ->items, uSQ->nitems, sizeof(useq_t *), sphere_size_order);
// Default output.
if (OUTPUTT == DEFAULT_OUTPUT) {
// Sequence id stack.
idstack_t * idstack = NULL;
if (showids) idstack = idstack_new(64);
for (int i = 0 ; i < uSQ->nitems ; i++) {
useq_t *u = (useq_t *) uSQ->items[i];
if (u->canonical != u) break;
fprintf(OUTPUTF1, "%s\t", u->seq);
if (showclusters) {
fprintf(OUTPUTF1, "%d\t%s", u->sphere_c, u->seq);
}
else {
fprintf(OUTPUTF1, "%d", u->sphere_c);
}
// Reset stack and add canonical ids.
if (showids) {
idstack->pos = 0;
idstack_push(u->seqid, u->nids, idstack);
}
// Get sequences and ids from matches.
if ((showclusters || showids) && u->matches != NULL) {
gstack_t *hits;
for (int j = 0 ; (hits = u->matches[j]) != TOWER_TOP ; j++) {
for (int k = 0 ; k < hits->nitems ; k++) {
useq_t *match = (useq_t *) hits->items[k];
if (match->canonical != u) continue;
if (showclusters) fprintf(OUTPUTF1, ",%s", match->seq);
if (showids) idstack_push(match->seqid, match->nids, idstack);
}
}
}
// Print cluster seqIDs.
if (showids) sort_and_print_ids(idstack);
fprintf(OUTPUTF1, "\n");
}
if (showids) idstack_free(idstack);
}
/*
* CONNECTED COMPONENTS ALGORITHM
*/
} else if (CLUSTERALG == COMPONENTS_CLUSTER) {
if (verbose) fprintf(stderr, "connected components clustering\n");
// Cluster connected components.
// Returns a stack containing stacks of clusters, where clusters->item[i]->item[0] is
// the centroid of the i-th cluster. The output is sorted by cluster count, which is
// stored in centroid->count.
gstack_t * clusters = compute_clusters(uSQ);
// Default output.
if (OUTPUTT == DEFAULT_OUTPUT) {
idstack_t * idstack = NULL;
if (showids) idstack = idstack_new(64);
for (int i = 0; i < clusters->nitems; i++) {
gstack_t * cluster = (gstack_t *) clusters->items[i];
// Get canonical.
useq_t * canonical = (useq_t *) cluster->items[0];
// Print canonical and cluster count.
fprintf(OUTPUTF1, "%s\t%d", canonical->seq, canonical->count);
if (showclusters || showids) {
fprintf (OUTPUTF1, "\t%s", canonical->seq);
if (showids) {
idstack->pos = 0;
idstack_push(canonical->seqid, canonical->nids, idstack);
}
for (int k = 1; k < cluster->nitems; k++) {
useq_t * u = (useq_t *) cluster->items[k];
if (showclusters) fprintf (OUTPUTF1, ",%s", u->seq);
if (showids) idstack_push(u->seqid, u->nids, idstack);
}
if (showids) sort_and_print_ids(idstack);
}
fprintf(OUTPUTF1, "\n");
}
if (showids) idstack_free(idstack);
} else if (OUTPUTT == NRED_OUTPUT) {
uSQ->nitems = 0;
// Fill uSQ with cluster centroids.
for (int i = 0 ; i < clusters->nitems ; i++)
push(((gstack_t *)clusters->items[i])->items[0], &uSQ);
}
}
/*
* ALTERNATIVE OUTPUT FORMAT: NON-REDUNDANT
*/
if (OUTPUTT == NRED_OUTPUT) {
if (verbose) fprintf(stderr, "non-redundant output\n");
// If print non redundant sequences, just print the
// canonicals with their info.
void (* print_nr) (useq_t *) = {0};
if (FORMAT == FASTA) print_nr = print_nr_fasta;
else if (FORMAT == FASTQ) print_nr = print_nr_fastq;
else if (FORMAT == PE_FASTQ) print_nr = print_nr_pe_fastq;
else print_nr = print_nr_raw;
for (int i = 0 ; i < uSQ->nitems ; i++) {
useq_t *u = (useq_t *) uSQ->items[i];
if (u->canonical == NULL) break;
if (u->canonical != u) continue;
print_nr(u);
}
}
// Do not free anything.
OUTPUTF1 = NULL;
OUTPUTF2 = NULL;
return 0;
}
void
run_plan
(
mtplan_t *mtplan,
const int verbose,
const int thrmax
)
{
// Count total number of jobs.
int njobs = mtplan->ntries * (mtplan->ntries+1) / 2;
// Thread Scheduler
int triedone = 0;
int idx = -1;
while (triedone < mtplan->ntries) {
// Cycle through the tries in turn.
idx = (idx+1) % mtplan->ntries;
mttrie_t *mttrie = mtplan->tries + idx;
pthread_mutex_lock(mtplan->mutex);
// Check whether trie is idle and there are available threads.
if (mttrie->flag == TRIE_FREE && mtplan->active < thrmax) {
// No more jobs on this trie.
if (mttrie->currentjob == mttrie->njobs) {
mttrie->flag = TRIE_DONE;
triedone++;
}
// Some more jobs to do.
else {
mttrie->flag = TRIE_BUSY;
mtplan->active++;
mtjob_t *job = mttrie->jobs + mttrie->currentjob++;
pthread_t thread;
// Start job and detach thread.
if (pthread_create(&thread, NULL, do_query, job)) {
alert();
krash();
}
pthread_detach(thread);
if (verbose) {
fprintf(stderr, "progress: %.2f%% \r",
100*(float)(mtplan->jobsdone)/njobs);
}
}
}
// If max thread number is reached, wait for a thread.
while (mtplan->active == thrmax) {
pthread_cond_wait(mtplan->monitor, mtplan->mutex);
}
pthread_mutex_unlock(mtplan->mutex);
}
return;
}
void *
do_query
(
void * args
)
{
// Unpack arguments.
mtjob_t * job = (mtjob_t*) args;
gstack_t * useqS = job->useqS;
trie_t * trie = job->trie;
lookup_t * lut = job->lut;
const int tau = job->tau;
node_t * node_pos = job->node_pos;
// Create local hit stack.
gstack_t **hits = new_tower(tau+1);
if (hits == NULL) {
alert();
krash();
}
// Define a constant to help the compiler recognize
// that only one of the two cases will ever be used
// in the loop below.
const int bidir_match = (CLUSTERALG == SPHERES_CLUSTER || CLUSTERALG == COMPONENTS_CLUSTER);
useq_t * last_query = NULL;
for (int i = job->start ; i <= job->end ; i++) {
useq_t *query = (useq_t *) useqS->items[i];
int do_search = lut_search(lut, query) == 1;
// Insert the new sequence in the lut and trie, but let
// the last pointer to NULL so that the query does not
// find itself upon search.
void **data = NULL;
if (job->build) {
if (lut_insert(lut, query)) {
alert();
krash();
}
data = insert_string_wo_malloc(trie, query->seq, &node_pos);
if (data == NULL || *data != NULL) {
alert();
krash();
}
}
if (do_search) {
int trail = 0;
if (i < job->end) {
useq_t *next_query = (useq_t *) useqS->items[i+1];
// The 'while' condition is guaranteed to be false
// before the end of the 'char' arrays because all
// the queries have the same length and are different.
while (query->seq[trail] == next_query->seq[trail]) {
trail++;
}
}
// Compute start height.
int start = 0;
if (last_query != NULL) {
while(query->seq[start] == last_query->seq[start]) start++;
}
// Clear hit stack. //
for (int j = 0 ; hits[j] != TOWER_TOP ; j++) {
hits[j]->nitems = 0;
}
// Search the trie. //
int err = search(trie, query->seq, tau, hits, start, trail);
if (err) {
alert();
krash();
}
for (int j = 0 ; hits[j] != TOWER_TOP ; j++) {
if (hits[j]->nitems > hits[j]->nslots) {
fprintf(stderr, "warning: incomplete search (%s)\n",
query->seq);
break;
}
}
// Link matching pairs for clustering.
// Skip dist = 0, as this would be self.
for (int dist = 1 ; dist < tau+1 ; dist++) {
for (int j = 0 ; j < hits[dist]->nitems ; j++) {
useq_t *match = (useq_t *) hits[dist]->items[j];
if (bidir_match) {
// Make a bidirectional match reference.
// Add reference from query to matched node.
pthread_mutex_lock(job->mutex + job->queryid);
if (addmatch(query, match, dist, tau)) {
fprintf(stderr,
"Please contact guillaume.filion@gmail.com "
"for support with this issue.\n");
abort();
}
pthread_mutex_unlock(job->mutex + job->queryid);
// Add reference from matched node to query.
pthread_mutex_lock(job->mutex + job->trieid);
if (addmatch(match, query, dist, tau)) {
fprintf(stderr,
"Please contact guillaume.filion@gmail.com "
"for support with this issue.\n");
abort();
}
pthread_mutex_unlock(job->mutex + job->trieid);
}
else {
// The parent is the sequence with highest count.
// For ties, parent is the query and child is the match.
// Matches are stored in child only (i.e. children
// know their parents).
useq_t *parent = match->count > query->count ? match : query;
useq_t *child = match->count > query->count ? query : match;
// If clustering is done by message passing, do not link
// pair if counts are on the same order of magnitude.
int mincount = child->count;
int maxcount = parent->count;
if (maxcount < CLUSTER_RATIO * mincount) continue;
// In case CLUSTER_RATIO is set to 1, set parent to the
// lexicographically smaller. This will avoid circular
// parent references that produce infinite loops when
// clustering.
if (maxcount == mincount) {
if (strcmp(parent->seq, child->seq) > 0) {
useq_t * t = parent;
parent = child;
child = t;
}
}
// The child is modified, use the child mutex.
int mutexid = parent == query ? job->trieid : job->queryid;
pthread_mutex_lock(job->mutex + mutexid);
if (addmatch(child, parent, dist, tau)) {
fprintf(stderr,
"Please contact guillaume.filion@gmail.com "
"for support with this issue.\n");
abort();
}
pthread_mutex_unlock(job->mutex + mutexid);
}
}
}
last_query = query;
}
if (job->build) {
// Finally set the pointer of the inserted tail node.
*data = query;
}
}
destroy_tower(hits);
// Flag trie, update thread count and signal scheduler.
// Use the general mutex. (job->mutex[0])
pthread_mutex_lock(job->mutex);
*(job->active) -= 1;
*(job->jobsdone) += 1;
*(job->trieflag) = TRIE_FREE;
pthread_cond_signal(job->monitor);
pthread_mutex_unlock(job->mutex);
return NULL;
}
mtplan_t *
plan_mt
(
int tau,
int height,
int medianlen,
int ntries,
gstack_t *useqS
)
// SYNOPSIS:
// The scheduler makes the key assumption that the number of tries is
// an odd number, which allows to distribute the jobs among as in the
// example shown below. The rows indicate blocks of query strings and
// the columns are distinct tries. An circle (o) indicates a build job,
// a cross (x) indicates a query job, and a dot (.) indicates that the
// block is not queried in the given trie.
//
// --- Tries ---
// 1 2 3 4 5
// 1 o . . x x
// 2 x o . . x
// 3 x x o . .
// 4 . x x o .
// 5 . . x x o
//
// This simple schedule ensures that each trie is built from one query
// block and that each block is queried against every other exactly one
// time (a query of block i in trie j is the same as a query of block j
// in trie i).
{
if (ntries < 1) {
alert();
krash();
}
// Initialize plan.
mtplan_t *mtplan = malloc(sizeof(mtplan_t));
if (mtplan == NULL) {
alert();
krash();
}
// Initialize mutex.
pthread_mutex_t *mutex = calloc(ntries + 1, sizeof(pthread_mutex_t));
pthread_cond_t *monitor = malloc(sizeof(pthread_cond_t));
if (mutex == NULL || monitor == NULL) {
alert();
krash();
}
for (int i = 0; i < ntries + 1; i++) pthread_mutex_init(mutex + i,NULL);
pthread_cond_init(monitor,NULL);
// Initialize 'mttries'.
mttrie_t *mttries = calloc(ntries, sizeof(mttrie_t));
if (mttries == NULL) {
alert();
krash();
}
// Boundaries of the query blocks.
int Q = useqS->nitems / ntries;
int R = useqS->nitems % ntries;
int *bounds = calloc(ntries+1, sizeof(int));
for (int i = 0 ; i < ntries+1 ; i++) bounds[i] = Q*i + min(i, R);
// Preallocated tries.
// Count with maxlen-1
long *nnodes = calloc(ntries, sizeof(long));
for (int i = 0; i < ntries; i++) nnodes[i] =
count_trie_nodes((useq_t **)useqS->items, bounds[i], bounds[i+1]);
// Create jobs for the tries.
for (int i = 0 ; i < ntries; i++) {
// Remember that 'ntries' is odd.
int njobs = (ntries+1)/2;
trie_t *local_trie = new_trie(height);
node_t *local_nodes = (node_t *) calloc(nnodes[i], sizeof(node_t));
mtjob_t *jobs = calloc(njobs, sizeof(mtjob_t));
if (local_trie == NULL || jobs == NULL) {
alert();
krash();
}
// Allocate lookup struct.
// TODO: Try only one lut as well. (It will always return 1
// in the query step though). #
lookup_t * local_lut = new_lookup(medianlen, height, tau);
if (local_lut == NULL) {
alert();
krash();
}
mttries[i].flag = TRIE_FREE;
mttries[i].currentjob = 0;
mttries[i].njobs = njobs;
mttries[i].jobs = jobs;
for (int j = 0 ; j < njobs ; j++) {
// Shift boundaries in a way that every trie is built
// exactly once and that no redundant jobs are allocated.
int idx = (i+j) % ntries;