Parsing moved to (new) ScoreMatrixFile, drag and drop to alignment now
[jalview.git] / src / jalview / analysis / scoremodels / ScoreModels.java
1 package jalview.analysis.scoremodels;
2
3 import jalview.api.analysis.ScoreModelI;
4 import jalview.io.DataSourceType;
5 import jalview.io.FileParse;
6 import jalview.io.ScoreMatrixFile;
7
8 import java.io.IOException;
9 import java.util.Map;
10 import java.util.TreeMap;
11
12 /**
13  * A class that can register and serve instances of ScoreModelI
14  */
15 public class ScoreModels
16 {
17   private static ScoreModels instance = new ScoreModels();
18
19   private Map<String, ScoreModelI> models;
20
21   public static ScoreModels getInstance()
22   {
23     return instance;
24   }
25
26   /**
27    * Private constructor to enforce use of singleton. Registers Jalview's
28    * "built-in" score models:
29    * <ul>
30    * <li>BLOSUM62</li>
31    * <li>PAM250</li>
32    * <li>DNA</li>
33    * <li>Sequence Feature Similarity</li>
34    * <li>Percentage Identity</li>
35    * </ul>
36    */
37   private ScoreModels()
38   {
39     /*
40      * using TreeMap keeps models ordered alphabetically by name
41      */
42     models = new TreeMap<String, ScoreModelI>(String.CASE_INSENSITIVE_ORDER);
43     loadScoreMatrix("scoreModel/blosum62.scm");
44     loadScoreMatrix("scoreModel/pam250.scm");
45     loadScoreMatrix("scoreModel/dna.scm");
46     registerScoreModel(new FeatureScoreModel());
47     registerScoreModel(new PIDScoreModel());
48   }
49
50   /**
51    * Try to load a score matrix from the given resource file, and if successful,
52    * register it. Answers true if successful, else false.
53    * 
54    * @param string
55    */
56   boolean loadScoreMatrix(String resourcePath)
57   {
58     try
59     {
60       /*
61        * delegate parsing to ScoreMatrixFile
62        */
63       FileParse fp = new FileParse(resourcePath, DataSourceType.CLASSLOADER);
64       ScoreMatrix sm = new ScoreMatrixFile(fp).parseMatrix();
65       registerScoreModel(sm);
66       return true;
67     } catch (IOException e)
68     {
69       System.err.println("Error reading " + resourcePath + ": "
70               + e.getMessage());
71     }
72     return false;
73   }
74
75   /**
76    * Answers an iterable set of the registered score models. Currently these are
77    * ordered by name (not case sensitive).
78    * 
79    * @return
80    */
81   public Iterable<ScoreModelI> getModels()
82   {
83     return models.values();
84   }
85
86   public ScoreModelI forName(String s)
87   {
88     return models.get(s);
89   }
90
91   public void registerScoreModel(ScoreModelI sm)
92   {
93     ScoreModelI sm2 = models.get(sm.getName());
94     if (sm2 != null)
95     {
96       System.err.println("Warning: replacing score model " + sm2.getName());
97     }
98     models.put(sm.getName(), sm);
99   }
100 }