-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild_repeat_families.c
2269 lines (2041 loc) · 67.1 KB
/
build_repeat_families.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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <math.h>
#include "cmd_line_opts.h"
#include "build_repeat_families.h"
/* build_repeat_families.c -- build list of repeat families */
// RMH: From Version.c created by the Makefile
extern const char *Version;
int MAXLENGTH; /* Length of sequence. It's a misnomer, primarily for backwards compatability. */
#define PADLENGTH 11000 /* should be >= L+MAXOFFSET */
int l; /* Length of l-mers to look at. Odd or even is OK */
#define smalll 6
#define SEEDMISMATCHES 0 /* allow this many mismatches from seed */
#define HASH_SIZE 16000057 /* prime */
#define SMALLHASH_SIZE 5003 /* prime */
char* SEQUENCE_FILE; /* Where to get sequence data from. */
char* OUTPUT_FILE; /* Where to put output. */
char* LMER_TABLE_FILE; /* Where the lmer table is stored. */
char* RANGES_FILE = NULL; /* Where to put the extended sequence ranges. */
int MINTHRESH; /* at end, remove l-mers with freq < MINTHRESH */
int TANDEMDIST; /* l-mers must be this far apart to avoid tandem repeats */
int VERBOSE; /* How chatty? Real chatty? Really really chatty? Super extra really chatty? */
int L; /* How far to extend. max total length of master is 2*L+l (L >>> l) */
int MAXOFFSET; /* max offset (5) */
int MAXN; /* max #occ of lmer (10000) */
int MAXR; /* max #families (100000) */
int MATCH; /* match score (1) */
int MISMATCH; /* mismatch score (-1) */
int GAP; /* gap (indel) score (-5) */
int CAPPENALTY; /* cap on penalty for exiting alignment (-20) */
int MINIMPROVEMENT; /* amount totalbestscore must improve for each extra letter (3) */
int WHEN_TO_STOP; /* stop if no improvement after extending this far (500) */
#define REMOVE_DEGENERATES 0
#define EXTRAMASK 1 /* default is 1 */
float MAXENTROPY; /* ignore freq l-mers with entropy greater than this (-0.70) */
int GOODLENGTH; /* minimum length of a good subfamily (50) */
int default_l(int);
/*
* -------- Internal global variables --------
*/
int length; /* length of genome sequence */
char *sequence; /* [2*MAXLENGTH+3*PADLENGTH]; */
char *removed; /* [2*MAXLENGTH+3*PADLENGTH]; */
char *master;
char **masters; /* MAXR * (2*L+l) but allocate dynamically */
int *masters_allocated;
int *masterstart;
int *masterend;
int *pos;
char *rev; // RMH: Flag indicating if N is a forward/reverse strand lmer
int *upperBoundI; // RMH: Index into boundaries for lmer upper sequence bound
int N;
int ***score; /* 2 * MAXN * (2*MAXOFFSET+1) */
int **score_of_besty; /* MAXN * (2*MAXOFFSET+1) */
int **maskscore; /* 2 * (2*MAXOFFSET+1) */
/* Reduce memory use by freeing once no longer needed */
int totalbestscore; /* alignment score for this y or w */
int besttotalbestscore; /* best alignment score for any y or w seen so far */
int *bestbestscore; /* best alignment score for this n for any y or w seen so far */
int *savebestscore;
// RMH: Added to keep track of the best left and right offsets
int *best_left_offset;
int *save_left_offset;
int *best_right_offset;
int *save_right_offset;
// RMH: Added to support sequence identifiers
char **sequence_ids = NULL;
int besty, bestw, nrepeatocc, nactiverepeatocc, bestnrepeatocc, bestnactiverepeatocc, R;
int bestrepeaty, bestsequencey, bestrepeatw, bestsequencew, repeat2sequence;
int maxrepeaty, minrepeatw;
int **distmat;
int prevbestfreq, prevbesthash;
int *boundaries; // RMH: Fasta sequence boundaries. This contains
// a non-zero ( zero-based ) position for the
// start of each sequence. The first sequence
// position is assumed to be 0 and therefore is
// not stored in this array. ( NOTE: This is the
// pre "PADLENGTH" padded position.
#define IUPAC(c) c == 'R' || c=='r' || c=='Y' || c=='y' || c=='M' || c=='m' || c=='K' || c=='k' || c=='W' || c=='w' || c=='S' || c=='s' || c=='B' || c=='b' || c=='D' || c=='d' || c=='H' || c=='h' || c=='V' || c=='v'
void usage()
{
fprintf(stderr, "RepeatScout Version %s\n\nUsage: \n"
"RepeatScout [opts][-ranges <file>] -sequence <file> -output <file> -freq <file> -l #\n"
" -sequence <file> # file containing sequence data (FASTA format)\n"
" -output <file> # file to write identified consensi to (FASTA format)\n"
" -freq <file> # file containing l-mer frequency table\n"
" -l # # length of l-mers to use (must be same as frequency file)\n"
" -ranges <file> # file to save the extended sequence ranges (optional)\n"
"\n"
" -L # size of region to extend left or right (10000) \n"
" -match # reward for a match (+1) \n"
" -mismatch # penalty for a mismatch (-1) \n"
" -gap # penalty for a gap (-5)\n"
" -maxgap # maximum number of gaps allowed (5) \n"
" -maxoccurrences # cap on the number of sequences to align (10,000) \n"
" -maxrepeats # stop work after reporting this number of repeats (10000)\n"
" -cappenalty # cap on penalty for exiting alignment of a sequence (-20)\n"
" -tandemdist # of bases that must intervene between two l-mers for both to be counted (500)\n"
" -minthresh # stop if fewer than this number of l-mers are found in the seeding phase (3)\n"
" -minimprovement # amount that a the alignment needs to improve each step to be considered progress (3)\n"
" -stopafter # stop the alignment after this number of no-progress columns (100)\n"
" -goodlength # minimum required length for a sequence to be reported (50)\n"
" -maxentropy # entropy (complexity) threshold for an l-mer to be considered (-.7)\n"
" -v[v[v[v]]] How verbose do you want it to be? -vvvv is super-verbose.\n",
Version );
exit(1);
}
int main(int argc, char* argv[])
{
time_t start, finish;
double duration;
int x;
struct llist **headptr;
struct llist *besttmp;
FILE *fp;
FILE *ranges_fp = NULL;
start = time(0);
if( 0 == 1 *
co_get_string(argc, argv, "-sequence", &SEQUENCE_FILE) *
co_get_string(argc, argv, "-output", &OUTPUT_FILE) *
co_get_string(argc, argv, "-freq", &LMER_TABLE_FILE)
) {
usage();
exit(1);
}
fp = fopen(SEQUENCE_FILE, "ro");
if( NULL == fp ) {
fprintf(stderr, "Could not open sequence file %s\n", SEQUENCE_FILE);
exit(1);
}
fseek(fp, 0, SEEK_END);
MAXLENGTH = ftell(fp);
fclose(fp);
(void)(co_get_int(argc, argv, "-l", &l) || (l = default_l(MAXLENGTH)));
co_get_string(argc, argv, "-ranges", &RANGES_FILE);
sequence = (char *) malloc( (2 * MAXLENGTH + 3 * PADLENGTH) * sizeof(char) );
if( NULL == sequence ) {
fprintf(stderr, "Could not allocate space for sequence\n");
exit(1);
}
removed = (char *) malloc( (2 * MAXLENGTH + 3 * PADLENGTH) * sizeof(char) );
if( NULL == removed ) {
fprintf(stderr, "Could not allocate space for masking array\n");
exit(1);
}
co_get_int(argc, argv, "-L", &L) || (L=10000);
co_get_int(argc, argv, "-match", &MATCH) || (MATCH=1);
co_get_int(argc, argv, "-mismatch", &MISMATCH) || (MISMATCH=-1);
co_get_int(argc, argv, "-gap", &GAP) || (GAP=-5);
co_get_int(argc, argv, "-maxgap", &MAXOFFSET) || (MAXOFFSET=5);
co_get_int(argc, argv, "-maxoccurrences", &MAXN) || (MAXN = 10000);
co_get_int(argc, argv, "-maxrepeats", &MAXR) || (MAXR = 100000);
co_get_int(argc, argv, "-cappenalty", &CAPPENALTY) || (CAPPENALTY=-20);
co_get_int(argc, argv, "-minimprovement", &MINIMPROVEMENT) || (MINIMPROVEMENT=3);
co_get_int(argc, argv, "-stopafter", &WHEN_TO_STOP) || (WHEN_TO_STOP=100);
(void)(co_get_float(argc, argv, "-maxentropy", &MAXENTROPY)|| (MAXENTROPY=-0.7));
co_get_int(argc, argv, "-goodlength", &GOODLENGTH) || (GOODLENGTH=50);
co_get_int(argc, argv, "-tandemdist", &TANDEMDIST) || (TANDEMDIST=500);
co_get_int(argc, argv, "-minthresh", &MINTHRESH) || (MINTHRESH=3);
VERBOSE = co_get_bool(argc, argv, "-v", &x) ? 1 :
co_get_bool(argc, argv, "-vv", &x) ? 2 :
co_get_bool(argc, argv, "-vvv", &x) ? 3 :
co_get_bool(argc, argv, "-vvvv", &x) ? 20: 0;
master = (char *)malloc( (2*L+l+1) * sizeof(char));
master[2*L+l] = '\0';
if( NULL == master ) {
fprintf(stderr, "Could not allocate space for master array\n");
exit(1);
}
masters_allocated = (int *)malloc( MAXR * sizeof(int) );
if( NULL == masters_allocated ) {
fprintf(stderr, "Could not allocated space for the master's allocation table\n");
exit(1);
}
masterstart = (int *)malloc( MAXR * sizeof(int) );
if( NULL == masterstart ) {
fprintf(stderr, "Could not allocated space for the master start positions\n");
exit(1);
}
masterend = (int *)malloc( MAXR * sizeof(int) );
if( NULL == masterend) {
fprintf(stderr, "Could not allocated space for the master stop positions\n");
exit(1);
}
// RMH: Initialize the rev array
rev = (char *)malloc( MAXN * sizeof(char) );
if( NULL == rev ) {
fprintf(stderr, "Could not allocated space for the reversed array\n");
exit(1);
}
// RMH: Initialize the upperBoundI array
upperBoundI = (int *)malloc( MAXN * sizeof(int) );
if( NULL == upperBoundI ) {
fprintf(stderr, "Could not allocated space for the upperBoundI array\n");
exit(1);
}
pos = (int *)malloc( MAXN * sizeof(int) );
if( NULL == pos ) {
fprintf(stderr, "Could not allocated space for the position array\n");
exit(1);
}
bestbestscore = (int *)malloc( MAXN * sizeof(int) );
savebestscore = (int *)malloc( MAXN * sizeof(int) );
if( NULL == bestbestscore || NULL == savebestscore ) {
fprintf(stderr, "Could not allocated space for internal arrays\n");
exit(1);
}
// RMH: Added to keep track of the best left and right offsets
best_left_offset = (int *)malloc( MAXN * sizeof(int) );
save_left_offset = (int *)malloc( MAXN * sizeof(int) );
best_right_offset = (int *)malloc( MAXN * sizeof(int) );
save_right_offset = (int *)malloc( MAXN * sizeof(int) );
if ( NULL == best_left_offset || NULL == save_left_offset ||
NULL == best_right_offset || NULL == save_right_offset ) {
fprintf(stderr, "Could not allocated space for the best offset arrays\n");
exit(1);
}
for(int n=0; n<MAXN; n++)
{
best_left_offset[n] = -1;
save_left_offset[n] = -1;
best_right_offset[n] = -1;
save_right_offset[n] = -1;
}
/* print parameters */
if(VERBOSE) print_parameters();
/* build sequence */
length = build_sequence(sequence,SEQUENCE_FILE);
// RMH: This is no longer needed. We use one copy of
// the sequence now. Saves space and makes further
// modifications easier.
//add_rc(sequence); if(VERBOSE) fprintf(stderr,"Done building sequence\n");
for(x=0; x<length; x++) removed[x] = 0;
/* allocate space */
allocate_space();
/* build headptr */
if((headptr = (struct llist **) malloc(HASH_SIZE*sizeof(*headptr))) == NULL)
{
fprintf(stderr,"Out of memory\n"); exit(1);
}
if(VERBOSE) fprintf(stderr,"Done allocating headptr\n");
build_headptr(headptr);
if(VERBOSE) fprintf(stderr,"Done building headptr\n");
if( (fp = fopen(OUTPUT_FILE, "w")) == NULL)
{
fprintf(stderr,"Could not open input file %s\n", OUTPUT_FILE); exit(1);
}
if ( RANGES_FILE != NULL )
{
if( (ranges_fp = fopen(RANGES_FILE, "w")) == NULL)
{
fprintf(stderr,"Could not open input file %s\n", RANGES_FILE); exit(1);
}
}
R = 0;
prevbestfreq = 1000000000;
prevbesthash = 0;
while(1)
{
besttmp = find_besttmp(headptr);
if((besttmp == NULL) || (besttmp->freq < MINTHRESH)) /* 2nd cond added 6/9/04 */
{
if(VERBOSE) printf("Stopped at R=%d since no more frequent l-mers\n",R);
if(VERBOSE) fprintf(stderr,"Stopped at R=%d since no more frequent l-mers\n",R);
break;
}
/* build master */
for(x=0; x<l; x++) master[L+x] = sequence[(besttmp->lastocc)+x];
build_pos(besttmp); /* computes N */
// RMH: Added because I was seeing some strange cases.
if ( N < MINTHRESH )
{
printf("Warning: N ( %d ) is less than MINTHRESH ( %d ) yet "
"besttmp->freq = %d....hmmm\nlmer = ",
N, MINTHRESH, besttmp->freq );
for(x=0; x<l; x++)
printf("%c", num_to_char( sequence[(besttmp->lastocc)+x] ) );
printf("\nh = %d\n", prevbesthash );
besttmp->freq = N;
continue;
}
// RMH: New in 1.0.7 these arrays keep track of the absolute high scoring
// left and right extension offsets (best_left/best_right) and the
// highest seen at the time the MSA was scoring highest (save_left/save_right).
for(int n=0; n<N; n++)
{
best_left_offset[n] = -1;
save_left_offset[n] = -1;
best_right_offset[n] = -1;
save_right_offset[n] = -1;
}
if(masters_allocated[R] == 0)
{
if((masters[R] = (char *) malloc((2*L+l)*sizeof(*masters[R]))) == NULL)
{ fprintf(stderr,"Out of memory\n"); exit(1); }
masters_allocated[R] = 1;
}
// Do the extensions
extend_right();
extend_left();
// RMH: New in 1.0.7, print the extended ranges to the ranges file (if specified)
if ( ranges_fp != NULL )
{
for(int n=0; n<N; n++) {
x = 0;
while ( boundaries[x] != 0 )
{
if ( boundaries[x] + PADLENGTH > pos[n] )
break;
x++;
}
int seq_idx = x;
int seq_lower_bound = PADLENGTH;
if ( seq_idx > 0 )
seq_lower_bound = boundaries[seq_idx-1]+PADLENGTH;
int left_ext = 0;
int right_ext = 0;
if ( save_left_offset[n] >= 0 )
left_ext = L-save_left_offset[n] - 1;
if ( save_right_offset[n] >= 0 )
right_ext = save_right_offset[n]-l-L;
int int_start = 0;
int int_end = 0;
if ( rev[n] ) {
int_start = pos[n]-right_ext;
int_end = pos[n]+l+left_ext;
}else {
int_start = pos[n]-left_ext;
int_end = pos[n]+l+right_ext;
}
int seq_start = int_start - seq_lower_bound;
int seq_end = int_end - seq_lower_bound;
// As with the normal output routines only save families that
// meet the GOODLENGTH criteria, and in this case only save
// examplars that also meet the GOODLENGTH criteria.
if (masterend[R]-masterstart[R]+1 >= GOODLENGTH &&
int_end-int_start+1 >= GOODLENGTH) {
if ( rev[n] ) {
fprintf(ranges_fp,"%s\t%d\t%d\tR=%d\t-\t%d\t%d\t%d\n",
sequence_ids[seq_idx],seq_start,seq_end+1,R,pos[n]-seq_lower_bound,left_ext,right_ext);
}else {
fprintf(ranges_fp,"%s\t%d\t%d\tR=%d\t+\t%d\t%d\t%d\n",
sequence_ids[seq_idx],seq_start,seq_end+1,R,pos[n]-seq_lower_bound,left_ext,right_ext);
}
}
// RMH: In the future we may want to save the actual sequences to a FASTA file. For now
// I am leaving this in here for debugging purposes.
//for(x=0; x<(int_end-int_start+1); x++) fprintf(ranges_fp,"%c",num_to_char(sequence[int_start+x]));
//fprintf(ranges_fp,"\n");
}
}
if(masterend[R]-masterstart[R]+1 >= GOODLENGTH)
{
if(VERBOSE)
{
printf("R=%d: Master lmer hit is ",R);
for(x=0; x<l; x++) printf("%c",num_to_char(master[L+x]));
printf("\n");
fprintf(stderr,"R=%d: Master lmer hit is ",R);
for(x=0; x<l; x++) fprintf(stderr,"%c",num_to_char(master[L+x]));
fprintf(stderr,"\n");
}
if((SEEDMISMATCHES == 0) && (N != MAXN) && (N != besttmp->freq))
{
if(VERBOSE) fprintf(stderr,"WARNING N=%d but goodfreq=%d\n",N,besttmp->freq); /* exit(1); */
if(VERBOSE) printf("WARNING N=%d but goodfreq=%d\n",N,besttmp->freq); /* exit(1); */
}
fprintf(fp,">R=%d\n",R);
for(x=masterstart[R]; x<=masterend[R]; x++)
{
fprintf(fp,"%c",num_to_char(master[x]));
if((x-masterstart[R])%80 == 79) fprintf(fp,"\n");
}
if((x-masterstart[R])%80 > 0) fprintf(fp,"\n");
if(VERBOSE)
{
printf("R=%d: N is %d\n",R,N);
fprintf(stderr,"R=%d: N is %d\n",R,N);
printf("AFTER EXTENDING FAMILY %d IS:\n",R);
printf("%d letters total:\n",masterend[R]-masterstart[R]+1);
for(x=masterstart[R]; x<=masterend[R]; x++)
{
printf("%c",num_to_char(master[x]));
if((x-masterstart[R])%80 == 79) printf("\n");
}
if((x-masterstart[R])%80 > 0) printf("\n");
fprintf(stderr,"AFTER EXTENDING FAMILY %d IS:\n",R);
fprintf(stderr,"%d letters total:\n",masterend[R]-masterstart[R]+1);
for(x=masterstart[R]; x<=masterend[R]; x++)
{
fprintf(stderr,"%c",num_to_char(master[x]));
if((x-masterstart[R])%80 == 79) fprintf(stderr,"\n");
}
if((x-masterstart[R])%80 > 0) fprintf(stderr,"\n");
}
finish = time(0);
duration = difftime(finish,start);
if(VERBOSE) printf("Time1 to this point is %.1f sec = %.1f min = %.1f hr\n",duration, duration/60.0, duration/3600.0);
if(VERBOSE) fprintf(stderr,"Time1 to this point is %.1f sec = %.1f min = %.1f hr\n",duration, duration/60.0, duration/3600.0);
R++;
if(R == MAXR) break;
mask_headptr(headptr); /* removed[x]=1 means l-mer x was removed */
finish = time(0);
duration = difftime(finish,start);
if(VERBOSE) printf("Time2 to this point is %.1f sec = %.1f min = %.1f hr\n\n",duration, duration/60.0, duration/3600.0);
if(VERBOSE) fprintf(stderr,"Time2 to this point is %.1f sec = %.1f min = %.1f hr\n\n",duration, duration/60.0, duration/3600.0);
}
else
{
R++;
if(R == MAXR) break;
mask_headptr(headptr);
R--;
}
}
finish = time(0);
duration = difftime(finish,start);
if(VERBOSE) printf("Program duration is %.1f sec = %.1f min = %.1f hr\n",duration, duration/60.0, duration/3600.0);
fprintf(stderr,"Program duration is %.1f sec = %.1f min = %.1f hr\n",duration, duration/60.0, duration/3600.0);
return 0;
}
/* ************************************************************** */
void build_headptr(struct llist **headptr)
{
FILE *fp;
char string[1000];
int thisfreq, thisocc, x, h, n;
struct llist *tmp;
if( (fp = fopen(LMER_TABLE_FILE, "r")) == NULL)
{
fprintf(stderr,"Could not open input file %s\n", LMER_TABLE_FILE); exit(1);
}
/* set each head pointer *headptr to NULL */
for(h=0; h<HASH_SIZE; h++)
headptr[h] = NULL;
int items_read = 0;
n = 0;
while(1)
{
items_read = fscanf(fp, "%s", string);
if (items_read == EOF) {
if (feof(fp)) {
// Normal EOF reached; exit the loop gracefully
break;
} else {
// An error occurred while reading
fprintf(stderr, "Error reading kmer string from frequency file.\n");
exit(1);
}
} else if (items_read != 1) {
fprintf(stderr, "Error reading kmer string from frequency file.\n");
exit(1);
}
// Read the frequency
items_read = fscanf(fp, "%d", &thisfreq);
if (items_read == EOF) {
fprintf(stderr, "Unexpected end of file when reading frequency.\n");
exit(1);
} else if (items_read != 1) {
fprintf(stderr, "Error reading frequency from frequency file.\n");
exit(1);
}
// Read the occurrence
items_read = fscanf(fp, "%d", &thisocc);
if (items_read == EOF) {
fprintf(stderr, "Unexpected end of file when reading occurrence.\n");
exit(1);
} else if (items_read != 1) {
fprintf(stderr, "Error reading occurrence from frequency file.\n");
exit(1);
}
if ( strlen(string) != l ) {
fprintf(stderr, "Error: lmer length mismatch. Expected %d, got %ld.\n", l, strlen(string));
exit(1);
}
for(x=0; x<l; x++) string[x] = char_to_num(string[x]); /* must translate */
h = hash_function(string);
if(h<0) continue;
tmp = headptr[h];
while(tmp != NULL)
{
if(lmermatcheither(sequence+(tmp->lastocc),string) == 1) /* forward or rc match */
{
/* already in there. Means we have reached end of file: all done */
break;
}
tmp = tmp->next;
}
/* add new guys */
if(tmp != NULL) break; /* all done */
if(compute_entropy(sequence+thisocc) > MAXENTROPY) continue; /* skip */
if((tmp = (struct llist *) malloc(sizeof(*tmp))) == NULL)
{
fprintf(stderr,"Out of memory\n"); exit(1);
}
n++;
tmp->freq = thisfreq;
tmp->lastocc = thisocc;
tmp->next = headptr[h]; /* either NULL, or some other l-mer with hash h */
tmp->pos = NULL;
headptr[h] = tmp;
}
fclose(fp);
trim_headptr(headptr);
build_all_pos(headptr);
}
void trim_headptr(struct llist **headptr)
{
int h;
struct llist *tmp, *prevtmp, *nexttmp;
/* remove l-mers with freq < MINTHRESH */
for(h=0; h<HASH_SIZE; h++)
{
prevtmp = NULL;
tmp = headptr[h];
while(tmp != NULL)
{
if(tmp->freq >= MINTHRESH)
{ /* don't remove tmp */
// RMH: Let build_all_pos rebuild this ( based on seq boundaries )
tmp->freq = 0;
prevtmp = tmp;
tmp = tmp->next;
continue;
}
/* remove tmp */
nexttmp = tmp->next;
free(tmp);
tmp = nexttmp;
if(prevtmp == NULL) /* first guy in linked list */
headptr[h] = tmp;
else
prevtmp->next = tmp;
}
}
}
void build_all_pos(struct llist **headptr)
{
int x, h, pos1, pos2;
// RMH: Added for rev/fwd strand mods
struct posllist *postmp2;
struct llist *tmp;
struct posllist *postmp, *prevpostmp, *nextpostmp;
int currBoundary = 0;
if(VERBOSE) fprintf(stderr,"Starting build_all_pos 1\n");
for(x=l-1; x<length-l+1; x++)
{
// RMH: Make sure we are not on a sequence boundary.
// NOTE: I have decided to adjust the frequency
// also at this stage. This should take care
// of build_lmer_table including elements
// which cross sequence boundaries. I don't
// like adjusting it here but until build_lmer_table
// is revamped or we switch to elmer....
//
if ( boundaries[currBoundary] > 0 )
{
if ( x == boundaries[currBoundary] + PADLENGTH )
{
currBoundary++;
}
if ( x+l > boundaries[currBoundary] + PADLENGTH )
{
if(VERBOSE) printf("Skipping lmer @ %d due to sequence boundary\n", (x+l) );
continue;
}
}
/* look for this l-mer in headptr */
// RMH: This may be a good place for an optimisation.
// We could use the bit table trick to disqualify
// lmers that can't be in the hash table. Thus
// reducing the hash table lookup cost.
h = hash_function(sequence+x);
if(h<0) continue;
tmp = headptr[h];
while(tmp != NULL)
{
// RMH: Changed this to "either" now that we are not loading
// into memory the reverse complemented sequence.
if( ((SEEDMISMATCHES==0) && (lmermatcheither(sequence+(tmp->lastocc),sequence+x))) /* seq incl rc */ ||
((SEEDMISMATCHES>0) && (mismatches(sequence+(tmp->lastocc),sequence+x)<=SEEDMISMATCHES)))
{
/* a hit. Add position x to tmp->pos */
if((postmp = (struct posllist *) malloc(sizeof(*postmp))) == NULL)
{
fprintf(stderr,"Out of memory\n"); exit(1);
}
postmp->this = x;
postmp->next = tmp->pos;
tmp->pos = postmp;
tmp->freq++;
}
tmp = tmp->next;
}
}
if(VERBOSE) fprintf(stderr,"Starting build_all_pos 2\n");
/* extra code to remove position pairs within TANDEMDIST */
// RMH: NOTE - Tandem repeat removal creates assymetry in the
// algorithm. When two lmers are within TANDEMDIST
// apart the first one is removed and the last one
// kept. Obviously this is dependent on the strand
// you feed the program. Setting tandemdist to 0
// will restore symmetry for testing purposes.
for(h=0; h<HASH_SIZE; h++)
{
tmp = headptr[h];
while(tmp != NULL)
{
/* mark within-TANDEMDIST guys as negative */
postmp = tmp->pos;
while((postmp != NULL) && (postmp->next != NULL))
{
pos1 = postmp->this;
// RMH: Fwd/Rev strand mods
// Tandem distance needs to be measured from the last
// occurance of a same-stranded lmer.
postmp2 = postmp;
while ( ( postmp2 = postmp2->next ) != NULL )
{
pos2 = postmp2->this;
if ( pos1-pos2 >= TANDEMDIST )
break;
if ( lmermatch(sequence+pos1,sequence+pos2) )
{
postmp->this = -pos1;
break;
}
}
postmp = postmp->next;
}
/* remove guys marked as negative */
postmp = tmp->pos;
prevpostmp = NULL;
while(postmp != NULL)
{
if(postmp->this >= 0)
{ /* don't remove postmp */
prevpostmp = postmp;
postmp = postmp->next;
continue;
}
/* remove postmp */
nextpostmp = postmp->next;
// RMH: Reduce frequency as we remove them?
// TODO: Consider if this is what we want.
tmp->freq--;
removed[-postmp->this] = 1;
//
free(postmp);
postmp = nextpostmp;
if(prevpostmp == NULL) /* first guy in linked list */
tmp->pos = postmp;
else
prevpostmp->next = postmp;
}
tmp = tmp->next;
}
}
return;
if(VERBOSE) fprintf(stderr,"Done with build_all_pos\n");
}
struct llist *find_besttmp(struct llist **headptr)
{
int h;
struct llist *tmp, *besttmp;
int bestfreq;
/* first, try to match prevbestfreq */
for(h=prevbesthash; h<HASH_SIZE; h++)
{
tmp = headptr[h];
while(tmp != NULL)
{
if(tmp->freq == prevbestfreq)
{
prevbesthash = h;
return tmp;
}
tmp = tmp->next;
}
}
/* otherwise, just find best */
besttmp = NULL;
bestfreq = 0;
for(h=0; h<HASH_SIZE; h++)
{
tmp = headptr[h];
while(tmp != NULL)
{
if(tmp->freq > bestfreq)
{
besttmp = tmp;
bestfreq = tmp->freq;
prevbesthash = h;
}
tmp = tmp->next;
}
}
prevbestfreq = bestfreq;
return besttmp;
}
void allocate_space()
{
int r, x, n;
/* char **masters; MAXR * (2*L+l) but allocate dynamically */
if((masters = (char **) malloc(MAXR*sizeof(*masters))) == NULL)
{ fprintf(stderr,"Out of memory\n"); exit(1); }
for(r=0; r<MAXR; r++) masters_allocated[r] = 0;
if((distmat = (int **) malloc((l+1)*sizeof(*distmat))) == NULL)
{ fprintf(stderr,"Out of memory\n"); exit(1); }
for(x=0; x<=l; x++)
{
if((distmat[x] = (int *) malloc((l+1)*sizeof(*distmat[x]))) == NULL)
{ fprintf(stderr,"Out of memory\n"); exit(1); }
}
/* int ***score; 2 * MAXN * (2*MAXOFFSET+1) */
if((score = (int ***) malloc(2*sizeof(*score))) == NULL)
{ fprintf(stderr,"Out of memory\n"); exit(1); }
for(x=0; x<2; x++)
{
if((score[x] = (int **) malloc(MAXN*sizeof(*score[x]))) == NULL)
{ fprintf(stderr,"Out of memory\n"); exit(1); }
for(n=0; n<MAXN; n++)
{
if((score[x][n] = (int *) malloc((2*MAXOFFSET+1)*sizeof(*score[x][n]))) == NULL)
{ fprintf(stderr,"Out of memory\n"); exit(1); }
}
}
/* int **score_of_besty; MAXN * (2*MAXOFFSET+1) */
if((score_of_besty = (int **) malloc(MAXN*sizeof(*score_of_besty))) == NULL)
{ fprintf(stderr,"Out of memory\n"); exit(1); }
for(n=0; n<MAXN; n++)
{
if((score_of_besty[n] = (int *) malloc((2*MAXOFFSET+1)*sizeof(*score_of_besty[n]))) == NULL)
{ fprintf(stderr,"Out of memory\n"); exit(1); }
}
/* int **maskscore; 2 * (2*MAXOFFSET+1) */
if((maskscore = (int **) malloc(2*sizeof(*maskscore))) == NULL)
{ fprintf(stderr,"Out of memory\n"); exit(1); }
for(x=0; x<2; x++)
{
if((maskscore[x] = (int *) malloc((2*MAXOFFSET+1)*sizeof(*maskscore[x]))) == NULL)
{ fprintf(stderr,"Out of memory\n"); exit(1); }
}
}
void print_parameters()
{
printf("Parameters:\n");
printf("SEQUENCE_FILE %s\n",SEQUENCE_FILE);
printf("LMER_TABLE_FILE %s\n",LMER_TABLE_FILE);
printf("MAXLENGTH %d\n",MAXLENGTH);
printf("PADLENGTH %d\n",PADLENGTH);
printf("l %d\n",l);
printf("SEEDMISMATCHES %d\n",SEEDMISMATCHES);
printf("HASH_SIZE %d\n",HASH_SIZE);
printf("L %d\n",L);
printf("MAXOFFSET %d\n",MAXOFFSET);
printf("MAXN %d\n",MAXN);
printf("MAXR %d\n",MAXR);
printf("MATCH %d MISMATCH %d GAP %d\n",MATCH,MISMATCH,GAP);
printf("MINTHRESH %d\n",MINTHRESH);
printf("CAPPENALTY %d MINIMPROVEMENT %d\n",CAPPENALTY,MINIMPROVEMENT);
printf("WHEN_TO_STOP %d\n",WHEN_TO_STOP);
printf("REMOVE_DEGENERATES %d\n",REMOVE_DEGENERATES);
printf("TANDEMDIST %d\n",TANDEMDIST);
printf("EXTRAMASK %d\n",EXTRAMASK);
printf("MAXENTROPY %f\n",MAXENTROPY);
}
int build_sequence(char *sequence, char *filename)
{
int i, j, seq;
char c;
FILE *fp;
int boundariesSize = 100;
int id_count = 0;
char id_buffer[1024];
// RMH: Initialize the boundaries array
boundaries = (int *)malloc( boundariesSize * sizeof(int) );
if( NULL == boundaries ) {
fprintf(stderr, "Could not allocated space for the boundaries array\n");
exit(1);
}
if( (fp = fopen(filename, "r")) == NULL)
{
fprintf(stderr,"Could not open input file %s\n", filename); exit(1);
}
for(i=0; i<PADLENGTH; i++) sequence[i] = 99;
i = 0;
seq = 0;
while( !feof(fp) && (i<MAXLENGTH) )
{ /* process one line of file */
c = getc(fp);
if(c == EOF) continue;
if(c == '\n') continue;
if(c == '>')
{
// RMH: New in 1.0.7 - read in and save the sequence identifiers for use in the ranges output
j = 0;
while ((c = getc(fp)) != '\n' && c != EOF) {
if ( c == ' ' || c == '\t' ) {
while ((c = getc(fp)) != '\n' && c != EOF) {
;
}
break;
}
if (j < sizeof(id_buffer) - 1) {
id_buffer[j++] = c;
}
}
id_buffer[j] = '\0';
id_count++;
char **temp = realloc(sequence_ids, (id_count + 1) * sizeof(char *));
if (temp == NULL) {
fprintf(stderr, "Could not allocate more space for the sequence_ids array\n");
exit(1);
}
sequence_ids = temp;
sequence_ids[id_count] = NULL;
sequence_ids[id_count-1] = malloc(strlen(id_buffer) + 1);
if ( ! sequence_ids[id_count-1] ) {
fprintf(stderr, "Could not allocate more space for the ids array\n");
exit(1);
}
strcpy(sequence_ids[id_count-1], id_buffer);
// RMH: Store boundary info
if ( seq > 0 )
{
if ( seq > boundariesSize )
{
boundariesSize += 100;
boundaries = realloc( boundaries, boundariesSize * sizeof(int) );
if( NULL == boundaries ) {
fprintf(stderr, "Could not allocated more space for the "
"boundaries array\n");
exit(1);
}
}
//printf("Adding sequence boundary[%d] = %d, %d\n",
// ( seq-1 ), i, i+PADLENGTH );
boundaries[seq-1] = i;
}
seq++;
}
else
{
if(c > 64)
{
sequence[i+PADLENGTH] = char_to_num(c);
i++;
}
for(j=0; ((c = getc(fp)) != '\n') && !feof(fp) && (i<MAXLENGTH); j++)
{
if(c > 64)
{
sequence[i+PADLENGTH] = char_to_num(c);
i++;
}
}
}
}
if ( seq == 0 )
seq = 1;
if ( seq+1 >= boundariesSize )
{
boundariesSize += 100;
boundaries = realloc( boundaries, boundariesSize * sizeof(int) );
if( NULL == boundaries ) {
fprintf(stderr, "Could not allocated more space for the "
"boundaries array\n");
exit(1);
}
}
boundaries[seq-1] = i + 1;
//printf("Adding sequence boundary[%d] = %d, %d\n", seq-1, (i + 1), (i+1)+PADLENGTH );
boundaries[seq] = 0;
fclose(fp);
return (i+PADLENGTH); /* length of genome */
}
void add_rc(char *sequence)
{
int x;
for(x=0; x<PADLENGTH; x++)
sequence[length+x] = 99;
for(x=0; x<length; x++)
{
if(sequence[length-1-x] == 99)
sequence[length+PADLENGTH+x] = 99;
else
sequence[length+PADLENGTH+x] = 3 - sequence[length-1-x];
}
length = 2*length + PADLENGTH;
}
void build_pos(struct llist *besttmp)
{
struct posllist *postmp;
int x = 0;