File: tracediff.cpp

package info (click to toggle)
staden 2.0.0%2Bb11-5
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 21,568 kB
  • sloc: ansic: 240,605; tcl: 65,360; cpp: 12,854; makefile: 11,201; sh: 2,952; fortran: 2,033; perl: 63; awk: 46
file content (340 lines) | stat: -rw-r--r-- 10,578 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
/*
 * 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 <cassert>
#include <cstring>                    // For strcpy(), memset()
#include <cstdio>                     // For std::printf(), std::sprintf()
#include <new>                        // For std::bad_alloc
#include <algorithm>                  // For std::max()
#include <list.hpp>                   // For list template
#include <trace.hpp>                  // For Trace object
#include <muttag.hpp>                 // For MutTag object
#include <tagarray.hpp>               // For TagArray object
#include <tracealign.hpp>             // For TraceAlignValidateInput() prototype
#include <tracediff.hpp>              // For helpers
#include <tracediff_parameters.hpp>   // For TraceDiffParameter object



/* #define VERBOSE_DEBUG */



/**
   Initialises an empty tracediff_t structure.
*/
void TraceDiffInit( tracediff_t* td )
{
   assert(td != NULL);
   TraceDiffParameters Parameter;
   std::memset( td, 0, sizeof(tracediff_t) );
   td->ResultString    = new char[ 512 ];
   td->ResultString[0] = 0;
   for( int n=0; n<TRACEDIFF_PARAMETERS; n++ )
       td->Parameter[n] = Parameter[n].Default();
   TraceAlignInit( &td->Alignment );
   td->Initialised = 1;
}



/**
   Frees up all memory allocated by the trace difference algorithm
   in the tracediff_t structure.
*/
void TraceDiffDestroy( tracediff_t* td )
{
   assert(td != NULL);
   assert(td->Initialised);
   try
   {
      // Delete all data
      TraceAlignDestroy( &td->Alignment );
      TraceDiffDestroyResults( td );
      delete [] td->ResultString;
   }
   catch(...)
   {
      // Shouldn't happen, but we musn't throw exceptions outside dll boundary
      assert(0);
   }
}



/**
   Gets the value of the tracediff parameter 'p'.
*/
double TraceDiffGetParameter( tracediff_t* td, tracediff_parameter_t p )
{
   assert(td != NULL);
   assert(td->Initialised);
   assert(p<TRACEDIFF_PARAMETERS);
   return (p<TRACEDIFF_PARAMETERS) ? td->Parameter[p] : 0.0;
}



/**
   Sets the value of the tracediff parameter 'p'.
*/
void TraceDiffSetParameter( tracediff_t* td, tracediff_parameter_t p, double v )
{
   assert(td != NULL);
   assert(td->Initialised);
   assert(p<TRACEDIFF_PARAMETERS);
   if( p < TRACEDIFF_PARAMETERS )
       td->Parameter[p] = v;
}



/**
   Sets the specified reference trace. The clip points are in base units.
   The caller retains ownership of the Read structure.
*/
void TraceDiffSetReference( tracediff_t* td, Read* w, mutlib_strand_t d, int ql, int qr )
{
   assert(td != NULL);
   assert(td->Initialised);
   TraceAlignSetReference( &td->Alignment, d, w, ql, qr );
}



/**
   Sets the current input trace. The clip points are in base units.
   The caller retains ownership of the Read structure.
*/
void TraceDiffSetInput( tracediff_t* td, Read* i, mutlib_strand_t d, int ql, int qr )
{
   assert(td != NULL);
   assert(td->Initialised);
   TraceAlignSetInput( &td->Alignment, d, i, ql, qr );
}



/**
   Returns the result code generated by the Execute() function. This can be
   used to query the result later without having to save the value returned
   by Execute().
*/
mutlib_result_t TraceDiffGetResultCode( tracediff_t* td )
{
   assert(td != NULL);
   assert(td->Initialised);
   return td->ResultCode;
}



/**
   Returns a read-only user friendly error message corresponding to the
   last result code. It may contain more useful information such as a
   filename or the particular intput that was invalid. This can be displayed
   to the user if required.
*/
const char* TraceDiffGetResultString( tracediff_t* td )
{
   assert(td != NULL);
   assert(td->Initialised);
   return td->ResultString;
}



/**
   Returns the difference trace as a Read structure. Ownership of the Read
   structure is retained by the trace difference algorithm. If 'dl' or 'dr'
   is not null, the left and right clip points in base numbers are returned.
*/
Read* TraceDiffGetDifference( tracediff_t* td, int* dl, int* dr )
{
   assert(td != NULL);
   assert(td->Initialised);
   if( dl != 0 )
      *dl = td->DifferenceLeft;
   if( dr != 0 )
      *dr = td->DifferenceRight;
   return td->Difference;
}



/**
   Returns the number of tags generated by the mutation scanning algorithm
   which are available to be read.
*/
int TraceDiffGetTagCount( tracediff_t* td )
{
   assert(td != NULL);
   assert(td->Initialised);
   return td->TagCount;
}



/**
   Returns a pointer to the 'nth' tag in the list. If the tag item is empty,
   a null pointer is returned.
*/
mutlib_tag_t* TraceDiffGetTag( tracediff_t* td, int n )
{
   assert(td != NULL);
   assert(td->Initialised);
   assert(n<td->TagCount);
   if( n < td->TagCount )
   {
      assert(td->Tag != NULL);
      return &td->Tag[n];
   }
   return 0;
}



