JAL-3829 allow multiple URL mocks and include P01308 in 3d-beacons mocks
[jalview.git] / test / jalview / gui / structurechooser / StructureChooserQuerySourceTest.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.gui.structurechooser;
22
23
24 import static org.testng.Assert.assertEquals;
25 import static org.testng.Assert.assertTrue;
26
27 import java.util.Collection;
28 import java.util.List;
29 import java.util.Vector;
30
31 import org.junit.Assert;
32 import org.testng.AssertJUnit;
33 import org.testng.annotations.AfterMethod;
34 import org.testng.annotations.BeforeClass;
35 import org.testng.annotations.BeforeMethod;
36 import org.testng.annotations.DataProvider;
37 import org.testng.annotations.Test;
38
39 import jalview.datamodel.DBRefEntry;
40 import jalview.datamodel.DBRefSource;
41 import jalview.datamodel.PDBEntry;
42 import jalview.datamodel.Sequence;
43 import jalview.datamodel.SequenceI;
44 import jalview.fts.api.FTSData;
45 import jalview.fts.core.FTSRestRequest;
46 import jalview.fts.core.FTSRestResponse;
47 import jalview.fts.service.pdb.PDBFTSRestClient;
48 import jalview.fts.threedbeacons.TDBeaconsFTSRestClientTest;
49 import jalview.gui.JvOptionPane;
50 import jalview.gui.StructureChooser;
51 import jalview.jbgui.FilterOption;
52
53 public class StructureChooserQuerySourceTest
54 {
55
56   @BeforeClass(alwaysRun = true)
57   public void setUpJvOptionPane()
58   {
59     JvOptionPane.setInteractiveMode(false);
60     JvOptionPane.setMockResponse(JvOptionPane.CANCEL_OPTION);
61   }
62
63   Sequence seq,upSeq,upSeq_insulin;
64
65   // same set up as for structurechooser test
66   
67 @BeforeMethod(alwaysRun = true)
68   public void setUp() throws Exception
69   {
70     seq = new Sequence("PDB|4kqy|4KQY|A", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 1,
71             26);
72     seq.createDatasetSequence();
73     for (int x = 1; x < 5; x++)
74     {
75       DBRefEntry dbRef = new DBRefEntry();
76       dbRef.setAccessionId("XYZ_" + x);
77       seq.addDBRef(dbRef);
78     }
79
80     PDBEntry dbRef = new PDBEntry();
81     dbRef.setId("1tim");
82
83     Vector<PDBEntry> pdbIds = new Vector<>();
84     pdbIds.add(dbRef);
85
86     seq.setPDBId(pdbIds);
87     
88     // Uniprot sequence for 3D-Beacons mocks
89     upSeq = new Sequence("P38398", 
90             "MDLSALRVEEVQNVINAMQKILECPICLELIKEPVSTKCDHIFCKFCMLKLLNQKKGPSQCPLCKNDITKRS\n"
91             + "LQESTRFSQLVEELLKIICAFQLDTGLEYANSYNFAKKENNSPEHLKDEVSIIQSMGYRNRAKRLLQSEPEN\n"
92             + "PSLQETSLSVQLSNLGTVRTLRTKQRIQPQKTSVYIELGSDSSEDTVNKATYCSVGDQELLQITPQGTRDEI\n"
93             + "SLDSAKKAACEFSETDVTNTEHHQPSNNDLNTTEKRAAERHPEKYQGSSVSNLHVEPCGTNTHASSLQHENS\n"
94             + "SLLLTKDRMNVEKAEFCNKSKQPGLARSQHNRWAGSKETCNDRRTPSTEKKVDLNADPLCERKEWNKQKLPC\n"
95             + "SENPRDTEDVPWITLNSSIQKVNEWFSRSDELLGSDDSHDGESESNAKVADVLDVLNEVDEYSGSSEKIDLL\n"
96             + "ASDPHEALICKSERVHSKSVESNIEDKIFGKTYRKKASLPNLSHVTENLIIGAFVTEPQIIQERPLTNKLKR\n"
97             + "KRRPTSGLHPEDFIKKADLAVQKTPEMINQGTNQTEQNGQVMNITNSGHENKTKGDSIQNEKNPNPIESLEK\n"
98             + "ESAFKTKAEPISSSISNMELELNIHNSKAPKKNRLRRKSSTRHIHALELVVSRNLSPPNCTELQIDSCSSSE\n"
99             + "EIKKKKYNQMPVRHSRNLQLMEGKEPATGAKKSNKPNEQTSKRHDSDTFPELKLTNAPGSFTKCSNTSELKE\n"
100             + "FVNPSLPREEKEEKLETVKVSNNAEDPKDLMLSGERVLQTERSVESSSISLVPGTDYGTQESISLLEVSTLG\n"
101             + "KAKTEPNKCVSQCAAFENPKGLIHGCSKDNRNDTEGFKYPLGHEVNHSRETSIEMEESELDAQYLQNTFKVS\n"
102             + "KRQSFAPFSNPGNAEEECATFSAHSGSLKKQSPKVTFECEQKEENQGKNESNIKPVQTVNITAGFPVVGQKD\n"
103             + "KPVDNAKCSIKGGSRFCLSSQFRGNETGLITPNKHGLLQNPYRIPPLFPIKSFVKTKCKKNLLEENFEEHSM\n"
104             + "SPEREMGNENIPSTVSTISRNNIRENVFKEASSSNINEVGSSTNEVGSSINEIGSSDENIQAELGRNRGPKL\n"
105             + "NAMLRLGVLQPEVYKQSLPGSNCKHPEIKKQEYEEVVQTVNTDFSPYLISDNLEQPMGSSHASQVCSETPDD\n"
106             + "LLDDGEIKEDTSFAENDIKESSAVFSKSVQKGELSRSPSPFTHTHLAQGYRRGAKKLESSEENLSSEDEELP\n"
107             + "CFQHLLFGKVNNIPSQSTRHSTVATECLSKNTEENLLSLKNSLNDCSNQVILAKASQEHHLSEETKCSASLF\n"
108             + "SSQCSELEDLTANTNTQDPFLIGSSKQMRHQSESQGVGLSDKELVSDDEERGTGLEENNQEEQSMDSNLGEA\n"
109             + "ASGCESETSVSEDCSGLSSQSDILTTQQRDTMQHNLIKLQQEMAELEAVLEQHGSQPSNSYPSIISDSSALE\n"
110             + "DLRNPEQSTSEKAVLTSQKSSEYPISQNPEGLSADKFEVSADSSTSKNKEPGVERSSPSKCPSLDDRWYMHS\n"
111             + "CSGSLQNRNYPSQEELIKVVDVEEQQLEESGPHDLTETSYLPRQDLEGTPYLESGISLFSDDPESDPSEDRA\n"
112             + "PESARVGNIPSSTSALKVPQLKVAESAQSPAAAHTTDTAGYNAMEESVSREKPELTASTERVNKRMSMVVSG\n"
113             + "LTPEEFMLVYKFARKHHITLTNLITEETTHVVMKTDAEFVCERTLKYFLGIAGGKWVVSYFWVTQSIKERKM\n"
114             + "LNEHDFEVRGDVVNGRNHQGPKRARESQDRKIFRGLEICCYGPFTNMPTDQLEWMVQLCGASVVKELSSFTL\n"
115             + "GTGVHPIVVVQPDAWTEDNGFHAIGQMCEAPVVTREWVLDSVALYQCQELDTYLIPQIPHSHY\n"
116             + "", 1,
117 1863);
118     upSeq.createDatasetSequence();
119     upSeq.setDescription("Breast cancer type 1 susceptibility protein");
120     upSeq.addDBRef(new DBRefEntry("UNIPROT","0","P38398",null,true));
121     
122     upSeq_insulin=new Sequence("INS_HUMAN",
123             "MALWMRLLPLLALLALWGPDPAAAFVNQHLCGSHLVEALYLVCGERGFFYTPKTRREAEDLQVGQVELGGGP"
124             + "GAGSLQPLALEGSLQKRGIVEQCCTSICSLYQLENYCN");
125     upSeq_insulin.createDatasetSequence();
126     upSeq_insulin.setDescription("Insulin");
127     upSeq_insulin.addDBRef(new DBRefEntry("UNIPROT","0","P01308",null,true));
128   }
129
130 @AfterMethod(alwaysRun = true)
131   public void tearDown() throws Exception
132   {
133     seq = null;
134     upSeq=null;
135   }
136
137   @SuppressWarnings("deprecation")
138   @Test(groups = { "Functional" })
139   public void buildPDBQueryTest()
140   {
141     System.out.println("seq >>>> " + seq);
142     
143     StructureChooserQuerySource scquery = StructureChooserQuerySource.getQuerySourceFor(new SequenceI[] { seq});
144     AssertJUnit.assertTrue(scquery instanceof PDBStructureChooserQuerySource);
145     String query = scquery.buildQuery(seq);
146     AssertJUnit.assertEquals("pdb_id:1tim", query);
147     seq.getAllPDBEntries().clear();
148     query = scquery.buildQuery(seq);
149     AssertJUnit.assertEquals(
150             "text:XYZ_1 OR text:XYZ_2 OR text:XYZ_3 OR text:XYZ_4 OR text:4kqy",
151             query);
152     seq.setDBRefs(null);
153     query = scquery.buildQuery(seq);
154     System.out.println(query);
155     AssertJUnit.assertEquals("text:4kqy", query);
156
157     DBRefEntry uniprotDBRef = new DBRefEntry();
158     uniprotDBRef.setAccessionId("P12345");
159     uniprotDBRef.setSource(DBRefSource.UNIPROT);
160     seq.addDBRef(uniprotDBRef);
161
162     DBRefEntry pdbDBRef = new DBRefEntry();
163     pdbDBRef.setAccessionId("1XYZ");
164     pdbDBRef.setSource(DBRefSource.PDB);
165     seq.addDBRef(pdbDBRef);
166
167     for (int x = 1; x < 5; x++)
168     {
169       DBRefEntry dbRef = new DBRefEntry();
170       dbRef.setAccessionId("XYZ_" + x);
171       seq.addDBRef(dbRef);
172     }
173     System.out.println("");
174     System.out.println(seq.getDBRefs());
175     System.out.println(query);
176     query = scquery.buildQuery(seq);
177     AssertJUnit.assertEquals(
178             "uniprot_accession:P12345 OR uniprot_id:P12345 OR pdb_id:1xyz",
179             query);
180   }
181
182   @SuppressWarnings("deprecation")
183   @Test(groups = { "Functional" })
184   public void buildThreeDBQueryTest()
185   {
186     System.out.println("seq >>>> " + upSeq);
187     TDBeaconsFTSRestClientTest.setMock();
188     PDBFTSRestClient.setMock();
189     StructureChooserQuerySource scquery = StructureChooserQuerySource.getQuerySourceFor(new SequenceI[] { upSeq});
190     // gets the lightweight proxy rather than the ThreeDBStructureChooserQuerySource
191     AssertJUnit.assertTrue(scquery instanceof ThreeDBStructureChooserQuerySource);
192     String query = scquery.buildQuery(upSeq);
193     AssertJUnit.assertEquals("P38398", query);
194     
195     // query shouldn't change regardless of additional entries
196     // because 3DBeacons requires canonical entries.
197     upSeq.getAllPDBEntries().clear();
198     query = scquery.buildQuery(upSeq);
199     AssertJUnit.assertEquals("P38398", query);
200     upSeq.setDBRefs(null);
201     query = scquery.buildQuery(upSeq);
202     /*
203      * legacy projects/datasets will not have canonical flags set for uniprot dbrefs
204      * graceful behaviour would be to
205      *  - pick one ? not possible
206      *  - iterate through all until a 200 is obtained ?
207      *  ---> ideal but could be costly
208      *  ---> better to do a direct retrieval from uniprot to work out which is the canonical identifier..
209      *  ----> need a test to check that accessions can be promoted to canonical!
210      */
211     //FIXME - need to be able to use ID to query here ?
212     AssertJUnit.assertEquals(null, query);
213
214     
215     
216     // TODO: 
217     /**
218      * set of sequences:
219      * - no protein -> TDB not applicable, query PDBe only (consider RNA or DNA - specific query adapter ?)
220      * - protein but no uniprot -> first consider trying to get uniprot refs (need a mark to say none are available)
221      * - protein and uniprot - no canonicals -> resolve to uniprot automatically to get canonicals
222      * - query uniprot against 3DBeacons
223      * --> decorate experimental structures with additional data from PDBe
224      * - query remaining against PDBe
225      * Ranking
226      * - 3D Beacons
227      *  --> in memory ranking - no need to query twice
228      *  Rank by
229      *  - experimental > AlphaFold -> Model
230      *  - start > end
231      *  -> filters for 
232      *  -> experimental only
233      *  -> experimental plus best models for other regions
234      *  -> "best cover" 
235      *  -> need to be able to select correct reference (the longest one that covers all) for superposition
236      */
237 //    
238 //    DBRefEntry uniprotDBRef = new DBRefEntry();
239 //    uniprotDBRef.setAccessionId("P12345");
240 //    uniprotDBRef.setSource(DBRefSource.UNIPROT);
241 //    upSeq.addDBRef(uniprotDBRef);
242 //
243 //    DBRefEntry pdbDBRef = new DBRefEntry();
244 //    pdbDBRef.setAccessionId("1XYZ");
245 //    pdbDBRef.setSource(DBRefSource.PDB);
246 //    upSeq.addDBRef(pdbDBRef);
247 //
248 //    for (int x = 1; x < 5; x++)
249 //    {
250 //      DBRefEntry dbRef = new DBRefEntry();
251 //      dbRef.setAccessionId("XYZ_" + x);
252 //      seq.addDBRef(dbRef);
253 //    }
254 //    System.out.println("");
255 //    System.out.println(seq.getDBRefs());
256 //    System.out.println(query);
257 //    query = scquery.buildQuery(seq);
258 //    assertEquals(
259 //            "uniprot_accession:P12345 OR uniprot_id:P12345 OR pdb_id:1xyz",
260 //            query);
261   }
262   @Test(groups= {"Functional"},dataProvider = "testUpSeqs")
263   public void cascadingThreeDBandPDBQuerys(SequenceI testUpSeq)
264   {
265     TDBeaconsFTSRestClientTest.setMock();
266     PDBFTSRestClient.setMock();
267     ThreeDBStructureChooserQuerySource tdbquery = new ThreeDBStructureChooserQuerySource();
268     PDBStructureChooserQuerySource pdbquery  = new PDBStructureChooserQuerySource();
269             
270
271     
272     FTSRestResponse upResponse = null;
273     FTSRestResponse pdbResponse = null;
274     // TODO test available options
275     // Best coverage
276     // Best Alphafold Model
277     // Best model (by confidence score)
278     // Will also need to develop a more sophisticated filtering system
279     List<FilterOption> opts = tdbquery.getAvailableFilterOptions(StructureChooser.VIEWS_FILTER);
280     FilterOption opt_singlebest = opts.get(0);
281     FilterOption opt_manybest = opts.get(1);
282     assertEquals(opt_singlebest.getValue(), ThreeDBStructureChooserQuerySource.FILTER_FIRST_BEST_COVERAGE);
283     assertEquals(opt_manybest.getValue(), ThreeDBStructureChooserQuerySource.FILTER_TDBEACONS_COVERAGE);
284     
285     try {
286       upResponse = tdbquery.fetchStructuresMetaData(testUpSeq, tdbquery.getDocFieldPrefs().getStructureSummaryFields(),  opt_singlebest, false);
287       tdbquery.updateAvailableFilterOptions(StructureChooser.VIEWS_FILTER,opts,upResponse.getSearchSummary());
288       // test ranking without additional PDBe data
289       FTSRestResponse firstRanked = tdbquery.selectFirstRankedQuery(testUpSeq, upResponse.getSearchSummary(), tdbquery.getDocFieldPrefs().getStructureSummaryFields(), opt_singlebest.getValue(), false);
290       assertEquals(firstRanked.getNumberOfItemsFound(),1);
291       // many best response
292       upResponse = tdbquery.fetchStructuresMetaData(testUpSeq, tdbquery.getDocFieldPrefs().getStructureSummaryFields(),  opt_manybest, false);
293       assertTrue(firstRanked.getSearchSummary().size()<upResponse.getSearchSummary().size());
294       // NB Could have race condition here 
295       String pdb_Query = tdbquery.buildPDBFTSQueryFor(upResponse);
296       assertTrue(pdb_Query.trim().length()>0);
297       pdbResponse = tdbquery.fetchStructuresMetaDataFor(pdbquery, upResponse);
298       assertTrue(pdbResponse.getNumberOfItemsFound()>0);
299       FTSRestResponse joinedResp = tdbquery.joinResponses(upResponse, pdbResponse);
300       assertEquals(upResponse.getNumberOfItemsFound(),joinedResp.getNumberOfItemsFound());
301       
302       
303     } catch (Exception x)
304     {
305       x.printStackTrace();
306       Assert.fail("Unexpected Exception");
307     }
308     StructureChooserQuerySource scquery = StructureChooserQuerySource.getQuerySourceFor(new SequenceI[] { testUpSeq});
309
310   }
311   
312   @DataProvider(name = "testUpSeqs")
313   public Object[][] testUpSeqs() throws Exception
314   {
315     setUp();
316     return new Object[][] { {upSeq},{upSeq_insulin}};
317   }
318   
319   @Test(groups = { "Functional" })
320   public void sanitizeSeqNameTest()
321   {
322     String name = "ab_cdEF|fwxyz012349";
323     AssertJUnit.assertEquals(name, PDBStructureChooserQuerySource.sanitizeSeqName(name));
324
325     // remove a [nn] substring
326     name = "abcde12[345]fg";
327     AssertJUnit.assertEquals("abcde12fg", PDBStructureChooserQuerySource.sanitizeSeqName(name));
328
329     // remove characters other than a-zA-Z0-9 | or _
330     name = "ab[cd],.\t£$*!- \\\"@:e";
331     AssertJUnit.assertEquals("abcde", PDBStructureChooserQuerySource.sanitizeSeqName(name));
332
333     name = "abcde12[345a]fg";
334     AssertJUnit.assertEquals("abcde12345afg", PDBStructureChooserQuerySource.sanitizeSeqName(name));
335   }
336 }