2 package org.forester.io.writers;
4 import java.io.IOException;
8 import org.forester.sequence.BasicSequence;
9 import org.forester.sequence.Sequence;
10 import org.forester.util.ForesterUtil;
12 public class SequenceWriter {
14 public static enum SEQ_FORMAT {
18 public static void main( final String[] args ) {
19 final Sequence s = BasicSequence.createAaSequence( "name", "abcdefghiiklmnap" );
20 System.out.println( s.toString() );
21 System.out.println( SequenceWriter.toFasta( s, 0 ).toString() );
22 System.out.println( SequenceWriter.toFasta( s, 5 ).toString() );
23 System.out.println( SequenceWriter.toFasta( s, 8 ).toString() );
24 System.out.println( SequenceWriter.toFasta( s, 4 ).toString() );
25 System.out.println( SequenceWriter.toFasta( s, 3 ).toString() );
26 System.out.println( SequenceWriter.toFasta( s, 2 ).toString() );
27 System.out.println( SequenceWriter.toFasta( s, 1 ).toString() );
28 System.out.println( SequenceWriter.toFasta( s, 100 ).toString() );
29 System.out.println( SequenceWriter.toFasta( s, 15 ).toString() );
30 System.out.println( SequenceWriter.toFasta( s, 16 ).toString() );
33 public static StringBuilder toFasta( final Sequence seq, final int width ) {
34 final StringBuilder sb = new StringBuilder();
36 sb.append( seq.getIdentifier().toString() );
37 sb.append( ForesterUtil.LINE_SEPARATOR );
38 if ( ( width < 1 ) || ( width >= seq.getLength() ) ) {
39 sb.append( seq.getMolecularSequence() );
42 final int lines = seq.getLength() / width;
43 final int rest = seq.getLength() - ( lines * width );
44 for( int i = 0; i < lines; ++i ) {
45 sb.append( seq.getMolecularSequence(), i * width, width );
46 if ( i < ( lines - 1 ) ) {
47 sb.append( ForesterUtil.LINE_SEPARATOR );
51 sb.append( ForesterUtil.LINE_SEPARATOR );
52 sb.append( seq.getMolecularSequence(), lines * width, rest );
58 public static void toFasta( final Sequence seq, final Writer w, final int width ) throws IOException {
60 w.write( seq.getIdentifier().toString() );
61 w.write( ForesterUtil.LINE_SEPARATOR );
62 if ( ( width < 1 ) || ( width >= seq.getLength() ) ) {
63 w.write( seq.getMolecularSequence() );
66 final int lines = seq.getLength() / width;
67 final int rest = seq.getLength() - ( lines * width );
68 for( int i = 0; i < lines; ++i ) {
69 w.write( seq.getMolecularSequence(), i * width, width );
70 if ( i < ( lines - 1 ) ) {
71 w.write( ForesterUtil.LINE_SEPARATOR );
75 w.write( ForesterUtil.LINE_SEPARATOR );
76 w.write( seq.getMolecularSequence(), lines * width, rest );
81 public static void writeSeqs( final List<Sequence> seqs,
83 final SEQ_FORMAT format,
84 final int width ) throws IOException {
87 for( final Sequence s : seqs ) {
88 toFasta( s, writer, width );
89 writer.write( ForesterUtil.LINE_SEPARATOR );
93 throw new RuntimeException( "unknown format " + format );