02da257664a0817e2a58a9a5a094e847a0dd8a99
[jalview.git] / forester / java / src / org / forester / msa / BasicMsa.java
1 // $Id:
2 // forester -- software libraries and applications
3 // for genomics and evolutionary biology research.
4 //
5 // Copyright (C) 2010 Christian M Zmasek
6 // Copyright (C) 2010 Sanford-Burnham Medical Research Institute
7 // All rights reserved
8 //
9 // This library is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU Lesser General Public
11 // License as published by the Free Software Foundation; either
12 // version 2.1 of the License, or (at your option) any later version.
13 //
14 // This library is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // Lesser General Public License for more details.
18 //
19 // You should have received a copy of the GNU Lesser General Public
20 // License along with this library; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
22 //
23 // Contact: phylosoft @ gmail . com
24 // WWW: https://sites.google.com/site/cmzmasek/home/software/forester
25
26 package org.forester.msa;
27
28 import java.io.IOException;
29 import java.io.StringWriter;
30 import java.io.Writer;
31 import java.util.ArrayList;
32 import java.util.HashSet;
33 import java.util.List;
34 import java.util.Set;
35
36 import org.forester.io.writers.SequenceWriter;
37 import org.forester.io.writers.SequenceWriter.SEQ_FORMAT;
38 import org.forester.sequence.BasicSequence;
39 import org.forester.sequence.MolecularSequence;
40 import org.forester.sequence.MolecularSequence.TYPE;
41 import org.forester.util.ForesterUtil;
42
43 public class BasicMsa implements Msa {
44
45     private final char[][]    _data;
46     private final String[]    _identifiers;
47     private final Set<String> _identifiers_set;
48     private final TYPE        _type;
49
50     public BasicMsa( final int rows, final int columns, final TYPE type ) {
51         if ( ( rows < 1 ) || ( columns < 1 ) ) {
52             throw new IllegalArgumentException( "basic msa of size zero are illegal" );
53         }
54         _data = new char[ rows ][ columns ];
55         _identifiers = new String[ rows ];
56         _identifiers_set = new HashSet<String>();
57         _type = type;
58     }
59
60     BasicMsa( final BasicMsa msa ) {
61         _data = msa._data;
62         _identifiers = msa._identifiers;
63         _type = msa._type;
64         _identifiers_set = msa._identifiers_set;
65     }
66
67     @Override
68     public List<MolecularSequence> asSequenceList() {
69         final List<MolecularSequence> seqs = new ArrayList<MolecularSequence>();
70         for( int i = 0; i < getNumberOfSequences(); ++i ) {
71             seqs.add( getSequence( i ) );
72         }
73         return seqs;
74     }
75
76     @Override
77     public List<Character> getColumnAt( final int col ) {
78         final List<Character> column = new ArrayList<Character>();
79         for( int row = 0; row < getNumberOfSequences(); ++row ) {
80             column.add( getResidueAt( row, col ) );
81         }
82         return column;
83     }
84
85     @Override
86     public String getIdentifier( final int row ) {
87         return _identifiers[ row ];
88     }
89
90     @Override
91     public int getLength() {
92         return _data[ 0 ].length;
93     }
94
95     @Override
96     public int getNumberOfSequences() {
97         return _identifiers.length;
98     }
99
100     @Override
101     public char getResidueAt( final int row, final int col ) {
102         return _data[ row ][ col ];
103     }
104
105     @Override
106     public MolecularSequence getSequence( final int row ) {
107         return new BasicSequence( getIdentifier( row ), _data[ row ], getType() );
108     }
109
110     @Override
111     public MolecularSequence getSequence( final String id ) {
112         for( int i = 0; i < getNumberOfSequences(); ++i ) {
113             if ( getIdentifier( i ).equals( id ) ) {
114                 return getSequence( i );
115             }
116         }
117         return null;
118     }
119
120     @Override
121     public StringBuffer getSequenceAsString( final int row ) {
122         final StringBuffer sb = new StringBuffer( getLength() );
123         for( int col = 0; col < getLength(); ++col ) {
124             sb.append( getResidueAt( row, col ) );
125         }
126         return sb;
127     }
128
129     @Override
130     public TYPE getType() {
131         return _type;
132     }
133
134     @Override
135     public boolean isGapAt( final int row, final int col ) {
136         return getResidueAt( row, col ) == MolecularSequence.GAP;
137     }
138
139     @Override
140     public void setIdentifier( final int row, final String id ) {
141         if ( ForesterUtil.isEmpty( id ) ) {
142             throw new IllegalArgumentException( "illegal attempt to create msa with empty identifier" );
143         }
144         if ( _identifiers_set.contains( id ) ) {
145             throw new IllegalArgumentException( "illegal attempt to create msa with non-unique identifiers [" + id
146                                                 + "]" );
147         }
148         _identifiers_set.add( id );
149         _identifiers[ row ] = id;
150     }
151
152     @Override
153     public void setResidueAt( final int row, final int col, final char residue ) {
154         _data[ row ][ col ] = residue;
155     }
156
157     @Override
158     public String toString() {
159         final Writer w = new StringWriter();
160         try {
161             write( w, MSA_FORMAT.PHYLIP );
162         }
163         catch ( final IOException e ) {
164             e.printStackTrace();
165         }
166         return w.toString();
167     }
168
169     @Override
170     public void write( final Writer w, final MSA_FORMAT format ) throws IOException {
171         switch ( format ) {
172             case PHYLIP:
173                 writeToPhylip( w );
174                 break;
175             case FASTA:
176                 writeToFasta( w );
177                 break;
178             case NEXUS:
179                 writeToNexus( w );
180                 break;
181             default:
182                 throw new RuntimeException( "unknown format " + format );
183         }
184     }
185
186     private short determineMaxIdLength() {
187         short max = 0;
188         for( int row = 0; row < getNumberOfSequences(); ++row ) {
189             final short l = ( short ) getIdentifier( row ).length();
190             if ( l > max ) {
191                 max = l;
192             }
193         }
194         return max;
195     }
196
197     private void writeToFasta( final Writer w ) throws IOException {
198         SequenceWriter.writeSeqs( asSequenceList(), w, SEQ_FORMAT.FASTA, 100 );
199     }
200
201     private void writeToNexus( final Writer w ) throws IOException {
202         final int max = determineMaxIdLength() + 1;
203         w.write( "Begin Data;" );
204         w.write( ForesterUtil.LINE_SEPARATOR );
205         w.write( "   Dimensions NTax=" + getNumberOfSequences() );
206         w.write( " NChar=" + getLength() );
207         w.write( ";" );
208         w.write( ForesterUtil.LINE_SEPARATOR );
209         w.write( "   Format DataType=Protein Interleave=No gap=-;" );
210         w.write( ForesterUtil.LINE_SEPARATOR );
211         w.write( "   Matrix" );
212         w.write( ForesterUtil.LINE_SEPARATOR );
213         for( int row = 0; row < getNumberOfSequences(); ++row ) {
214             final MolecularSequence seq = getSequence( row );
215             final String s = seq.getMolecularSequenceAsString();
216             w.write( "      " );
217             w.write( ForesterUtil.pad( getIdentifier( row ).replace( ' ', '_' ), max, ' ', false ).toString() );
218             w.write( " " );
219             w.write( s );
220             w.write( ForesterUtil.LINE_SEPARATOR );
221         }
222         w.write( "   ;" );
223         w.write( ForesterUtil.LINE_SEPARATOR );
224         w.write( "End;" );
225         w.write( ForesterUtil.LINE_SEPARATOR );
226     }
227
228     private void writeToPhylip( final Writer w ) throws IOException {
229         final int max = determineMaxIdLength() + 1;
230         w.write( getNumberOfSequences() + " " + getLength() );
231         w.write( ForesterUtil.LINE_SEPARATOR );
232         for( int row = 0; row < getNumberOfSequences(); ++row ) {
233             w.write( ForesterUtil.pad( getIdentifier( row ).replace( ' ', '_' ), max, ' ', false ).toString() );
234             for( int col = 0; col < getLength(); ++col ) {
235                 w.write( getResidueAt( row, col ) );
236             }
237             w.write( ForesterUtil.LINE_SEPARATOR );
238         }
239     }
240
241     public static Msa createInstance( final List<MolecularSequence> seqs ) {
242         if ( seqs.size() < 1 ) {
243             throw new IllegalArgumentException( "cannot create msa from less than one sequence" );
244         }
245         final int length = seqs.get( 0 ).getLength();
246         final BasicMsa msa = new BasicMsa( seqs.size(), length, seqs.get( 0 ).getType() );
247         for( int row = 0; row < seqs.size(); ++row ) {
248             final MolecularSequence seq = seqs.get( row );
249             if ( seq.getLength() != length ) {
250                 throw new IllegalArgumentException( "illegal attempt to build msa from sequences of unequal length ["
251                         + seq.getIdentifier() + "]" );
252             }
253             if ( seq.getType() != msa.getType() ) {
254                 throw new IllegalArgumentException( "illegal attempt to build msa from sequences of different type ["
255                         + seq.getIdentifier() + "]" );
256             }
257             msa.setIdentifier( row, seq.getIdentifier() );
258             for( int col = 0; col < length; ++col ) {
259                 msa._data[ row ][ col ] = seq.getResidueAt( col );
260             }
261         }
262         return msa;
263     }
264 }