File: fastq-lib.cpp

package info (click to toggle)
ea-utils 1.1.2+dfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 840 kB
  • sloc: ansic: 11,459; cpp: 3,752; perl: 426; makefile: 74; sh: 42
file content (375 lines) | stat: -rw-r--r-- 11,786 bytes parent folder | download | duplicates (3)
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
/*
Copyright (c) 2011 Expression Analysis / Erik Aronesty

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include "fastq-lib.h"

#ifdef __MAIN__
int main(int argc, char **argv) {
	// todo... put testing stuff in here, so the lib can be tested independently of the other componenets
}
#endif

int read_line(FILE *in, struct line &l) {
        return (l.n = getline(&l.s, &l.a, in));
}

int read_fq(FILE *in, int rno, struct fq *fq, const char *name) {
    read_line(in, fq->id);
	if (fq->id.s && (*fq->id.s == '>')) {
		fq->id.s[0] = '@';
		// read fasta instead
		char c = fgetc(in);
		while (c != '>' && c != EOF) {
			if (fq->seq.a <= (fq->seq.n+1)) {
				fq->seq.s=(char *)realloc(fq->seq.s, fq->seq.a=(fq->seq.a+16)*2);
			}
			if (!isspace(c)) 
				fq->seq.s[fq->seq.n++]=c;
			c = fgetc(in);
		}
		if (c != EOF) {
			ungetc(c, in);
		}
		// make it look like a fastq
		fq->qual.s=(char *)realloc(fq->qual.s, fq->qual.a=(fq->seq.n+1));
		memset(fq->qual.s, 'h', fq->seq.n);
		fq->qual.s[fq->qual.n=fq->seq.n]=fq->seq.s[fq->seq.n]='\0';
		fq->com.s=(char *)malloc(fq->com.a=2);
		fq->com.n=1;
		strcpy(fq->com.s,"+");
	} else {
		read_line(in, fq->seq);
		read_line(in, fq->com);
		read_line(in, fq->qual);
	}

        if (fq->qual.n <= 0)
                return 0;
        if (fq->id.s[0] != '@' || fq->com.s[0] != '+' || fq->seq.n != fq->qual.n) {
                const char *errtyp = (fq->seq.n != fq->qual.n) ?  "length mismatch" : fq->id.s[0] != '@' ? "no '@' for id" : "no '+' for comment";
                if (name) {
                    fprintf(stderr, "Malformed fastq record (%s) in file '%s', line %d\n", errtyp, name, rno*2+1);
                } else {
                    fprintf(stderr, "Malformed fastq record (%s) at line %d\n", errtyp, rno*2+1);
                }
                return -1;
        }
        // win32-safe chomp
        fq->seq.s[--fq->seq.n] = '\0';
        if (fq->seq.s[fq->seq.n-1] == '\r') {
                fq->seq.s[--fq->seq.n] = '\0';
        }
        fq->qual.s[--fq->qual.n] = '\0';
        if (fq->qual.s[fq->qual.n-1] == '\r') {
                fq->qual.s[--fq->qual.n] = '\0';
        }
        return 1;
}

struct qual_str {
        long long int cnt;
        long long int sum;
        long long int ssq;
        long long int ns;
} quals[MAX_FILENO_QUALS+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}};

int gzclose(FILE *f, bool isgz) {
	return isgz ? pclose(f) : fclose(f);
}

FILE *gzopen(const char *f, const char *m, bool*isgz) {
	// maybe use zlib some day?
        FILE *h;
        const char * ext = fext(f);
        if (!strcmp(ext,".gz")) {
            char *tmp=(char *)malloc(strlen(f)+100);
            if (strchr(m,'w')) {
                    strcpy(tmp, "gzip --rsyncable > '");
                    strcat(tmp, f);
                    strcat(tmp, "'");
            } else {
                    strcpy(tmp, "gunzip -c '");
                    strcat(tmp, f);
                    strcat(tmp, "'");
            }
            h = popen(tmp, m);
            *isgz=1;
            free(tmp);
        } else if (!strcmp(ext,".zip")) {
            char *tmp=(char *)malloc(strlen(f)+100);
            if (strchr(m,'w')) {
                    strcpy(tmp, "zip -q '");
                    strcat(tmp, f);
                    strcat(tmp, "' -");
            } else {
                    strcpy(tmp, "unzip -p '");
                    strcat(tmp, f);
                    strcat(tmp, "'");
            }
            h = popen(tmp, m);
            *isgz=1;
            free(tmp);
        } else {
                h = fopen(f, m);
                *isgz=0;
        }
        if (!h) {
                fprintf(stderr, "Error opening file '%s': %s\n",f, strerror(errno));
                exit(1);
        }
        return h;
}

const char *fext(const char *f) {
        const char *x=strrchr(f,'.');
        return x ? x : "";
}

bool poorqual(int n, int l, const char *s, const char *q) {
        int i=0, sum=0, ns=0;
        for (i=0;i<l;++i) {
                if (s[i] == 'N')
                    ++ns;
                quals[n].cnt++;
                quals[n].ssq += q[i] * q[i];
                sum+=q[i];
        }
        quals[n].sum += sum;
        quals[n].ns += ns;
        int xmean = sum/l;
        if (quals[n].cnt < 20000) {
            // mean qual < 18 = junk
            return ((xmean-33) < 18) || (ns > 1);
        }
        // enough data? use stdev
        int pmean = quals[n].sum / quals[n].cnt;                                // mean q
        double pdev = stdev(quals[n].cnt, quals[n].sum, quals[n].ssq);          // dev q
        int serr = min(pmean/2,max(1,pdev/sqrt(l)));                                         // stderr for length l
        // mean qual < min(18,peman-serr*3) = junk/skip it
        // cap low qual, because adapters often are low qual
        // but you still need to calculate something, in case we're doing ion/pacbio
        int thr = min((33+18), (pmean - serr * 3));
        if (xmean < thr) {
//           fprintf(stderr, "POORQ xmean:%d, pmean:%d, pdev:%f, sqrt(l):%f, serr:%d, thr: %d, %s",xmean,pmean,pdev,sqrt(l),serr,thr,s);
            return 1;                                                       // ditch it
        }
        if (ns > (1+(l*quals[n].ns / quals[n].cnt))) {                          // 1 more n than average?
//           fprintf(stderr, "POORQ: ns:%d, thr: %d\n",ns,(int)(1+(l*quals[n].ns / quals[n].cnt)));
            return 1;                                                       // ditch it
        }
        return 0;
}

#define comp(c) ((c)=='A'?'T':(c)=='a'?'t':(c)=='C'?'G':(c)=='c'?'g':(c)=='G'?'C':(c)=='g'?'c':(c)=='T'?'A':(c)=='t'?'a':(c))

void revcomp(struct fq *d, struct fq *s) {
        if (!d->seq.s) {
                d->seq.s=(char *) malloc(d->seq.a=s->seq.n+1);
                d->qual.s=(char *) malloc(d->qual.a=s->qual.n+1);
        } else if (d->seq.a <= s->seq.n) {
                d->seq.s=(char *) realloc(d->seq.s, d->seq.a=(s->seq.n+1));
                d->qual.s=(char *) realloc(d->qual.s, d->qual.a=(s->qual.n+1));
        }
        int i;
        for (i=0;i<s->seq.n/2;++i) {
                char b=s->seq.s[i];
                char q=s->qual.s[i];
                //printf("%d: %c, %c\n", i, comp(s->seq.s[s->seq.n-i-1]), s->qual.s[s->qual.n-i-1]);
                d->seq.s[i]=comp(s->seq.s[s->seq.n-i-1]);
                d->qual.s[i]=s->qual.s[s->qual.n-i-1];
                //printf("%d: %c, %c\n", s->seq.n-i-1, comp(b), q);
                d->seq.s[s->seq.n-i-1]=comp(b);
                d->qual.s[s->seq.n-i-1]=q;
        }
        if (s->seq.n % 2) {
                //printf("%d: %c, %c\n", 1+s->seq.n/2, comp(s->seq.s[s->seq.n/2]));
                d->seq.s[s->seq.n/2] = comp(s->seq.s[s->seq.n/2]);
                d->qual.s[s->seq.n/2] = s->qual.s[s->seq.n/2];
        }
        d->seq.n=s->seq.n;
        d->qual.n=s->qual.n;
        d->seq.s[s->seq.n]='\0';
        d->qual.s[s->seq.n]='\0';
}

void free_line(struct line *l) {
   if (l) {
       if (l->s) free(l->s); 
       l->s=NULL;
   }
}

void free_fq(struct fq *f) {
    if (f) {
        free_line(&f->id);
        free_line(&f->seq);
        free_line(&f->com);
        free_line(&f->qual);
    }
}


/* getline.c -- Replacement for GNU C library function getline

Copyright (C) 1993 Free Software Foundation, Inc.

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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */

/* Written by Jan Brittenson, bson@gnu.ai.mit.edu.  */

#include <sys/types.h>
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>

/* Read up to (and including) a TERMINATOR from STREAM into *LINEPTR
   + OFFSET (and null-terminate it). *LINEPTR is a pointer returned from
   malloc (or NULL), pointing to *N characters of space.  It is realloc'd
   as necessary.  Return the number of characters read (not including the
   null terminator), or -1 on error or EOF.  */

int getstr (char ** lineptr, size_t *n, FILE * stream, char terminator, int offset)
{
  int nchars_avail;		/* Allocated but unused chars in *LINEPTR.  */
  char *read_pos;		/* Where we're reading into *LINEPTR. */
  int ret;

  if (!lineptr || !n || !stream)
    return -1;

  if (!*lineptr)
    {
      *n = 64;
      *lineptr = (char *) malloc (*n);
      if (!*lineptr)
	return -1;
    }

  nchars_avail = *n - offset;
  read_pos = *lineptr + offset;

  for (;;)
    {
      register int c = getc (stream);

      /* We always want at least one char left in the buffer, since we
	 always (unless we get an error while reading the first char)
	 NUL-terminate the line buffer.  */

      assert(*n - nchars_avail == read_pos - *lineptr);
      if (nchars_avail < 1)
	{
	  if (*n > 64)
	    *n *= 2;
	  else
	    *n += 64;

	  nchars_avail = *n + *lineptr - read_pos;
	  *lineptr = (char *) realloc (*lineptr, *n);
	  if (!*lineptr)
	    return -1;
	  read_pos = *n - nchars_avail + *lineptr;
	  assert(*n - nchars_avail == read_pos - *lineptr);
	}

      if (c == EOF || ferror (stream))
	{
	  /* Return partial line, if any.  */
	  if (read_pos == *lineptr)
	    return -1;
	  else
	    break;
	}

      *read_pos++ = c;
      nchars_avail--;

      if (c == terminator)
	/* Return the line.  */
	break;
    }

  /* Done - NUL terminate and return the number of chars read.  */
  *read_pos = '\0';

  ret = read_pos - (*lineptr + offset);
  return ret;
}

#if !defined(__GNUC__) || defined(__APPLE__) || defined(WIN32)

ssize_t getline(char **lineptr, size_t *n, FILE *stream)
{
  return getstr (lineptr, n, stream, '\n', 0);
}

/* 
 * public domain strtok_r() by Charlie Gordon
 *
 *   from comp.lang.c  9/14/2007
 *
 *      http://groups.google.com/group/comp.lang.c/msg/2ab1ecbb86646684
 *
 *     (Declaration that it's public domain):
 *      http://groups.google.com/group/comp.lang.c/msg/7c7b39328fefab9c
 */

char* strtok_r(char *str, const char *delim, char **nextp) 
{
    char *ret;

    if (str == NULL) {
        str = *nextp;
    }

    str += strspn(str, delim);

    if (*str == '\0'){
        return NULL;
    }
	
    ret = str;
    str += strcspn(str, delim);

    if (*str) {
        *str++ = '\0';
    }

    *nextp = str;
    return ret;
}

#endif