File: SequenceReader.java

package info (click to toggle)
proalign 0.603-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 492 kB
  • sloc: java: 8,673; sh: 27; makefile: 4
file content (641 lines) | stat: -rw-r--r-- 14,925 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
/**
 * Title:        ProAlign<p>
 * Description:  <p>
 * Copyright:    Copyright (c) Ari Loytynoja<p>
 * License:      GNU GENERAL PUBLIC LICENSE<p>
 * @see          http://www.gnu.org/copyleft/gpl.html
 * Company:      ULB<p>
 * @author Ari Loytynoja
 * @version 1.0
 */
package proalign;

import java.io.File;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.HashMap;
import java.io.IOException;
import java.io.FileNotFoundException;

/**
 * Reads FASTA/PIR format alignment files.
 * Data read into a hashtable: String 'name', String 'data'
 */
public class SequenceReader {
    String row, str1, str2 = new String();
    HashMap seqmap;
    boolean allFine;
    String alphabet;
    String errors;

    SequenceReader() { }


    /**
     * Tries to read from a file. Returns TRUE if fine, FALSE if errors.
     */
    boolean fromFile(String infile) {

	allFine = true;
	seqmap = new HashMap();
	errors = new String("\n");

	ProAlign.log("SequenceReader: "+infile);

	String firstRow = new String();
	try {
	    InFile in = new InFile(infile);
	    while(true) {
		firstRow = in.readLine().trim();
		if(firstRow.equals("")) {
		    continue;
		}
		break;
	    }
	    
	} catch(FileNotFoundException e) {
	    warnError("File not found:" + infile);
	} catch(IOException e) { }

	if(firstRow.startsWith(">")) {
	    readFasta(infile);
	} else if(Character.isDigit(firstRow.charAt(0))) {
	    readPhylip(infile);
	} else if(firstRow.equalsIgnoreCase("#nexus")) {
	    readNexus(infile);
	} else if(firstRow.equalsIgnoreCase("PileUp")||
		  firstRow.equalsIgnoreCase("!!AA_MULTIPLE_ALIGNMENT")||
		  firstRow.equalsIgnoreCase("!!NA_MULTIPLE_ALIGNMENT")) {
	    readMsf(infile);
	} else {
	    warnError("     The file does not look like Fasta-,\n"+
		      "    PIR-, Phylip-, MSF-, or Nexus-format!");
	}

	if(seqmap.size()>0 && allFine) {
	    return true;
	} else {
	    return false;
	}
    }


    void readFasta(String infile) {
	
	try {
	    
	    // Calls ready-made filereader
	    InFile in = new InFile(infile);
	    
	    int formatType = 0;

	    while(true) { // Read first non-empty line
		row = in.readLine().trim();
		if(row.equals("")) {
		    continue;
		}
		break;
	    }

	    while(row != null) {
		
		// Takes sequence name and checks
		// that same name doesn't exist
		if(row.startsWith(">")) {
		    row = row.substring(1);
		    row = row.trim();
		    
		    // Sequence is PIR
		    if(row.startsWith("DL;")) {
			formatType = 1;
			row = row.substring(3);
			row = row.trim();
			in.readLine(); // skip one row!
			
		    } else if(row.startsWith("P1;")) {
			formatType = 2;
			row = row.substring(3);
			row = row.trim();
			in.readLine(); // skip one row!
			
			//Sequence must be FASTA
		    } else {
			formatType = 0;
		    }
		    
		    // Same sequence name given twice!!
		    if(seqmap.containsKey(row)) {
			warnError("  Sequence " + row + "\n     is double defined!");
		    }
		    
		    if(formatType > 0) { // If PIR -> has to end with '*'
			
			str2 = "";
			while((str1 = in.readLine())!= null) {
			    			    
			    // remove "gap" signs
			    if(str1.indexOf("-")>-1) {
				str1 = removeChar(str1,'-');
			    }
			    if(str1.indexOf(" ")>-1) {
				str1 = removeSpace(str1);
			    }
			    
			    if(str1.length() == 0) {  // Skips empty lines.
				continue;   
			    }
			    
			    str2 += str1;
			    
			    if(str1.endsWith("*")){ // Reads until the asterisk (needed!)
				
				str1 = str2.substring(0,str2.indexOf("*")); // but removed.
				str1 = str1.toUpperCase();
				
				seqmap.put(row, str1);
				ProAlign.log(">"+row+"\n"+str1);
				
				row = in.readLine(); // New one in!
				break;
			    }
			}
		    }

		    
		    
		    // Append FASTA sequence and save it.
		    else { // If FASTA -> no '*' in the end
			
			str2 = "";
			while((str1 = in.readLine())!= null) {
			    
			    // remove "gap" signs
			    if(str1.indexOf("-")>-1) {
				str1 = removeChar(str1,'-');
			    }
			    if(str1.indexOf(" ")>-1) {
				str1 = removeSpace(str1);
			    }
			    
			    if(str1.length() == 0) { // Skips empty lines.
				continue;
			    }
			    
			    if(str1.startsWith(">")){  // Loop works until a new seqname
				
				str2 = str2.toUpperCase();			    
				
				seqmap.put(row, str2);
				ProAlign.log(">"+row+"\n"+str2);
				
				row = str1; // Copy new one
				row = row.trim();
				break;
			    }
			    str2 += str1;
			}
			if(str1 == null) { // Take the last seq. End of the file.
			    
			    str2 = str2.toUpperCase();			    
			    
			    seqmap.put(row, str2);
			    ProAlign.log(">"+row+"\n"+str2);
			    
			    row = str1; // Copy null so first loop stops
			}
		    }
		} else if(row.trim().equals("")){
		    row = in.readLine();
		    continue;		    
		} else {
		    warnError("  File '" + infile + "'\n"+
			      "    is supposed to start with '>'!");
		    break;
		    //row = in.readLine();
		}
	    }
	    in.close();
	    
	    // Something wrong. Give warnings and return.
	} catch(FileNotFoundException e) {
	    warnError("File not found:" + infile);
		
	} catch(IOException e) { }
    }