/**
   Executes the trace difference algorithm optionally followed by the
   mutation detection algorithm.
*/
mutlib_result_t TraceDiffExecute( tracediff_t* td, tracediff_algorithm_t a )
{
    enum { STATE_INITIALISE, STATE_VALIDATE_INPUT, STATE_TRACE_ALIGN,
           STATE_TRACE_DIFFERENCE, STATE_MUTATION_ANALYSIS, STATE_EXIT };
    int                 n;
    mutlib_strand_t     Strand = MUTLIB_STRAND_FORWARD;
    TraceDiffParameters Parameter;
    Trace               AlignedTrace[2];
    int                 AlignedTraceClipL[2];
    int                 AlignedTraceClipR[2];
    List<MutTag>        DiffTagList;
    Trace*              DiffTrace = 0;
    bool                Done      = false;
    int                 State     = STATE_INITIALISE;
    assert(td != NULL);
    try
    {
        while(!Done)
        {
            switch(State)
            {
                case STATE_INITIALISE:
                    // Destroy old results
                    TraceDiffDestroyResults( td );
                    Strand = td->Alignment.Input.Strand;
                    State  = STATE_VALIDATE_INPUT;
                    break;



                case STATE_VALIDATE_INPUT:
                    // Check input values
                    State = STATE_EXIT;
                    for( n=0; n<TRACEDIFF_PARAMETERS; n++ )
                        Parameter[n].Value( td->Parameter[n] );
                    if( TraceDiffValidateParameters(td,Parameter) != MUTLIB_RESULT_SUCCESS )
                        break;
                    if( TraceAlignValidateInput(&td->Alignment) != MUTLIB_RESULT_SUCCESS )
                    {
                        td->ResultCode = td->Alignment.ResultCode;
                        std::strcpy( td->ResultString, td->Alignment.ResultString );
                        break;
                    }
                    State = STATE_TRACE_ALIGN;
                    break;



                case STATE_TRACE_ALIGN:
                    // Align the reference and input traces
                    if( TraceAlignExecute(&td->Alignment) != MUTLIB_RESULT_SUCCESS )
                    {
                        td->ResultCode = TraceAlignGetResultCode( &td->Alignment );
                        std::strcpy( td->ResultString, TraceAlignGetResultString(&td->Alignment) );
                        State = STATE_EXIT;
                        break;
                    }
                    for( int n=0; n<2; n++ )
                        AlignedTrace[n].Wrap(TraceAlignGetAlignment(&td->Alignment,static_cast<mutlib_input_t>(n),&AlignedTraceClipL[n],&AlignedTraceClipR[n]),false);
                    State = STATE_TRACE_DIFFERENCE;
                    break;



                case STATE_TRACE_DIFFERENCE: {
                    // Scale & Subtract the two traces to obtain the difference trace
                    State = (a&TRACEDIFF_ALGORITHM_DEFAULT_DIFFERENCE_ONLY) ? STATE_EXIT : STATE_MUTATION_ANALYSIS;
                    if( Parameter[TRACEDIFF_PARAMETER_YSCALE].Value() > 0.0 )
                        AlignedTrace[MUTLIB_INPUT].ScaleTo( AlignedTrace[MUTLIB_INPUT_REFERENCE] );
                    DiffTrace = AlignedTrace[MUTLIB_INPUT].Subtract( AlignedTrace[MUTLIB_INPUT_REFERENCE] );
                    if( !DiffTrace )
                        throw std::bad_alloc();
                    DiffTrace->AutoDestroy( false );
                    td->Difference      = DiffTrace->Raw();
                    td->DifferenceLeft  = AlignedTraceClipL[MUTLIB_INPUT];
                    td->DifferenceRight = AlignedTraceClipR[MUTLIB_INPUT];
                    break; }



                case STATE_MUTATION_ANALYSIS:
                    // Analyse the difference trace for possible mutations
                    TraceDiffScanForMutations( *DiffTrace, Strand, DiffTrace->IntervalMode(),
                        AlignedTraceClipL[MUTLIB_INPUT], Parameter, DiffTagList );
                    if( DiffTagList.Count() > 0 )
                    {
                        // Construct output mutation tag list
                        TagArray OutTags;
                        bool bComplementBases = Parameter[TRACEDIFF_PARAMETER_COMPLEMENT_TAGS].Value()>0.0 ? true : false;
                        OutTags.Create( DiffTagList.Count() );
                        OutTags.ReadTags( DiffTagList, 1, bComplementBases );
                        OutTags.AutoDestroy( false );
                        td->Tag        = OutTags.Raw();
                        td->TagCount   = DiffTagList.Count();
                    }
                    State = STATE_EXIT;
                    break;



                case STATE_EXIT:
                    // Quit
                    Done = true;
                    break;
            }
        }
    }
    catch( std::bad_alloc& )
    {
        // Memory allocation error
        td->ResultCode = MUTLIB_RESULT_OUT_OF_MEMORY;
        std::strcpy( td->ResultString, "Not enough memory available to complete the operation.\n" );
    }
    catch(...)
    {
        // Unknown exceptions
        td->ResultCode = MUTLIB_RESULT_UNEXPECTED_EXCEPTION;
        std::strcpy( td->ResultString, "An unexpected fatal exception has occurred, please "
                     "report the details to staden-package@mrc-lmb.cam.ac.uk.\n" );
    }



    // Cleanup & exit
    delete DiffTrace;
    return td->ResultCode;
}