package jalview.analysis.scoremodels; import jalview.api.analysis.ScoreModelI; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Map; import java.util.TreeMap; /** * A class that can register and serve instances of ScoreModelI */ public class ScoreModels { private static ScoreModels instance = new ScoreModels(); private Map models; public static ScoreModels getInstance() { return instance; } /** * Private constructor to enforce use of singleton. Registers Jalview's * "built-in" score models: * */ private ScoreModels() { /* * using TreeMap keeps models ordered alphabetically by name */ models = new TreeMap(String.CASE_INSENSITIVE_ORDER); loadScoreMatrix("/scoreModel/blosum62.scm"); loadScoreMatrix("/scoreModel/pam250.scm"); loadScoreMatrix("/scoreModel/dna.scm"); registerScoreModel(new FeatureScoreModel()); registerScoreModel(new PIDScoreModel()); } /** * Try to load a score matrix from the given resource file, and if successful, * register it. Answers true if successful, else false. Any errors are * reported on syserr but not thrown. * * @param string */ boolean loadScoreMatrix(String resourcePath) { URL url = this.getClass().getResource(resourcePath); if (url == null) { System.err.println("Failed to locate " + resourcePath); return false; } boolean success = false; InputStream is = null; try { is = url.openStream(); ScoreMatrix sm = ScoreMatrix.parse(is); if (sm != null) { registerScoreModel(sm); success = true; } } catch (IOException e) { } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } return success; } /** * Answers an iterable set of the registered score models. Currently these are * ordered by name (not case sensitive). * * @return */ public Iterable getModels() { return models.values(); } public ScoreModelI forName(String s) { return models.get(s); } public void registerScoreModel(ScoreModelI sm) { ScoreModelI sm2 = models.get(sm.getName()); if (sm2 != null) { System.err.println("Warning: replacing score model " + sm2.getName()); } models.put(sm.getName(), sm); } }