File: main.cpp

package info (click to toggle)
staden 2.0.0%2Bb11-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster
  • size: 21,556 kB
  • sloc: ansic: 240,603; tcl: 65,360; cpp: 12,854; makefile: 11,201; sh: 2,952; fortran: 2,033; perl: 63; awk: 46
file content (658 lines) | stat: -rw-r--r-- 20,462 bytes parent folder | download | duplicates (5)
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
/*
 * Copyright (c) Medical Research Council 2002. All rights reserved.
 *
 * Permission to use, copy, modify and distribute this software and its
 * documentation for any purpose is hereby granted without fee, provided that
 * this copyright and notice appears in all copies.
 *
 * This file was written as part of the Staden Package at the MRC Laboratory
 * of Molecular Biology, Hills Road, Cambridge, CB2 2QH, United Kingdom.
 *
 * MRC disclaims all warranties with regard to this software.
 *
 */

#include <staden_config.h>

#include <cassert>
#include <new>              // For bad_alloc
#include <cstdio>           // For fprintf(), fflush(), etc
#include <cctype>           // For isspace(), toupper()
#include <cstring>          // For strcpy(), strcat(), etc
#include <cstdlib>          // For atof()
#include <staden.h>         // For io_lib and licence stuff
#include <mutlib.h>         // For mutation library
#include <pathutil.h>       // For MakeFullPath()
#include <stringlist.hpp>   // For StringList
#include <string.h>	    // Needed for Solaris C++ compiler?



//-------------
// Module Data
//-------------

const int BUFSIZE = 512;




//------------------
// Helper Functions
//------------------

void PrintBanner()
{
    std::fprintf( stdout, "Mutscan v1.00, by Mark Jordan.\n"
                  "MRC Laboratory of Molecular Biology, Copyright (C) 2002. All Rights Reserved.\n" );
    std::fflush( stdout );
}



void PrintUsage( mutscan_t& ms )
{
    std::fprintf( stdout, "Usage  : mutscan [options] <experiment-files>\n"
    "Options:\n"
    "[-a<mutation-count>]     = Alignment failure report threshold   (default=%0.0f)\n"
    "[-c]                     = Complement reverse strand tags       (default=off)\n"
    "[-f<file-of-filenames>]  = File of experiment filenames\n"
    "[-h<heterzygote-SNR>]    = Heterzygote SNR threshold in dB      (default=%0.2f)\n"
    "[-l<peakdrop-threshold>] = Lower peak drop threshold percentage (default=%0.2f)\n"
    "[-n<noise-threshold]     = Noise level threshold percentage     (default=%0.2f)\n"
    "[-q]                     = Quiet mode                           (default=off)\n"
    "[-u<peakdrop-threshold>] = Upper peak drop threshold percentage (default=%0.2f)\n"
    "[-w<search-window-size>] = Peak search window size in bases     (default=%0.2f)\n"
    "[-p]                     = Proximity filter threshold...        (default=7)\n"
    "[-z]                     = Enter debugging loop and wait...     (default=off)\n",
     ms.Parameter[MUTSCAN_PARAMETER_ALIGNFAIL_THRESHOLD],
     ms.Parameter[MUTSCAN_PARAMETER_HETSNR_THRESHOLD],
     ms.Parameter[MUTSCAN_PARAMETER_PEAKDROP_LOWER],
     ms.Parameter[MUTSCAN_PARAMETER_NOISE_THRESHOLD],
     ms.Parameter[MUTSCAN_PARAMETER_PEAKDROP_UPPER],
     ms.Parameter[MUTSCAN_PARAMETER_SEARCH_WINDOW]
    );
    std::fflush( stdout );
}