    void readPhylip(String infile) {

	String[] seqNames = new String[0];
	String[] seqData = new String[0];

	String row = new String();
	try {
	    InFile in = new InFile(infile);
	    while(true) {
		row = in.readLine().trim();
		if(row.equals("")) {
		    continue;
		}
		break;
	    }

	    int numTaxa = new Integer(row.substring(0,row.indexOf(" ")).trim()).intValue();
	    int seqLength = new Integer(row.substring(row.indexOf(" ")+1).trim()).intValue();

	    seqNames = new String[numTaxa];
	    seqData = new String[numTaxa];

	    int sn = 0;
	    int rn = 0;
	    while((row = in.readLine())!= null) {
		if(row.trim().equals("")) {
		    continue;
		}
		if(rn<numTaxa) {
		    seqNames[sn] = row.substring(0,row.indexOf(" ")).trim();
		    seqData[sn] = row.substring(row.indexOf(" ")+1).trim();
		    rn++; sn++;
		} else {
		    seqData[sn++] += row.trim();
		}
		if(sn==numTaxa) {
		    sn=0;
		}
	    }
	    in.close();
	    
	    // Something wrong. Give warnings and return.
	} catch(FileNotFoundException e) {
	    warnError("File not found:" + infile);
		
	} catch(IOException e) { }

	for(int i=0; i<seqNames.length; i++) {

	    if(seqmap.containsKey(seqNames[i])) {
		warnError("  Sequence " +seqNames[i]+ "\n     is double defined!");
	    }

	    String seq = removeSpace(seqData[i].toUpperCase());
	    seq = removeChar(seq,'-');

	    seqmap.put(seqNames[i],seq);
	    ProAlign.log(">"+seqNames[i]+"\n"+seq);
	}
    }


