File: FASTA.cpp

package info (click to toggle)
snap-aligner 2.0.3%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 6,652 kB
  • sloc: cpp: 41,051; ansic: 5,239; python: 227; makefile: 85; sh: 28
file content (400 lines) | stat: -rw-r--r-- 12,246 bytes parent folder | download | duplicates (2)
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
/*++

Module Name:

    FASTA.cpp

Abstract:

    FASTA reader

Authors:

    Bill Bolosky, August, 2011

Environment:

    User mode service.

Revision History:

    Adapted from Matei Zaharia's Scala implementation.

--*/

#include "stdafx.h"
#include "Compat.h"
#include "FASTA.h"
#include "Error.h"
#include "exit.h"
#include "Util.h"
#include "DataReader.h"

using namespace std;

    bool
IsContigALT(
	const char		*contigName,
	GenomeDistance	 contigSize,
	const char* const*opt_in_alt_names,
	int				 opt_in_alt_names_count,
	const char* const*opt_out_alt_names,
	int				 opt_out_alt_names_count,
	GenomeDistance	 maxSizeForAutomaticALT,
    bool             autoALT)
{

	for (int i = 0; i < opt_out_alt_names_count; i++) {
		if (!_stricmp(opt_out_alt_names[i], contigName)) {
			return false;
		}
	} // opt out

	if (contigSize <= maxSizeForAutomaticALT) {
		return true;
	}

	for (int i = 0; i < opt_in_alt_names_count; i++) {
		if (!_stricmp(opt_in_alt_names[i], contigName)) {
			return true;
		} // match
	} // opt in

    if (autoALT && ((strlen(contigName) > 4 && !_stricmp(contigName + strlen(contigName) - 4, "_alt")) || 
                    (strlen(contigName) > 3 && (contigName[0] == 'H' || contigName[0] == 'h') && (contigName[1] == 'L' || contigName[1] == 'l') && (contigName[2] == 'A' || contigName[2] == 'a') && contigName[3] == '-')))  {
        return true;
    }

    return false;
} // MarkALTContigIfAppropriate


//
// There are several ways of specifying ALT contigs.  There is an opt-in list of ALTs, an opt-out list of regular chromosomes (these must be mutually
// exclusive), and a size cutoff below which is contig is an ALT.  The opt-in and opt-out lists supersede the size cutoff.
//

struct ContigLine {
    char* bases;
    ContigLine* next;

    ContigLine() {
        bases = NULL;
        next = NULL;
    }
};

struct RawContigData {
    ContigLine* lines;
    ContigLine* lastLine;
    GenomeDistance totalSize;
    char* name;
    RawContigData* next;
    int contigNumber;   // Where this contig is in the original FASTA file

    RawContigData() {
        lines = NULL;
        lastLine = NULL;
        totalSize = 0;
        name = NULL;
        next = NULL;
        contigNumber = -1;
    }

    void addLine(const char* bases) {
        ContigLine*line = new ContigLine();
        size_t size = strlen(bases) + 1;
        line->bases = new char[size];
        strncpy(line->bases, bases, size);
        if (lines == NULL) {
            lines = lastLine = line;
        } else {
            lastLine->next = line;
            lastLine = line;
        }
    } // addLine

    ~RawContigData() {
        delete[] name;

        while (lines != NULL) {
            ContigLine* toDelete = lines;
            lines = lines->next;
            delete[] toDelete->bases;
            delete toDelete;
        }
    }
}; // RawContigData

   void
AddRawContigToList(
    RawContigData*   currentContig,
    RawContigData**  altContigs,
    RawContigData**  regularContigs,
    const char* const* opt_in_alt_names,
    int				 opt_in_alt_names_count,
    const char* const* opt_out_alt_names,
    int				 opt_out_alt_names_count,
    GenomeDistance	 maxSizeForAutomaticALT,
    bool             autoALT)
{
    if (IsContigALT(currentContig->name, currentContig->totalSize, opt_in_alt_names, opt_in_alt_names_count, opt_out_alt_names,
        opt_out_alt_names_count, maxSizeForAutomaticALT, autoALT)) {
        currentContig->next = *altContigs;
        *altContigs = currentContig;
    }  else {
        currentContig->next = *regularContigs;
        *regularContigs = currentContig;
    }
}

   void