// Filter clusters of tags too close to the end of MCOV
void filter_tags ( mutscan_t& ms, int nTags, int threshold ) {
    int *scores_a, *scores;
    int cov_start = 0, cov_end = 0;
    const int win_len = 5;

    // Get coverage range
    for( int i=0; i<nTags; i++ ) {
        mutlib_tag_t* pTag = MutScanGetTag( &ms, i );
        assert(pTag != NULL);

	if (std::strcmp(pTag->Type,"MCOV") == 0) {
	    cov_start = pTag->Position[0];
	    cov_end   = pTag->Position[1];
	    break;
	}
    }
    printf("Cov=%d..%d\n", cov_start, cov_end);


    /*
     * Allocate an array indexed from -win_len to cov_end+win_len.
     * Each tag gets a peak of width 2*win_len+1 centred on it and is
     * accumulated in this array.
     */
    scores_a = new int[win_len*2+cov_end+1];
    scores = &scores_a[win_len];
    memset(scores_a, 0, (win_len*2+cov_end) *sizeof(*scores_a));

    // Convolve tag peaks
    for (int i=0; i < nTags; i++) {
	mutlib_tag_t* pTag = MutScanGetTag( &ms, i );
	int pos = pTag->Position[0];
	if (pos < 0) pos = 0;
	if (pos > cov_end) pos = cov_end;

	scores[pos] += win_len+1;
	for (int j=1; j<=win_len; j++) {
	    scores[pos+j] += win_len+1 - j;
	    scores[pos-j] += win_len+1 - j;
	}
    }

    // Filter tags
    for (int i=0; i < nTags; i++) {
	mutlib_tag_t* pTag = MutScanGetTag( &ms, i );
	int pos = pTag->Position[0];

	if (std::strcmp(pTag->Type,"MCOV") == 0)
	    continue;

	if (scores[pos] >= threshold) {
	    pTag->Type[3] = '?';
	}
    }
    
    delete [] scores_a;

#if 0
    int last = 0;
    int cost = 0, highest_cost = 0;
    int range_start = 0, range_end = 0;
    for ( int i=0; i<nTags; i++) {
        mutlib_tag_t* pTag = MutScanGetTag( &ms, i );

	cost += 4;
	if (i != range_start)
	    cost -= pTag->Position[0] - last;
	printf("Tag %d at %d, cost = %d\n", i, pTag->Position[0], cost);
	if (highest_cost <= cost) {
	    highest_cost = cost;
	    range_end = i;
	}
	
	if ((cost < highest_cost-10 || cost < 0) && highest_cost > 10) {
	    printf("    Tag %d..%d highest_cost=%d\n",
		   range_start, range_end, highest_cost);
	    i = range_end;
	    range_start = i+1;
	    highest_cost = cost = 0;
	}
	last = pTag->Position[0];
    }
    if (highest_cost > 10) {
	printf("    Tag %d..%d highest_cost=%d\n",
	       range_start, range_end, highest_cost);
    }
#endif

#if 0
    // Adjust left end
    int cost = -5, last = cov_start;
    puts("==Left==");
    for( int i=0; i<nTags; i++ ) {
        mutlib_tag_t* pTag = MutScanGetTag( &ms, i );
        assert(pTag != NULL);
	if (std::strcmp(pTag->Type,"MCOV") == 0)
	    continue;

	cost += pTag->Position[0] - last;
	printf("Tag at %d cost=%d\n", pTag->Position[0], cost);
	if (cost <= 0) {
	    printf("Reject tag at %d\n", pTag->Position[0]);
	    *pTag->Type = 0;
	    cost -= 1;
	}
	last = pTag->Position[0];
    }

    // Adjust right end
    cost = -5;
    last = cov_end;
    puts("==Right==");
    for( int i=nTags-1; i>=0; i-- ) {
        mutlib_tag_t* pTag = MutScanGetTag( &ms, i );
        assert(pTag);
	if (std::strcmp(pTag->Type,"MCOV") == 0)
	    continue;

	cost += last - pTag->Position[0];
	printf("Tag at %d cost=%d\n", pTag->Position[0], cost);
	if (cost <= 0) {
	    printf("Reject tag at %d\n", pTag->Position[0]);
	    *pTag->Type = 0;
	    cost -= 2;
	}
	last = pTag->Position[0];
    }
#endif
}

//-----------
// Tracediff
//-----------