    void readMsf(String infile) {

	String[] seqNames = new String[0];
	String[] seqData = new String[0];
	HashMap names = new HashMap();

	String row = new String();
	try {
	    InFile in = new InFile(infile);
	    int s=0;
	    while(true) {
		row = in.readLine().trim();
		if(row.startsWith("//")) {
		    break;
		} else if(row.indexOf("Name:")>-1) {
		    row = row.substring(row.indexOf("Name:")+5).trim();
		    if(row.indexOf(" ")>-1) {
			row = row.substring(0,row.indexOf(" ")).trim();
		    }
		    names.put(row,new Integer(s));
		    s++;
		} else {
		    continue;		    
		}
	    }
	    
	    seqNames = new String[names.size()];
	    seqData = new String[names.size()];

	    Iterator nameKeys = names.keySet().iterator();
	    while(nameKeys.hasNext()) {
		String n = (String) nameKeys.next();
		s = ((Integer)names.get(n)).intValue();
		seqNames[s] = n;
		seqData[s] = "";
	    }

	    while((row = in.readLine())!= null) {
		if(row.trim().equals("")) {
		    continue;
		}
		
		String begin = row.substring(0,row.indexOf(" ")).trim();

		if(names.containsKey(begin)) {

		    String end = row.substring(row.indexOf(" ")+1).trim();
		    s = ((Integer)names.get(begin)).intValue();
		    seqData[s] += end;

		}
	    }
	    in.close();
	    
	    // Something wrong. Give warnings and return.
	} catch(FileNotFoundException e) {
	    warnError("File not found:" + infile);
		
	} catch(IOException e) { }

	for(int i=0; i<seqNames.length; i++) {

	    if(seqmap.containsKey(seqNames[i])) {
		warnError("  Sequence " +seqNames[i]+ "\n     is double defined!");
	    }

	    String seq = removeSpace(seqData[i].toUpperCase());
	    seq = removeChar(seq,'-');
	    seq = removeChar(seq,'.');
	    seq = removeChar(seq,'~');

	    seqmap.put(seqNames[i],seq);
	    ProAlign.log(">"+seqNames[i]+"\n"+seq);
	}
//
	ProAlign.log.print("CORE ");
	for(int m=0; m<seqData[0].length(); m++) {
	    if(Character.isUpperCase(seqData[0].charAt(m))) {
		ProAlign.log.print("1");
	    } else {
		ProAlign.log.print("0");	
	    }    
	}
	ProAlign.log.println();
//
    }



    void readNexus(String infile) {

	String[] seqNames = new String[0];
	String[] seqData = new String[0];
	String missing = new String("?");

	try {
	    
	    // Calls ready-made filereader
	    InFile in = new InFile(infile);
	    int order = 0;
	    
	    int numChar = 0;
	    int numTaxa = 0;
	    
	    boolean interleave = false;
	    
	    String row = in.readLine(); // Read first line
	    while((row != null)) {
		
		row = row.toUpperCase().trim();
		
		if(row.startsWith("DIMENSIONS")) {
		    if(row.indexOf("NTAX")>-1) {
			String ntax = row.substring(row.indexOf("NTAX"));
			ntax = ntax.substring(ntax.indexOf("=")+1);
			if(ntax.indexOf(" ")>0) {
			    ntax = ntax.substring(0,ntax.indexOf(" "));
			} else {
			    ntax = ntax.substring(0,ntax.indexOf(";"));
			}
			numTaxa = Integer.valueOf(ntax).intValue();
		    }
		    if(row.indexOf("NCHAR")>-1) {
			String nchar = row.substring(row.indexOf("NCHAR"));
			nchar = nchar.substring(nchar.indexOf("=")+1);
			if(nchar.indexOf(" ")>0) {
			    nchar = nchar.substring(0,nchar.indexOf(" "));
			} else {
			    nchar = nchar.substring(0,nchar.indexOf(";"));
			}
			numChar = Integer.valueOf(nchar).intValue();
		    }
		}
		
		if(row.indexOf("MISSING")>-1) {
		    missing = row.substring(row.indexOf("MISSING"));
		    missing = missing.substring(missing.indexOf("=")+1);
		    if(missing.indexOf(" ")>0) {
			missing = missing.substring(0,missing.indexOf(" "));
		    } else {
			missing = missing.substring(0,missing.indexOf(";"));
		    }
		} else if(row.indexOf("GAP")>-1) {
		    missing = row.substring(row.indexOf("GAP"));
		    missing = missing.substring(missing.indexOf("=")+1);
		    if(missing.indexOf(" ")>0) {
			missing = missing.substring(0,missing.indexOf(" "));
		    } else if(missing.indexOf(";")>0) {
			missing = missing.substring(0,missing.indexOf(";"));
		    } else {
			missing = missing.trim();
		    }
		}
		if(row.indexOf("INTERLEAVE")>0) {
		    interleave = true;
		}

		if(row.startsWith("MATRIX")) {

		    // sequence data starts.
		    seqNames = new String[numTaxa];
		    seqData = new String[numTaxa];
		    
		    row = in.readLine();
		    while((row != null)) {
			row = row.trim();
			if(!interleave) {
			    for(int i=0; i<numTaxa; i++) {
				
				if(row.length() == 0 ) {
				    row = in.readLine().trim();
				    continue;
				}			
				if(row.indexOf("[")>-1) {
				    row = removeComment(row);
				}
				//System.out.println(i+": "+row);
				if(row.indexOf(" ")>-1) {
				    seqNames[i] = row.substring(0,row.indexOf(" "));
				    row = row.substring(row.indexOf(" ")+1).toUpperCase();

				    seqData[i] = removeSpace(row);
				    row = in.readLine();
				    while(seqData[i].length() < numChar) {
					if(row.length() == 0 ) {
					    row = in.readLine().trim();
					    continue;
					}
					row = row.toUpperCase();
					seqData[i] += removeSpace(row);
					row = in.readLine();
				    }
				} else {
				    seqNames[i] = row.trim();
				    row = in.readLine().trim();
				    //System.out.println(i+": "+row);
				    seqData[i] = removeSpace(row);
				    row = in.readLine();
				    while(seqData[i].length() < numChar) {
					if(row.length() == 0 ) {
					    row = in.readLine().trim();
					    continue;
					}
					row = row.toUpperCase();
					seqData[i] += removeSpace(row);
					row = in.readLine();
				    }
				} 

			    }
			    break;
			} else {
			    for(int i=0; i<numTaxa; i++) {
				if(row.length() == 0 ) {
				    row = in.readLine().trim();
				    continue;
				}
				seqNames[i] = row.substring(0,row.indexOf(" "));
				row = row.substring(row.indexOf(" ")+1).toUpperCase();
				seqData[i] = removeSpace(row);
				row = in.readLine().trim();
			    }
			    while(seqData[0].length() < numChar) {
				if(row.length() == 0 ) {
				    row = in.readLine().trim();
				    continue;
				}
				for(int i=0; i<numTaxa; i++) {
				    row = row.substring(row.indexOf(" ")+1).toUpperCase();
				    seqData[i] += removeSpace(row);
				    row = in.readLine().trim();
				}
			    }
			    break;
			}
		    }
		}
		
		row = in.readLine();
	    }
	    in.close();

	    // Something wrong. Give warnings and return.
	} catch(FileNotFoundException e) {
	    warnError("File not found:" + infile);
	    
	} catch(IOException e) { }
	
	for(int i=0; i<seqNames.length; i++) {
	    
	    if(seqmap.containsKey(seqNames[i])) {
		warnError("  Sequence " +seqNames[i]+ 
			  "\n     is double defined!");
	    }
	    
	    String seq = seqData[i].toUpperCase();
	    seq = removeChar(seqData[i],missing.charAt(0));

	    seqmap.put(seqNames[i].trim(),seq);
	    ProAlign.log(">"+seqNames[i]+"\n"+seq);
	}
    }