AddContigToGenome(
    RawContigData   *contig,
    Genome          *genome,
    char            *paddingBuffer)
{
    genome->addData(paddingBuffer);
    genome->startContig(contig->name, contig->contigNumber);

    for (ContigLine* line = contig->lines; NULL != line; line = line->next) {
        genome->addData(line->bases);
    }
} // AddContigToGenome

   void
ReverseContigList(RawContigData** head) 
{
    if (*head == NULL) {
        return;
    }

    RawContigData* cur = *head;
    RawContigData* prev = NULL;

    for (;;) {
        RawContigData* next = cur->next;
        cur->next = prev;

        if (next == NULL) {
            *head = cur;
            return;
        }

        prev = cur;
        cur = next;
    } // for ever
} // ReverseContigList

    const Genome *
ReadFASTAGenome(
	const char		*fileName,
	const char		*pieceNameTerminatorCharacters,
	bool			 spaceIsAPieceNameTerminator,
	unsigned		 chromosomePaddingSize,
	const char* const*opt_in_alt_names,
	int				 opt_in_alt_names_count,
	const char* const*opt_out_alt_names,
	int				 opt_out_alt_names_count,
	GenomeDistance	 maxSizeForAutomaticALT,
    bool             autoALT,
    char            **alt_liftover_contig_names,
	unsigned		*alt_liftover_contig_flags,
	char			**alt_liftover_proj_contig_names,
	unsigned		*alt_liftover_proj_contig_offsets,
	char			**alt_liftover_proj_cigar,
	int				 alt_liftover_count)
{
    //
    // We need to know a bound on the size of the genome before we create the Genome object.
    // A bound is the number of bytes in the FASTA file, because we store at most one base per
    // byte. We count the bytes as we read them rather than getting the file size so that
    // we can deal with inputs that are redirected to pipes.
    //
    _int64 fileSize = 0;
    bool isValidGenomeCharacter[256];

    for (int i = 0; i < 256; i++) {
        isValidGenomeCharacter[i] = false;
    }

    isValidGenomeCharacter['A'] = isValidGenomeCharacter['T'] = isValidGenomeCharacter['C'] = isValidGenomeCharacter['G'] = isValidGenomeCharacter['N'] = true;
    isValidGenomeCharacter['a'] = isValidGenomeCharacter['t'] = isValidGenomeCharacter['c'] = isValidGenomeCharacter['g'] = isValidGenomeCharacter['n'] = true;

    DataReader* fastaDataReader = getDefaultOrGzipDataReader(fileName);

    if (fastaDataReader == NULL) {
        WriteErrorMessage("Unable to open FASTA file '%s' (does it exist and do you have permission to open it?)\n", fileName);
        return NULL;
    }

    int lineBufferSize = 0;
    char *lineBuffer;
 
    //
    // Read in the raw data and split it up by chromosome.  We're going to rearrange it to put the ALT chromosomes at the end so that it's
    // quick to test whether a GenomeLocation is ALT or not.
    //
    unsigned nContigs = 0;

    RawContigData* regularContigs = NULL;
    RawContigData* altContigs = NULL;
    RawContigData* currentContig = NULL;

    bool warningIssued = false;
    bool inAContig = false;

    int nextContigNumber = 0;

    while (NULL != reallocatingFgets(&lineBuffer, &lineBufferSize, fastaDataReader)) {
        fileSize += strlen(lineBuffer);
        if (lineBuffer[0] == '>') {
            nContigs++;

            if (inAContig) {
                AddRawContigToList(currentContig, &altContigs, &regularContigs, opt_in_alt_names, opt_in_alt_names_count, opt_out_alt_names, opt_out_alt_names_count, maxSizeForAutomaticALT, autoALT);
			}

            currentContig = new RawContigData();

            inAContig = true;

            //
            // Now supply the contig name.
            //
            if (NULL != pieceNameTerminatorCharacters) {
                for (int i = 0; i < strlen(pieceNameTerminatorCharacters); i++) {
                    char *terminator = strchr(lineBuffer+1, pieceNameTerminatorCharacters[i]);
                    if (NULL != terminator) {
                        *terminator = '\0';
                    }
                }
            }

            if (spaceIsAPieceNameTerminator) {
                char *terminator = strchr(lineBuffer, ' ');
                if (NULL != terminator) {
                    *terminator = '\0';
                }

                terminator = strchr(lineBuffer, '\t');
                if (NULL != terminator) {
                    *terminator = '\0';
                }
            }

            char *terminator = strchr(lineBuffer, '\n');
            if (NULL != terminator) {
                *terminator = '\0';
            }

            terminator = strchr(lineBuffer, '\r');
            if (NULL != terminator) {
                *terminator = '\0';
            }

            size_t nameLength = strlen(lineBuffer + 1) + 1;

            currentContig->name = new char[nameLength];
            strncpy(currentContig->name, lineBuffer + 1, nameLength);
            currentContig->contigNumber = nextContigNumber;
            nextContigNumber++;

        } else {
            if (!inAContig) {
                WriteErrorMessage("\nFASTA file doesn't begin with a contig name (i.e., the first line doesn't start with '>').\n");
                soft_exit(1);
            }

            //
            // Convert it to upper case and truncate the newline before adding it to the genome.
            //

            char *newline = strchr(lineBuffer, '\n');
            if (NULL != newline) {
                *newline = 0;
            }

            //
            // Also smash CR for Windows-style CRLF text.
            //
            newline = strchr(lineBuffer, '\r');
            if (NULL != newline) {
                *newline = 0;
            }

            size_t lineLen = strlen(lineBuffer);

			for (unsigned i = 0; i < lineLen; i++) {
              lineBuffer[i] = toupper(lineBuffer[i]);
            }

			currentContig->totalSize += lineLen;

			for (unsigned i = 0; i < lineLen; i++) {
                if (!isValidGenomeCharacter[(unsigned char)lineBuffer[i]]) {
                    if (!warningIssued) {
                        WriteErrorMessage("\nFASTA file contained a character that's not a valid base (or N): '%c', full line '%s'; \nconverting to 'N'.  This may happen again, but there will be no more warnings.\n", lineBuffer[i], lineBuffer);
                        warningIssued = true;
                    }
                    lineBuffer[i] = 'N';
                }
            }

            currentContig->addLine(lineBuffer);
        }
    }

	if (!inAContig) {
		WriteErrorMessage("The FASTA file was empty.");
		return NULL;
	}

    AddRawContigToList(currentContig, &altContigs, &regularContigs, opt_in_alt_names, opt_in_alt_names_count, opt_out_alt_names, opt_out_alt_names_count, maxSizeForAutomaticALT, autoALT);

    //
    // AddRawContigToList reversed them.  Reverse them again so that they're in the same order as the FASTA, except that all ALTs follow all non-ALTs.
    // That's necessary to have the test for ALT be a simple comparison.  We fix that at sort time so they come out in the original order.
    //
    ReverseContigList(&altContigs);
    ReverseContigList(&regularContigs);

    Genome* genome = new Genome(fileSize + ((_int64)nContigs + 1) * (size_t)chromosomePaddingSize, fileSize + ((_int64)nContigs + 1) * (size_t)chromosomePaddingSize, chromosomePaddingSize, nContigs + 1);

    char* paddingBuffer = new char[(GenomeDistance)chromosomePaddingSize + 1];
    for (unsigned i = 0; i < chromosomePaddingSize; i++) {
        paddingBuffer[i] = 'n';
    }
    paddingBuffer[chromosomePaddingSize] = '\0';

    while (regularContigs != NULL) {
        AddContigToGenome(regularContigs, genome, paddingBuffer);
        RawContigData* toDelete = regularContigs;
        regularContigs = regularContigs->next;
        delete toDelete;
    }

    while (altContigs != NULL) {
        AddContigToGenome(altContigs, genome, paddingBuffer);
        genome->markContigALT(altContigs->name);
        if (alt_liftover_count > 0) {
            genome->markContigLiftover(altContigs->name, alt_liftover_contig_names, alt_liftover_contig_flags, alt_liftover_proj_contig_names, alt_liftover_proj_contig_offsets, alt_liftover_proj_cigar, alt_liftover_count);
        }
        RawContigData* toDelete = altContigs;
        altContigs = altContigs->next;
        delete toDelete;
    }

    //
    // And finally add padding at the end of the genome.
    //
    genome->addData(paddingBuffer);
    genome->fillInContigLengths();
    genome->sortContigsByName();
    genome->setUpContigNumbersByOriginalOrder();

    delete fastaDataReader;
    delete [] paddingBuffer;
    delete [] lineBuffer;
    return genome;
}