int main( int argc, char* argv[] )
{
    int             n;
    char*           p;
    mutscan_t       ms;
    mutlib_strand_t nStrand;
    StringList      FileList;
    int             nInputClipL;
    int             nInputClipR;
    char            pBuffer[BUFSIZE];
    char            pFileOfFiles[BUFSIZE]     = { 0 };
    Exp_info*       pExpFile                  = 0;
    Read*           pInputTrace               = 0;
    int             nRefClipL[2]              = { -1, -1 };
    int             nRefClipR[2]              = { -1, -1 };
    Read*           pRefTrace[2]              = { 0,   0 };
    char*           pRefSequence[2]           = { 0,   0 };
    bool            bDebug                    = false;
    bool            bQuiet                    = false;
    bool            bComplementTags           = false;
    double          nNoiseThreshold           = -1.0;
    double          nAlignFailThreshold       = -1.0;
    double          nSearchWindowSize         = -1.0;
    double          nPeakDropThresholdUpper   = -1.0;
    double          nPeakDropThresholdLower   = -1.0;
    double          nHeterozygoteSNRThreshold = -1.0;
    int 	    proximityThreshold = 7;
    MutScanInit( &ms );



    try
    {
        // Request traces to be used in preference to experiment files
        read_experiment_redirect(0);

        // Quick check of input
        if( argc < 2 )
        {
            PrintBanner();
            PrintUsage( ms );
            return -1;
        }



        // Parse the command line options
        for( n=1; n<argc; n++ )
        {
            // All options done?
            if( argv[n][0] != '-' )
                break;


            // Copy switch contents to buffer
            char c;
            int  k = 2;
            while( c=argv[n][k] )
            {
                pBuffer[k-2] = c;
                k++;
            }
            pBuffer[k-2] = 0;



            // Process each option
            switch( argv[n][1] )
            {
                case 'a':
                    // Alignment failure threshold
                    nAlignFailThreshold = std::atof( pBuffer );
                    break;


                case 'c':
                    // Complement reverse strand base tags
                    bComplementTags = true;
                    break;


                case 'f':
                    // File of filenames
                    std::strcpy( pFileOfFiles, pBuffer );
                    break;


                case 'h':
                    // Heterozygote SNR ratio threshold
                    nHeterozygoteSNRThreshold = std::atof( pBuffer );
                    break;


                case 'l':
                    // Lower peakdrop threshold
                    nPeakDropThresholdLower = std::atof( pBuffer );
                    break;


                case 'n':
                    // Noise window
                    nNoiseThreshold = std::atof( pBuffer );
                    break;


                case 'q':
                    // Quiet mode on
                    bQuiet = true;
                    break;


                case 'u':
                    // Upper peakdrop threshold
                    nPeakDropThresholdUpper = std::atof( pBuffer );
                    break;


                case 'w':
                    // Search window size
                    nSearchWindowSize = std::atof( pBuffer );
                    break;


                case 't':
                    // proximity threshold
                    proximityThreshold = std::atoi( pBuffer );
                    break;


                case 'z':
                    // Debug mode
                    bDebug = true;
                    break;


                default:
                    // Unknown switch
                    std::fprintf( stderr, "Unknown option %s, ignoring.", argv[n] );
                    std::fflush( stderr );
                    break;
            }
        }



        // Show banner
        if( !bQuiet )
            PrintBanner();



        // Loop for MSW debugger attachment purposes
        while( bDebug );



        // Read contents of file-of-filenames if supplied
        if( pFileOfFiles[0] )
        {
            std::FILE* pFOFN = std::fopen( pFileOfFiles, "rt" );
            if( pFOFN )
            {
                while( std::fgets(pBuffer,BUFSIZE,pFOFN) )
                {
                    p = std::strrchr(pBuffer,'\n');
                    if(p) *p = 0;
                    p = std::strrchr(pBuffer,'\r');
                    if(p) *p = 0;
                    FileList.Append( pBuffer );
                }
                std::fclose( pFOFN );
            }
            else
            {
                std::fprintf( stderr, "Unable to open file of filenames %s, skipping.\n", pFileOfFiles );
                std::fflush( stderr );
            }
        }



        // Add any experiment files on the command line
        for( n=n; n<argc; n++ )
            FileList.Append( argv[n] );
        if( FileList.Length() < 1 )
        {
            PrintUsage( ms );
            return -1;
        }



        // Set parameters if specified, otherwise accept defaults
        if( nAlignFailThreshold > 0.0 )
            MutScanSetParameter( &ms, MUTSCAN_PARAMETER_ALIGNFAIL_THRESHOLD, nAlignFailThreshold );
        if( nHeterozygoteSNRThreshold > 0.0 )
            MutScanSetParameter( &ms, MUTSCAN_PARAMETER_HETSNR_THRESHOLD, nHeterozygoteSNRThreshold );
        if( nNoiseThreshold > 0.0 )
            MutScanSetParameter( &ms, MUTSCAN_PARAMETER_NOISE_THRESHOLD, nNoiseThreshold );
        if( nSearchWindowSize > 0.0 )
            MutScanSetParameter( &ms, MUTSCAN_PARAMETER_SEARCH_WINDOW, nSearchWindowSize );
        if( nPeakDropThresholdLower > 0.0 )
            MutScanSetParameter( &ms, MUTSCAN_PARAMETER_PEAKDROP_LOWER, nPeakDropThresholdLower );
        if( nPeakDropThresholdUpper > 0.0 )
            MutScanSetParameter( &ms, MUTSCAN_PARAMETER_PEAKDROP_UPPER, nPeakDropThresholdUpper );
        if( bComplementTags == true )
            MutScanSetParameter( &ms, MUTSCAN_PARAMETER_COMPLEMENT_TAGS, 1.0 );



        // File processing loop
        for( n=0; n<FileList.Length(); n++ )
        {
            // Cleanup from previous iteration
            if( pExpFile )
            {
                exp_destroy_info(pExpFile);
                pExpFile = 0;
            }
            if( pInputTrace )
            {
                read_deallocate(pInputTrace);
                pInputTrace = 0;
            }
            p = (n==0) ? FileList.First() : FileList.Next();



            // Tell user what we're doing
            if( !bQuiet )
            {
                std::fprintf( stdout, "Scanning: %s\n", p );
                std::fflush( stdout );
            }



            // Open experiment file
            pExpFile = exp_read_info( p );
            if( !pExpFile )
            {
                std::fprintf( stderr, "Unable to open experiment file %s, skipping.\n", p );
                std::fflush( stderr );
                continue;
            }



            // Extract PR record, gives us strand direction
            int PR = 0;
            if( exp_get_int(pExpFile,EFLT_PR,&PR) )
            {
                std::fprintf( stderr, "Unable to read PR record from experiment file %s, assuming forward strand.\n", p );
                std::fflush( stderr );
            }
            nStrand = ((PR==0) || (PR==1) || (PR==3)) ? MUTLIB_STRAND_FORWARD : MUTLIB_STRAND_REVERSE;



            // If we don't have a reference trace/seq for this strand
            if( !pRefTrace[nStrand] )
            {
                // Extract reference trace name WT
                if( exp_get_str(pExpFile,EFLT_WT,pBuffer,BUFSIZE) )
                {
                    std::fprintf( stderr, "Unable to read WT record from experiment file %s, skipping.\n", p );
                    std::fflush( stderr );
                    continue;
                }


                // Open reference trace file
                MakeFullPath( p, pBuffer );
                pRefTrace[nStrand] = read_reading( pBuffer, TT_ANY );
                if( !pRefTrace[nStrand] )
                {
                    std::fprintf( stderr, "Unable to open reference trace file %s, skipping.\n", pBuffer );
                    std::fflush( stderr );
                    continue;
                }



                // Extract reference clip points WL/WR
                exp_get_int( pExpFile, EFLT_WL, &nRefClipL[nStrand] );
                exp_get_int( pExpFile, EFLT_WR, &nRefClipR[nStrand] );



                // If default clipping values used for reference
                if( (nRefClipL[nStrand]<0) || (nRefClipR[nStrand]<0) )
                {
                    // Construct the reference experiment file's name and attempt to open it
                    ReplaceExtension( pBuffer, ".exp" );
                    Exp_info* pRefExpFile = exp_read_info( pBuffer );
                    if( pRefExpFile )
                    {
                        // Extract the QL/QR records if they exist
                        if( nRefClipL[nStrand] < 0 )
                            exp_get_int( pRefExpFile, EFLT_QL, &nRefClipL[nStrand] );
                        if( nRefClipR[nStrand] < 0 )
                            exp_get_int( pRefExpFile, EFLT_QR, &nRefClipR[nStrand] );
                        exp_destroy_info(pRefExpFile);
                    }
                    // Otherwise use the entire reference trace
                }


                // Initialise the algorithm
                MutScanSetReference( &ms, nStrand, pRefTrace[nStrand], nRefClipL[nStrand], nRefClipR[nStrand] );
            }



            // Extract LN record, gives us input trace file name
            if( exp_get_str(pExpFile,EFLT_LN,pBuffer,BUFSIZE) )
            {
                std::fprintf( stderr, "Unable to read LN record from experiment file %s, skipping.\n", p );
                std::fflush( stderr );
                continue;
            }


            // Open input trace
            MakeFullPath( p, pBuffer );
            pInputTrace = read_reading( pBuffer, TT_ANY );
            if( !pInputTrace )
            {
                std::fprintf( stderr, "Unable to open input trace file %s, skipping.\n", pBuffer );
                std::fflush( stderr );
                continue;
            }
	    if ( !pInputTrace->NPoints ) {
		std::fprintf(stderr, "No trace data found in trace file %s, skipping.\n", pBuffer);
		continue;
	    }



            // Extract input clip points QL/QR
            nInputClipL = -1;
            nInputClipR = -1;
            exp_get_int( pExpFile, EFLT_QL, &nInputClipL );
            exp_get_int( pExpFile, EFLT_QR, &nInputClipR );



            // Initialise the algorithm
            MutScanSetInput( &ms, nStrand, pInputTrace, nInputClipL, nInputClipR );



            // Execute the algorithm
            MutScanExecute( &ms );
            if( MutScanGetResultCode(&ms) )
            {
                // Error
                std::fprintf( stderr, "%s", MutScanGetResultString(&ms) );
                std::fflush( stderr );
                continue;
            }
            int nTags = MutScanGetTagCount( &ms );



            // Find the rightmost tag position for this trace
            int nRightmostTag = -1;
            for( int i=0; i<nTags; i++ )
            {
                mutlib_tag_t* pTag = MutScanGetTag( &ms, i );
                if( pTag->Position[0] > nRightmostTag )
                    nRightmostTag = pTag->Position[0];
            }



            // If mutation tag is beyond the right clip point (as in the case of
            // insertions/deletions), we adjust QR so that it's visible in gap4.
            if( (nTags>0) && (nInputClipR<=nRightmostTag) )
            {
                std::sprintf( pBuffer, "%d", nRightmostTag+1 );
                exp_put_str( pExpFile, EFLT_QR, pBuffer, std::strlen(pBuffer) );
            }

	    // Filter clusters of tags too close to the end of MCOV
	    filter_tags( ms, nTags, proximityThreshold );

            // Output results
            for( int i=0; i<nTags; i++ )
            {
                // Write mutation tags to experiment file & stdout
                mutlib_tag_t* pTag = MutScanGetTag( &ms, i );
                assert(pTag != NULL);

		if (!*pTag->Type)
		  continue;

                bool bCoverageTag = std::strcmp(pTag->Type,"MCOV") == 0;
                char sc = (pTag->Strand==MUTLIB_STRAND_FORWARD) ? '+' : '-';
                if( bCoverageTag )
                {
                    std::sprintf( pBuffer, "%s %c %d..%d", pTag->Type, sc, pTag->Position[0], pTag->Position[1] );
                    if( !bQuiet )
                    {
                        std::fprintf( stdout, "%s\n", pBuffer );
                        std::fflush( stdout );
                    }
                }
                else
                {
                    std::sprintf( pBuffer, "%s %c %d..%d\n%s", pTag->Type, sc, pTag->Position[0], pTag->Position[1], pTag->Comment );
                    if( !bQuiet )
                    {
                        std::fprintf( stdout, "%s %5d %s\n", pTag->Type, pTag->Position[0], pTag->Comment );
                        std::fflush( stdout );
                    }
                }
                exp_put_str(pExpFile, EFLT_TG, pBuffer, std::strlen(pBuffer) );
            }
        }
    }
    catch( std::bad_alloc& )
    {
        // Out of memory
        std::fprintf( stderr, "%s", "Not enough memory to complete the operation.\n" );
        std::fflush( stderr );
    }
    catch(...)
    {
        // Print error message
        std::fprintf( stderr, "%s", "An unexpected fatal exception has occurred, please "
                              "report the details to staden-package@mrc-lmb.cam.ac.uk.\n" );
        std::fflush( stderr );
    }




    // Cleanup & exit
    if(pExpFile)     exp_destroy_info(pExpFile);
    if(pInputTrace)  read_deallocate(pInputTrace);
    if(pRefTrace[0]) read_deallocate(pRefTrace[0]);
    if(pRefTrace[1]) read_deallocate(pRefTrace[1]);
    MutScanDestroy( &ms );
    return 0;
}