    String removeSpace(String row) {
	if(row.indexOf(" ")>-1) {
	    String str = new String("");
	    for(int j=0; j<row.length(); j++) {
		if(row.charAt(j)!=' ') {
		    str += row.charAt(j);
		}
	    }
	    return str;
	} else {
	    return row;
	}
    }

    String removeChar(String row,char rem) {
	if(row.indexOf(rem)>-1) {
	    String str = new String("");
	    for(int j=0; j<row.length(); j++) {
		if(row.charAt(j)!=rem) {
		    str += row.charAt(j);
		}
	    }
	    return str;
	} else {
	    return row;
	}
    }

    String removeComment(String row) {

	String content = new String();
	boolean keep = true;
	for(int i=0; i<row.length(); i++) {
	    if(row.charAt(i)=='[') {
		keep=false;
	    } else if(row.charAt(i)==']') {
		keep=true;
		i++;
	    }
	    if(keep) {
		content += row.charAt(i);
	    }
	}
	return content.trim();
    }


    /**
     * Reading sequences returns just TRUE or FALSE.
     * Return sequences if reading the file was OK. 
     */
    public HashMap getSequences() {
	return seqmap;
    }
    
    void warnError(String msg) {
	allFine = false;
	ProAlign.log.println("SequenceReader: "+msg);
	errors += msg+"\n";
    }
    String getErrors() {
	return errors;
    }

/*   
    public static void main(String[] args) {
        SequenceReader sr = new SequenceReader();
        if(sr.fromFile(args[0])) {
	    
	    HashMap seqs = sr.getSequences();
	    Iterator it = seqs.keySet().iterator();
	    while(it.hasNext()) {
		String name = (String) it.next();
		String seq = (String) seqs.get(name);
		System.out.println(name+"\n"+seq);
	    }
	} 
    }
//*/
}