2 // forester -- software libraries and applications
3 // for genomics and evolutionary biology research.
5 // Copyright (C) 2010 Christian M Zmasek
6 // Copyright (C) 2010 Sanford-Burnham Medical Research Institute
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.
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.
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
23 // Contact: phylosoft @ gmail . com
24 // WWW: https://sites.google.com/site/cmzmasek/home/software/forester
26 package org.forester.ws.seqdb;
28 import java.io.BufferedReader;
29 import java.io.IOException;
30 import java.io.InputStreamReader;
31 import java.io.UnsupportedEncodingException;
33 import java.net.URLConnection;
34 import java.net.URLEncoder;
35 import java.util.ArrayList;
36 import java.util.List;
37 import java.util.SortedSet;
38 import java.util.TreeSet;
40 import org.forester.phylogeny.Phylogeny;
41 import org.forester.phylogeny.PhylogenyNode;
42 import org.forester.phylogeny.data.Accession;
43 import org.forester.phylogeny.data.Identifier;
44 import org.forester.phylogeny.data.Sequence;
45 import org.forester.phylogeny.data.Taxonomy;
46 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
47 import org.forester.util.ForesterUtil;
48 import org.forester.util.SequenceIdParser;
50 public final class SequenceDbWsTools {
52 public final static String BASE_UNIPROT_URL = "http://www.uniprot.org/";
53 public final static String BASE_EMBL_DB_URL = "http://www.ebi.ac.uk/Tools/dbfetch/dbfetch/";
54 public final static String EMBL_DBS_EMBL = "embl";
55 public final static String EMBL_DBS_REFSEQ_P = "refseqp";
56 public final static String EMBL_DBS_REFSEQ_N = "refseqn";
57 private final static String URL_ENC = "UTF-8";
58 private final static boolean DEBUG = false;
60 private static List<UniProtTaxonomy> getTaxonomiesFromCommonName( final String cn, final int max_taxonomies_return )
62 final List<String> result = getTaxonomyStringFromCommonName( cn, max_taxonomies_return );
63 if ( result.size() > 0 ) {
64 return parseUniProtTaxonomy( result );
69 public static List<UniProtTaxonomy> getTaxonomiesFromCommonNameStrict( final String cn,
70 final int max_taxonomies_return )
72 final List<UniProtTaxonomy> taxonomies = getTaxonomiesFromCommonName( cn, max_taxonomies_return );
73 if ( ( taxonomies != null ) && ( taxonomies.size() > 0 ) ) {
74 final List<UniProtTaxonomy> filtered_taxonomies = new ArrayList<UniProtTaxonomy>();
75 for( final UniProtTaxonomy taxonomy : taxonomies ) {
76 if ( taxonomy.getCommonName().equalsIgnoreCase( cn ) ) {
77 filtered_taxonomies.add( taxonomy );
80 return filtered_taxonomies;
85 public static List<UniProtTaxonomy> getTaxonomiesFromId( final String id, final int max_taxonomies_return )
87 final List<String> result = getTaxonomyStringFromId( id, max_taxonomies_return );
88 if ( result.size() > 0 ) {
89 return parseUniProtTaxonomy( result );
94 private static List<UniProtTaxonomy> getTaxonomiesFromScientificName( final String sn,
95 final int max_taxonomies_return )
97 final List<String> result = getTaxonomyStringFromScientificName( sn, max_taxonomies_return );
98 if ( result.size() > 0 ) {
99 return parseUniProtTaxonomy( result );
105 * Does not return "sub-types".
106 * For example, for "Mus musculus" only returns "Mus musculus"
107 * and not "Mus musculus", "Mus musculus bactrianus", ...
110 public static List<UniProtTaxonomy> getTaxonomiesFromScientificNameStrict( final String sn,
111 final int max_taxonomies_return )
113 final List<UniProtTaxonomy> taxonomies = getTaxonomiesFromScientificName( sn, max_taxonomies_return );
114 if ( ( taxonomies != null ) && ( taxonomies.size() > 0 ) ) {
115 final List<UniProtTaxonomy> filtered_taxonomies = new ArrayList<UniProtTaxonomy>();
116 for( final UniProtTaxonomy taxonomy : taxonomies ) {
117 if ( taxonomy.getScientificName().equalsIgnoreCase( sn ) ) {
118 filtered_taxonomies.add( taxonomy );
121 return filtered_taxonomies;
126 public static List<UniProtTaxonomy> getTaxonomiesFromTaxonomyCode( final String code,
127 final int max_taxonomies_return )
129 final String my_code = new String( code );
130 final List<String> result = getTaxonomyStringFromTaxonomyCode( my_code, max_taxonomies_return );
131 if ( result.size() > 0 ) {
132 return parseUniProtTaxonomy( result );
137 public static SequenceDatabaseEntry obtainEmblEntry( final Identifier id, final int max_lines_to_return )
139 final List<String> lines = queryEmblDb( id, max_lines_to_return );
140 return EbiDbEntry.createInstanceFromPlainText( lines );
143 public static SequenceDatabaseEntry obtainRefSeqEntryFromEmbl( final Identifier id, final int max_lines_to_return )
145 final List<String> lines = queryEmblDb( id, max_lines_to_return );
146 return EbiDbEntry.createInstanceFromPlainTextForRefSeq( lines );
149 public static SortedSet<String> obtainSeqInformation( final Phylogeny phy,
150 final boolean ext_nodes_only,
151 final boolean allow_to_set_taxonomic_data,
152 final int lines_to_return ) throws IOException {
153 final SortedSet<String> not_found = new TreeSet<String>();
154 for( final PhylogenyNodeIterator iter = phy.iteratorPostorder(); iter.hasNext(); ) {
155 final PhylogenyNode node = iter.next();
156 if ( ext_nodes_only && node.isInternal() ) {
160 Identifier id = null;
162 if ( node.getNodeData().isHasSequence() && ( node.getNodeData().getSequence().getAccession() != null )
163 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getAccession().getSource() )
164 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getAccession().getValue() )
165 && node.getNodeData().getSequence().getAccession().getValue().toLowerCase().startsWith( "uniprot" ) ) {
166 query = node.getNodeData().getSequence().getAccession().getValue();
169 else if ( node.getNodeData().isHasSequence()
170 && ( node.getNodeData().getSequence().getAccession() != null )
171 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getAccession().getSource() )
172 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getAccession().getValue() )
173 && ( node.getNodeData().getSequence().getAccession().getValue().toLowerCase().startsWith( "embl" ) || node
174 .getNodeData().getSequence().getAccession().getValue().toLowerCase().startsWith( "ebi" ) ) ) {
175 query = node.getNodeData().getSequence().getAccession().getValue();
178 else if ( !ForesterUtil.isEmpty( node.getName() ) ) {
179 if ( ( query = ForesterUtil.extractUniProtKbProteinSeqIdentifier( node ) ) != null ) {
182 else if ( ( id = SequenceIdParser.parse( node.getName() ) ) != null ) {
183 if ( id.getProvider().equalsIgnoreCase( Identifier.NCBI ) ) {
186 else if ( id.getProvider().equalsIgnoreCase( Identifier.REFSEQ ) ) {
191 if ( db == Db.NONE ) {
192 not_found.add( node.getName() );
194 SequenceDatabaseEntry db_entry = null;
195 if ( !ForesterUtil.isEmpty( query ) ) {
196 if ( db == Db.UNIPROT ) {
198 System.out.println( "uniprot: " + query );
200 db_entry = obtainUniProtEntry( query, lines_to_return );
202 if ( ( db == Db.EMBL ) || ( ( db == Db.UNIPROT ) && ( db_entry == null ) ) ) {
204 System.out.println( "embl: " + query );
206 db_entry = obtainEmblEntry( new Identifier( query ), lines_to_return );
207 if ( ( db == Db.UNIPROT ) && ( db_entry != null ) ) {
212 else if ( ( db == Db.REFSEQ ) && ( id != null ) ) {
213 db_entry = obtainRefSeqEntryFromEmbl( id, lines_to_return );
215 else if ( ( db == Db.NCBI ) && ( id != null ) ) {
216 db_entry = obtainEmblEntry( id, lines_to_return ); //TODO ?
218 if ( ( db_entry != null ) && !db_entry.isEmpty() ) {
219 final Sequence seq = node.getNodeData().isHasSequence() ? node.getNodeData().getSequence()
221 if ( !ForesterUtil.isEmpty( db_entry.getAccession() ) ) {
223 if ( db == Db.EMBL ) {
226 else if ( db == Db.UNIPROT ) {
229 else if ( db == Db.NCBI ) {
232 else if ( db == Db.REFSEQ ) {
235 seq.setAccession( new Accession( db_entry.getAccession(), type ) );
237 if ( !ForesterUtil.isEmpty( db_entry.getSequenceName() ) ) {
238 seq.setName( db_entry.getSequenceName() );
240 if ( !ForesterUtil.isEmpty( db_entry.getSequenceSymbol() ) ) {
241 seq.setSymbol( db_entry.getSequenceSymbol() );
243 final Taxonomy tax = node.getNodeData().isHasTaxonomy() ? node.getNodeData().getTaxonomy()
245 if ( !ForesterUtil.isEmpty( db_entry.getTaxonomyScientificName() ) ) {
246 tax.setScientificName( db_entry.getTaxonomyScientificName() );
248 if ( allow_to_set_taxonomic_data && !ForesterUtil.isEmpty( db_entry.getTaxonomyIdentifier() ) ) {
249 tax.setIdentifier( new Identifier( db_entry.getTaxonomyIdentifier(), "uniprot" ) );
251 node.getNodeData().setTaxonomy( tax );
252 node.getNodeData().setSequence( seq );
254 else if ( db != Db.NONE ) {
255 not_found.add( node.getName() );
258 Thread.sleep( 10 );// Sleep for 10 ms
260 catch ( final InterruptedException ie ) {
266 public static SequenceDatabaseEntry obtainUniProtEntry( final String query, final int max_lines_to_return )
268 final List<String> lines = queryUniprot( "uniprot/" + query + ".txt", max_lines_to_return );
269 return UniProtEntry.createInstanceFromPlainText( lines );
272 public static List<String> queryDb( final String query, int max_lines_to_return, final String base_url )
274 if ( ForesterUtil.isEmpty( query ) ) {
275 throw new IllegalArgumentException( "illegal attempt to use empty query " );
277 if ( max_lines_to_return < 1 ) {
278 max_lines_to_return = 1;
280 final URL url = new URL( base_url + query );
282 System.out.println( "url: " + url.toString() );
284 final URLConnection urlc = url.openConnection();
285 final BufferedReader in = new BufferedReader( new InputStreamReader( urlc.getInputStream() ) );
287 final List<String> result = new ArrayList<String>();
288 while ( ( line = in.readLine() ) != null ) {
290 System.out.println( line );
293 if ( result.size() > max_lines_to_return ) {
299 // To prevent accessing online dbs in too quick succession.
302 catch ( final InterruptedException e ) {
308 public static List<String> queryEmblDb( final Identifier id, final int max_lines_to_return ) throws IOException {
309 final StringBuilder url_sb = new StringBuilder();
310 url_sb.append( BASE_EMBL_DB_URL );
311 if ( ForesterUtil.isEmpty( id.getProvider() ) || id.getProvider().equalsIgnoreCase( Identifier.NCBI ) ) {
312 url_sb.append( SequenceDbWsTools.EMBL_DBS_EMBL );
313 url_sb.append( '/' );
315 else if ( id.getProvider().equalsIgnoreCase( Identifier.REFSEQ ) ) {
316 if ( id.getValue().toUpperCase().indexOf( 'P' ) == 1 ) {
317 url_sb.append( SequenceDbWsTools.EMBL_DBS_REFSEQ_P );
318 url_sb.append( '/' );
321 url_sb.append( SequenceDbWsTools.EMBL_DBS_REFSEQ_N );
322 url_sb.append( '/' );
325 return queryDb( id.getValue(), max_lines_to_return, url_sb.toString() );
328 public static List<String> queryUniprot( final String query, final int max_lines_to_return ) throws IOException {
329 return queryDb( query, max_lines_to_return, BASE_UNIPROT_URL );
332 private static String encode( final String str ) throws UnsupportedEncodingException {
333 return URLEncoder.encode( str.trim(), URL_ENC );
336 private static List<String> getTaxonomyStringFromCommonName( final String cn, final int max_lines_to_return )
338 return queryUniprot( "taxonomy/?query=common%3a%22" + encode( cn ) + "%22&format=tab", max_lines_to_return );
341 private static List<String> getTaxonomyStringFromId( final String id, final int max_lines_to_return )
343 return queryUniprot( "taxonomy/?query=id%3a%22" + encode( id ) + "%22&format=tab", max_lines_to_return );
346 private static List<String> getTaxonomyStringFromScientificName( final String sn, final int max_lines_to_return )
348 return queryUniprot( "taxonomy/?query=scientific%3a%22" + encode( sn ) + "%22&format=tab", max_lines_to_return );
351 private static List<String> getTaxonomyStringFromTaxonomyCode( final String code, final int max_lines_to_return )
353 return queryUniprot( "taxonomy/?query=mnemonic%3a%22" + encode( code ) + "%22&format=tab", max_lines_to_return );
356 private static List<UniProtTaxonomy> parseUniProtTaxonomy( final List<String> result ) throws IOException {
357 final List<UniProtTaxonomy> taxonomies = new ArrayList<UniProtTaxonomy>();
358 for( final String line : result ) {
359 if ( ForesterUtil.isEmpty( line ) ) {
360 // Ignore empty lines.
362 else if ( line.startsWith( "Taxon" ) ) {
363 final String[] items = line.split( "\t" );
364 if ( !( items[ 1 ].equalsIgnoreCase( "Mnemonic" ) && items[ 2 ].equalsIgnoreCase( "Scientific name" )
365 && items[ 3 ].equalsIgnoreCase( "Common name" ) && items[ 4 ].equalsIgnoreCase( "Synonym" )
366 && items[ 5 ].equalsIgnoreCase( "Other Names" ) && items[ 6 ].equalsIgnoreCase( "Reviewed" )
367 && items[ 7 ].equalsIgnoreCase( "Rank" ) && items[ 8 ].equalsIgnoreCase( "Lineage" ) ) ) {
368 throw new IOException( "Unreconized UniProt Taxonomy format: " + line );
372 if ( line.split( "\t" ).length > 4 ) {
373 taxonomies.add( new UniProtTaxonomy( line ) );
381 UNIPROT, EMBL, NCBI, NONE, REFSEQ;