JAL-2136 JAL-2137 Modified STRUCTMODEL annotation format and added implementation...
[jalview.git] / src / jalview / gui / StructureChooser.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
22 package jalview.gui;
23
24 import jalview.bin.Jalview;
25 import jalview.datamodel.DBRefEntry;
26 import jalview.datamodel.DBRefSource;
27 import jalview.datamodel.PDBEntry;
28 import jalview.datamodel.SequenceI;
29 import jalview.fts.api.FTSData;
30 import jalview.fts.api.FTSDataColumnI;
31 import jalview.fts.api.FTSRestClientI;
32 import jalview.fts.core.FTSRestRequest;
33 import jalview.fts.core.FTSRestResponse;
34 import jalview.fts.service.pdb.PDBFTSRestClient;
35 import jalview.io.DataSourceType;
36 import jalview.jbgui.GStructureChooser;
37 import jalview.structure.StructureMapping;
38 import jalview.structure.StructureSelectionManager;
39 import jalview.util.MessageManager;
40 import jalview.ws.DBRefFetcher;
41 import jalview.ws.phyre2.Phyre2Client;
42 import jalview.ws.phyre2.Phyre2SummaryPojo;
43 import jalview.ws.sifts.SiftsSettings;
44
45 import java.awt.event.ItemEvent;
46 import java.util.ArrayList;
47 import java.util.Collection;
48 import java.util.HashSet;
49 import java.util.LinkedHashSet;
50 import java.util.List;
51 import java.util.Objects;
52 import java.util.Set;
53 import java.util.Vector;
54
55 import javax.swing.JCheckBox;
56 import javax.swing.JComboBox;
57 import javax.swing.JLabel;
58 import javax.swing.table.AbstractTableModel;
59
60 /**
61  * Provides the behaviors for the Structure chooser Panel
62  * 
63  * @author tcnofoegbu
64  *
65  */
66 @SuppressWarnings("serial")
67 public class StructureChooser extends GStructureChooser implements
68         IProgressIndicator
69 {
70   private static int MAX_QLENGTH = 7820;
71
72   private SequenceI selectedSequence;
73
74   private SequenceI[] selectedSequences;
75
76   private IProgressIndicator progressIndicator;
77
78   private Collection<FTSData> discoveredStructuresSet;
79
80   private FTSRestRequest lastPdbRequest;
81
82   private FTSRestClientI pdbRestCleint;
83
84   private String selectedStructureFileName;
85
86   private boolean isValidPBDEntry;
87
88   private boolean cachedPDBExists;
89
90   public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
91           AlignmentPanel ap)
92   {
93     this.ap = ap;
94     this.selectedSequence = selectedSeq;
95     this.selectedSequences = selectedSeqs;
96     this.progressIndicator = (ap == null) ? null : ap.alignFrame;
97     init();
98   }
99
100   /**
101    * Initializes parameters used by the Structure Chooser Panel
102    */
103   public void init()
104   {
105     if (!Jalview.isHeadlessMode())
106     {
107       progressBar = new ProgressBar(this.statusPanel, this.statusBar);
108     }
109
110     // ensure a filter option is in force for search
111     populateFilterComboBox(true, cachedPDBExists);
112     Thread discoverPDBStructuresThread = new Thread(new Runnable()
113     {
114       @Override
115       public void run()
116       {
117         long startTime = System.currentTimeMillis();
118         updateProgressIndicator(MessageManager
119                 .getString("status.loading_cached_pdb_entries"), startTime);
120         loadLocalCachedPDBEntries();
121         updateProgressIndicator(null, startTime);
122         updateProgressIndicator(MessageManager
123                 .getString("status.searching_for_pdb_structures"),
124                 startTime);
125         fetchStructuresMetaData();
126         // revise filter options if no results were found
127         populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
128         updateProgressIndicator(null, startTime);
129         mainFrame.setVisible(true);
130         updateCurrentView();
131       }
132     });
133     discoverPDBStructuresThread.start();
134   }
135
136   /**
137    * Updates the progress indicator with the specified message
138    * 
139    * @param message
140    *          displayed message for the operation
141    * @param id
142    *          unique handle for this indicator
143    */
144   public void updateProgressIndicator(String message, long id)
145   {
146     if (progressIndicator != null)
147     {
148       progressIndicator.setProgressBar(message, id);
149     }
150   }
151
152   /**
153    * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
154    * selection group
155    */
156   public void fetchStructuresMetaData()
157   {
158     long startTime = System.currentTimeMillis();
159     pdbRestCleint = PDBFTSRestClient.getInstance();
160     Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
161             .getStructureSummaryFields();
162
163     discoveredStructuresSet = new LinkedHashSet<FTSData>();
164     HashSet<String> errors = new HashSet<String>();
165     for (SequenceI seq : selectedSequences)
166     {
167       FTSRestRequest pdbRequest = new FTSRestRequest();
168       pdbRequest.setAllowEmptySeq(false);
169       pdbRequest.setResponseSize(500);
170       pdbRequest.setFieldToSearchBy("(");
171       FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
172               .getSelectedItem());
173       pdbRequest.setFieldToSortBy(selectedFilterOpt.getValue(),
174               !chk_invertFilter.isSelected());
175       pdbRequest.setWantedFields(wantedFields);
176       pdbRequest.setSearchTerm(buildQuery(seq) + ")");
177       pdbRequest.setAssociatedSequence(seq);
178       FTSRestResponse resultList;
179       try
180       {
181         resultList = pdbRestCleint.executeRequest(pdbRequest);
182       } catch (Exception e)
183       {
184         e.printStackTrace();
185         errors.add(e.getMessage());
186         continue;
187       }
188       lastPdbRequest = pdbRequest;
189       if (resultList.getSearchSummary() != null
190               && !resultList.getSearchSummary().isEmpty())
191       {
192         discoveredStructuresSet.addAll(resultList.getSearchSummary());
193       }
194     }
195
196     int noOfStructuresFound = 0;
197     String totalTime = (System.currentTimeMillis() - startTime)
198             + " milli secs";
199     if (discoveredStructuresSet != null
200             && !discoveredStructuresSet.isEmpty())
201     {
202       getResultTable().setModel(
203               JvSummaryTable.getTableModel(lastPdbRequest,
204                       discoveredStructuresSet));
205       noOfStructuresFound = discoveredStructuresSet.size();
206       mainFrame.setTitle(MessageManager.formatMessage(
207               "label.structure_chooser_no_of_structures",
208               noOfStructuresFound, totalTime));
209     }
210     else
211     {
212       mainFrame.setTitle(MessageManager
213               .getString("label.structure_chooser_manual_association"));
214       if (errors.size() > 0)
215       {
216         StringBuilder errorMsg = new StringBuilder();
217         for (String error : errors)
218         {
219           errorMsg.append(error).append("\n");
220         }
221         JvOptionPane.showMessageDialog(this, errorMsg.toString(),
222                 MessageManager.getString("label.pdb_web-service_error"),
223                 JvOptionPane.ERROR_MESSAGE);
224       }
225     }
226   }
227
228   public void loadLocalCachedPDBEntries()
229   {
230     ArrayList<CachedPDB> entries = new ArrayList<CachedPDB>();
231     for (SequenceI seq : selectedSequences)
232     {
233       if (seq.getDatasetSequence() != null
234               && seq.getDatasetSequence().getAllPDBEntries() != null)
235       {
236         for (PDBEntry pdbEntry : seq.getDatasetSequence()
237                 .getAllPDBEntries())
238         {
239           if (pdbEntry.getFile() != null)
240           {
241             entries.add(new CachedPDB(seq, pdbEntry));
242           }
243         }
244       }
245     }
246     cachedPDBExists = !entries.isEmpty();
247     PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
248     tbl_local_pdb.setModel(tableModelx);
249   }
250
251   /**
252    * Builds a query string for a given sequences using its DBRef entries
253    * 
254    * @param seq
255    *          the sequences to build a query for
256    * @return the built query string
257    */
258
259   public static String buildQuery(SequenceI seq)
260   {
261     boolean isPDBRefsFound = false;
262     boolean isUniProtRefsFound = false;
263     StringBuilder queryBuilder = new StringBuilder();
264     Set<String> seqRefs = new LinkedHashSet<String>();
265
266     if (seq.getAllPDBEntries() != null
267             && queryBuilder.length() < MAX_QLENGTH)
268     {
269       for (PDBEntry entry : seq.getAllPDBEntries())
270       {
271         if (isValidSeqName(entry.getId()))
272         {
273           queryBuilder.append("pdb_id:")
274                   .append(entry.getId().toLowerCase()).append(" OR ");
275           isPDBRefsFound = true;
276         }
277       }
278     }
279
280     if (seq.getDBRefs() != null && seq.getDBRefs().length != 0)
281     {
282       for (DBRefEntry dbRef : seq.getDBRefs())
283       {
284         if (isValidSeqName(getDBRefId(dbRef))
285                 && queryBuilder.length() < MAX_QLENGTH)
286         {
287           if (dbRef.getSource().equalsIgnoreCase(DBRefSource.UNIPROT))
288           {
289             queryBuilder.append("uniprot_accession:")
290                     .append(getDBRefId(dbRef)).append(" OR ");
291             queryBuilder.append("uniprot_id:").append(getDBRefId(dbRef))
292                     .append(" OR ");
293             isUniProtRefsFound = true;
294           }
295           else if (dbRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
296           {
297
298             queryBuilder.append("pdb_id:")
299                     .append(getDBRefId(dbRef).toLowerCase()).append(" OR ");
300             isPDBRefsFound = true;
301           }
302           else
303           {
304             seqRefs.add(getDBRefId(dbRef));
305           }
306         }
307       }
308     }
309
310     if (!isPDBRefsFound && !isUniProtRefsFound)
311     {
312       String seqName = seq.getName();
313       seqName = sanitizeSeqName(seqName);
314       String[] names = seqName.toLowerCase().split("\\|");
315       for (String name : names)
316       {
317         // System.out.println("Found name : " + name);
318         name.trim();
319         if (isValidSeqName(name))
320         {
321           seqRefs.add(name);
322         }
323       }
324
325       for (String seqRef : seqRefs)
326       {
327         queryBuilder.append("text:").append(seqRef).append(" OR ");
328       }
329     }
330
331     int endIndex = queryBuilder.lastIndexOf(" OR ");
332     if (queryBuilder.toString().length() < 6)
333     {
334       return null;
335     }
336     String query = queryBuilder.toString().substring(0, endIndex);
337     return query;
338   }
339
340   /**
341    * Remove the following special characters from input string +, -, &, !, (, ),
342    * {, }, [, ], ^, ", ~, *, ?, :, \
343    * 
344    * @param seqName
345    * @return
346    */
347   static String sanitizeSeqName(String seqName)
348   {
349     Objects.requireNonNull(seqName);
350     return seqName.replaceAll("\\[\\d*\\]", "")
351             .replaceAll("[^\\dA-Za-z|_]", "").replaceAll("\\s+", "+");
352   }
353
354   /**
355    * Ensures sequence ref names are not less than 3 characters and does not
356    * contain a database name
357    * 
358    * @param seqName
359    * @return
360    */
361   public static boolean isValidSeqName(String seqName)
362   {
363     // System.out.println("seqName : " + seqName);
364     String ignoreList = "pdb,uniprot,swiss-prot";
365     if (seqName.length() < 3)
366     {
367       return false;
368     }
369     if (seqName.contains(":"))
370     {
371       return false;
372     }
373     seqName = seqName.toLowerCase();
374     for (String ignoredEntry : ignoreList.split(","))
375     {
376       if (seqName.contains(ignoredEntry))
377       {
378         return false;
379       }
380     }
381     return true;
382   }
383
384   public static String getDBRefId(DBRefEntry dbRef)
385   {
386     String ref = dbRef.getAccessionId().replaceAll("GO:", "");
387     return ref;
388   }
389
390   /**
391    * Filters a given list of discovered structures based on supplied argument
392    * 
393    * @param fieldToFilterBy
394    *          the field to filter by
395    */
396   public void filterResultSet(final String fieldToFilterBy)
397   {
398     Thread filterThread = new Thread(new Runnable()
399     {
400       @Override
401       public void run()
402       {
403         long startTime = System.currentTimeMillis();
404         pdbRestCleint = PDBFTSRestClient.getInstance();
405         lbl_loading.setVisible(true);
406         Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
407                 .getStructureSummaryFields();
408         Collection<FTSData> filteredResponse = new HashSet<FTSData>();
409         HashSet<String> errors = new HashSet<String>();
410
411         for (SequenceI seq : selectedSequences)
412         {
413           FTSRestRequest pdbRequest = new FTSRestRequest();
414           if (fieldToFilterBy.equalsIgnoreCase("uniprot_coverage"))
415           {
416             pdbRequest.setAllowEmptySeq(false);
417             pdbRequest.setResponseSize(1);
418             pdbRequest.setFieldToSearchBy("(");
419             pdbRequest.setSearchTerm(buildQuery(seq) + ")");
420             pdbRequest.setWantedFields(wantedFields);
421             pdbRequest.setAssociatedSequence(seq);
422             pdbRequest.setFacet(true);
423             pdbRequest.setFacetPivot(fieldToFilterBy + ",entry_entity");
424             pdbRequest.setFacetPivotMinCount(1);
425           }
426           else
427           {
428             pdbRequest.setAllowEmptySeq(false);
429             pdbRequest.setResponseSize(1);
430             pdbRequest.setFieldToSearchBy("(");
431             pdbRequest.setFieldToSortBy(fieldToFilterBy,
432                     !chk_invertFilter.isSelected());
433             pdbRequest.setSearchTerm(buildQuery(seq) + ")");
434             pdbRequest.setWantedFields(wantedFields);
435             pdbRequest.setAssociatedSequence(seq);
436           }
437           FTSRestResponse resultList;
438           try
439           {
440             resultList = pdbRestCleint.executeRequest(pdbRequest);
441           } catch (Exception e)
442           {
443             e.printStackTrace();
444             errors.add(e.getMessage());
445             continue;
446           }
447           lastPdbRequest = pdbRequest;
448           if (resultList.getSearchSummary() != null
449                   && !resultList.getSearchSummary().isEmpty())
450           {
451             filteredResponse.addAll(resultList.getSearchSummary());
452           }
453         }
454
455         String totalTime = (System.currentTimeMillis() - startTime)
456                 + " milli secs";
457         if (!filteredResponse.isEmpty())
458         {
459           final int filterResponseCount = filteredResponse.size();
460           Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<FTSData>();
461           reorderedStructuresSet.addAll(filteredResponse);
462           reorderedStructuresSet.addAll(discoveredStructuresSet);
463           getResultTable().setModel(
464                   JvSummaryTable.getTableModel(lastPdbRequest,
465                           reorderedStructuresSet));
466
467           JvSummaryTable.configureTableColumn(getResultTable(),
468                   wantedFields, tempUserPrefs);
469           getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
470           getResultTable().getColumn("Ref Sequence").setMinWidth(100);
471           getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
472           // Update table selection model here
473           getResultTable().addRowSelectionInterval(0,
474                   filterResponseCount - 1);
475           mainFrame.setTitle(MessageManager.formatMessage(
476                   "label.structure_chooser_filter_time", totalTime));
477         }
478         else
479         {
480           mainFrame.setTitle(MessageManager.formatMessage(
481                   "label.structure_chooser_filter_time", totalTime));
482           if (errors.size() > 0)
483           {
484             StringBuilder errorMsg = new StringBuilder();
485             for (String error : errors)
486             {
487               errorMsg.append(error).append("\n");
488             }
489             JvOptionPane.showMessageDialog(
490                     null,
491                     errorMsg.toString(),
492                     MessageManager.getString("label.pdb_web-service_error"),
493                     JvOptionPane.ERROR_MESSAGE);
494           }
495         }
496
497         lbl_loading.setVisible(false);
498
499         validateSelections();
500       }
501     });
502     filterThread.start();
503   }
504
505   /**
506    * Handles action event for btn_pdbFromFile
507    */
508   @Override
509   public void pdbFromFile_actionPerformed()
510   {
511     jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
512             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
513     chooser.setFileView(new jalview.io.JalviewFileView());
514     chooser.setDialogTitle(MessageManager.formatMessage(
515             "label.select_pdb_file_for",
516             selectedSequence.getDisplayId(false)));
517     chooser.setToolTipText(MessageManager.formatMessage(
518             "label.load_pdb_file_associate_with_sequence",
519             selectedSequence.getDisplayId(false)));
520
521     int value = chooser.showOpenDialog(null);
522     if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
523     {
524       selectedStructureFileName = chooser.getSelectedFile().getPath();
525       jalview.bin.Cache.setProperty("LAST_DIRECTORY",
526               selectedStructureFileName);
527       validateSelections();
528     }
529   }
530
531   /**
532    * Populates the filter combo-box options dynamically depending on discovered
533    * structures
534    */
535   protected void populateFilterComboBox(boolean haveData,
536           boolean cachedPDBExists)
537   {
538     /*
539      * temporarily suspend the change listener behaviour
540      */
541     cmb_filterOption.removeItemListener(this);
542
543     cmb_filterOption.removeAllItems();
544     if (haveData)
545     {
546       cmb_filterOption.addItem(new FilterOption("Best Quality",
547               "overall_quality", VIEWS_FILTER, false));
548       cmb_filterOption.addItem(new FilterOption("Best Resolution",
549               "resolution", VIEWS_FILTER, false));
550       cmb_filterOption.addItem(new FilterOption("Most Protein Chain",
551               "number_of_protein_chains", VIEWS_FILTER, false));
552       cmb_filterOption.addItem(new FilterOption("Most Bound Molecules",
553               "number_of_bound_molecules", VIEWS_FILTER, false));
554       cmb_filterOption.addItem(new FilterOption("Most Polymer Residues",
555               "number_of_polymer_residues", VIEWS_FILTER, true));
556     }
557     cmb_filterOption.addItem(new FilterOption("Enter PDB Id", "-",
558             VIEWS_ENTER_ID, false));
559     cmb_filterOption.addItem(new FilterOption("From File", "-",
560             VIEWS_FROM_FILE, false));
561
562     if (cachedPDBExists)
563     {
564       FilterOption cachedOption = new FilterOption("Cached PDB Entries",
565               "-", VIEWS_LOCAL_PDB, false);
566       cmb_filterOption.addItem(cachedOption);
567       cmb_filterOption.setSelectedItem(cachedOption);
568     }
569
570     cmb_filterOption.addItem(new FilterOption(
571             "Predict 3D Model with Phyre2", "-", VIEWS_PHYRE2_PREDICTION,
572             false));
573     cmb_filterOption.addItemListener(this);
574   }
575
576   /**
577    * Updates the displayed view based on the selected filter option
578    */
579   protected void updateCurrentView()
580   {
581     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
582             .getSelectedItem());
583     layout_switchableViews.show(pnl_switchableViews,
584             selectedFilterOpt.getView());
585     String filterTitle = mainFrame.getTitle();
586     mainFrame.setTitle(frameTitle);
587     chk_invertFilter.setVisible(false);
588     if (selectedFilterOpt.getView() == VIEWS_FILTER)
589     {
590       mainFrame.setTitle(filterTitle);
591       chk_invertFilter.setVisible(true);
592       filterResultSet(selectedFilterOpt.getValue());
593     }
594     else if (selectedFilterOpt.getView() == VIEWS_PHYRE2_PREDICTION)
595     {
596       mainFrame.setTitle(MessageManager
597               .getString("label.phyre2_model_prediction"));
598       phyre2InputAssSeqPanel.loadCmbAssSeq();
599     }
600     else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
601             || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
602     {
603       mainFrame.setTitle(MessageManager
604               .getString("label.structure_chooser_manual_association"));
605       idInputAssSeqPanel.loadCmbAssSeq();
606       fileChooserAssSeqPanel.loadCmbAssSeq();
607     }
608     validateSelections();
609   }
610
611   /**
612    * Validates user selection and activates the view button if all parameters
613    * are correct
614    */
615   @Override
616   public void validateSelections()
617   {
618     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
619             .getSelectedItem());
620     btn_view.setEnabled(false);
621     String currentView = selectedFilterOpt.getView();
622     if (currentView == VIEWS_FILTER)
623     {
624       if (getResultTable().getSelectedRows().length > 0)
625       {
626         btn_view.setEnabled(true);
627       }
628     }
629     else if (currentView == VIEWS_LOCAL_PDB)
630     {
631       if (tbl_local_pdb.getSelectedRows().length > 0)
632       {
633         btn_view.setEnabled(true);
634       }
635     }
636     else if (currentView == VIEWS_ENTER_ID)
637     {
638       validateAssociationEnterPdb();
639     }
640     else if (currentView == VIEWS_FROM_FILE)
641     {
642       validateAssociationFromFile();
643     }
644     else if (currentView == VIEWS_PHYRE2_PREDICTION)
645     {
646       validateAssociationFromPhyre2();
647       if (getPhyreResultTable().getSelectedRows().length > 0)
648       {
649         btn_view.setEnabled(true);
650       }
651     }
652   }
653
654   /**
655    * Validates inputs from the Manual PDB entry panel
656    */
657   public void validateAssociationEnterPdb()
658   {
659     AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
660             .getCmb_assSeq().getSelectedItem();
661     lbl_pdbManualFetchStatus.setIcon(errorImage);
662     lbl_pdbManualFetchStatus.setToolTipText("");
663     if (txt_search.getText().length() > 0)
664     {
665       lbl_pdbManualFetchStatus
666               .setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager
667                       .formatMessage("info.no_pdb_entry_found_for",
668                               txt_search.getText())));
669     }
670
671     if (errorWarning.length() > 0)
672     {
673       lbl_pdbManualFetchStatus.setIcon(warningImage);
674       lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(
675               true, errorWarning.toString()));
676     }
677
678     if (selectedSequences.length == 1
679             || !assSeqOpt.getName().equalsIgnoreCase(
680                     "-Select Associated Seq-"))
681     {
682       txt_search.setEnabled(true);
683       if (isValidPBDEntry)
684       {
685         btn_view.setEnabled(true);
686         lbl_pdbManualFetchStatus.setToolTipText("");
687         lbl_pdbManualFetchStatus.setIcon(goodImage);
688       }
689     }
690     else
691     {
692       txt_search.setEnabled(false);
693       lbl_pdbManualFetchStatus.setIcon(errorImage);
694     }
695   }
696
697   /**
698    * Validates inputs for the manual PDB file selection options
699    */
700   public void validateAssociationFromFile()
701   {
702     AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
703             .getCmb_assSeq().getSelectedItem();
704     lbl_fromFileStatus.setIcon(errorImage);
705     if (selectedSequences.length == 1
706             || (assSeqOpt != null && !assSeqOpt.getName().equalsIgnoreCase(
707                     "-Select Associated Seq-")))
708     {
709       btn_pdbFromFile.setEnabled(true);
710       if (selectedStructureFileName != null
711               && selectedStructureFileName.length() > 0)
712       {
713         btn_view.setEnabled(true);
714         lbl_fromFileStatus.setIcon(goodImage);
715       }
716     }
717     else
718     {
719       btn_pdbFromFile.setEnabled(false);
720       lbl_fromFileStatus.setIcon(errorImage);
721     }
722   }
723
724   /**
725    * Validates inputs for Phyre2 3D Model prediction
726    */
727   public void validateAssociationFromPhyre2()
728   {
729     AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) phyre2InputAssSeqPanel
730             .getCmb_assSeq().getSelectedItem();
731     if (selectedSequences.length == 1
732             || (assSeqOpt != null && !assSeqOpt.getName().equalsIgnoreCase(
733                     "-Select Associated Seq-")))
734     {
735       btn_runPhyre2Prediction.setEnabled(true);
736     }
737     else
738     {
739       btn_runPhyre2Prediction.setEnabled(false);
740     }
741   }
742
743   @Override
744   public void cmbAssSeqStateChanged()
745   {
746     validateSelections();
747   }
748
749   /**
750    * Handles the state change event for the 'filter' combo-box and 'invert'
751    * check-box
752    */
753   @Override
754   protected void stateChanged(ItemEvent e)
755   {
756     if (e.getSource() instanceof JCheckBox)
757     {
758       updateCurrentView();
759     }
760     else
761     {
762       if (e.getStateChange() == ItemEvent.SELECTED)
763       {
764         updateCurrentView();
765       }
766     }
767
768   }
769
770   /**
771    * Handles action event for btn_ok
772    */
773   @Override
774   public void ok_ActionPerformed()
775   {
776     final StructureSelectionManager ssm = ap.getStructureSelectionManager();
777     final int preferredHeight = pnl_filter.getHeight();
778     new Thread(new Runnable()
779     {
780       @Override
781       public void run()
782       {
783         FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
784                 .getSelectedItem());
785         String currentView = selectedFilterOpt.getView();
786         if (currentView == VIEWS_FILTER)
787         {
788           int pdbIdColIndex = getResultTable().getColumn("PDB Id")
789                   .getModelIndex();
790           int refSeqColIndex = getResultTable().getColumn("Ref Sequence")
791                   .getModelIndex();
792           int[] selectedRows = getResultTable().getSelectedRows();
793           PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
794           int count = 0;
795           List<SequenceI> selectedSeqsToView = new ArrayList<SequenceI>();
796           for (int row : selectedRows)
797           {
798             String pdbIdStr = getResultTable().getValueAt(row,
799                     pdbIdColIndex).toString();
800             SequenceI selectedSeq = (SequenceI) getResultTable()
801                     .getValueAt(row, refSeqColIndex);
802             selectedSeqsToView.add(selectedSeq);
803             PDBEntry pdbEntry = selectedSeq.getPDBEntry(pdbIdStr);
804             if (pdbEntry == null)
805             {
806               pdbEntry = getFindEntry(pdbIdStr,
807                       selectedSeq.getAllPDBEntries());
808             }
809             if (pdbEntry == null)
810             {
811               pdbEntry = new PDBEntry();
812               pdbEntry.setId(pdbIdStr);
813               pdbEntry.setType(PDBEntry.Type.PDB);
814               selectedSeq.getDatasetSequence().addPDBId(pdbEntry);
815             }
816             pdbEntriesToView[count++] = pdbEntry;
817           }
818           SequenceI[] selectedSeqs = selectedSeqsToView
819                   .toArray(new SequenceI[selectedSeqsToView.size()]);
820           launchStructureViewer(ssm, pdbEntriesToView, ap, selectedSeqs);
821         }
822         else if (currentView == VIEWS_LOCAL_PDB)
823         {
824           int[] selectedRows = tbl_local_pdb.getSelectedRows();
825           PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
826           int count = 0;
827           int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
828                   .getModelIndex();
829           int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
830                   .getModelIndex();
831           List<SequenceI> selectedSeqsToView = new ArrayList<SequenceI>();
832           for (int row : selectedRows)
833           {
834             PDBEntry pdbEntry = (PDBEntry) tbl_local_pdb.getValueAt(row,
835                     pdbIdColIndex);
836             pdbEntriesToView[count++] = pdbEntry;
837             SequenceI selectedSeq = (SequenceI) tbl_local_pdb.getValueAt(
838                     row, refSeqColIndex);
839             selectedSeqsToView.add(selectedSeq);
840           }
841           SequenceI[] selectedSeqs = selectedSeqsToView
842                   .toArray(new SequenceI[selectedSeqsToView.size()]);
843           launchStructureViewer(ssm, pdbEntriesToView, ap, selectedSeqs);
844         }
845         else if (currentView == VIEWS_ENTER_ID)
846         {
847           SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
848                   .getCmb_assSeq().getSelectedItem()).getSequence();
849           if (userSelectedSeq != null)
850           {
851             selectedSequence = userSelectedSeq;
852           }
853
854           String pdbIdStr = txt_search.getText();
855           PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
856           if (pdbEntry == null)
857           {
858             pdbEntry = new PDBEntry();
859             if (pdbIdStr.split(":").length > 1)
860             {
861               pdbEntry.setId(pdbIdStr.split(":")[0]);
862               pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase());
863             }
864             else
865             {
866               pdbEntry.setId(pdbIdStr);
867             }
868             pdbEntry.setType(PDBEntry.Type.PDB);
869             selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
870           }
871
872           PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
873           launchStructureViewer(ssm, pdbEntriesToView, ap,
874                   new SequenceI[] { selectedSequence });
875         }
876         else if (currentView == VIEWS_FROM_FILE)
877         {
878           SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
879                   .getCmb_assSeq().getSelectedItem()).getSequence();
880           if (userSelectedSeq != null)
881           {
882             selectedSequence = userSelectedSeq;
883           }
884           PDBEntry fileEntry = new AssociateStructureFileWithSeq()
885                   .associateStructureWithSeq(selectedStructureFileName,
886                           DataSourceType.FILE, selectedSequence, true,
887                           Desktop.instance);
888
889           launchStructureViewer(ssm, new PDBEntry[] { fileEntry }, ap,
890                   new SequenceI[] { selectedSequence });
891         }
892         else if (currentView == VIEWS_PHYRE2_PREDICTION)
893         {
894           SequenceI userSelectedSeq = ((AssociateSeqOptions) phyre2InputAssSeqPanel
895                   .getCmb_assSeq().getSelectedItem()).getSequence();
896           if (userSelectedSeq != null)
897           {
898             selectedSequence = userSelectedSeq;
899           }
900           int templateColIndex = getPhyreResultTable()
901                   .getColumn("Template").getModelIndex();
902           int[] selectedRows = getPhyreResultTable().getSelectedRows();
903           PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
904           int count = 0;
905           for (int row : selectedRows)
906           {
907             String templateId = getPhyreResultTable().getValueAt(row,
908                     templateColIndex).toString();
909             String structureFile = phyre2ResultDirectory + templateId;
910             pdbEntriesToView[count++] = new AssociateStructureFileWithSeq()
911                     .associateStructureWithSeq(structureFile,
912                             DataSourceType.FILE, selectedSequence, true,
913                             Desktop.instance);
914             ssm.registerPhyre2Template(structureFile);
915           }
916
917           final StructureSelectionManager ssm = ap
918                   .getStructureSelectionManager();
919           final long progressSessionId = System.currentTimeMillis();
920           ssm.setProgressSessionId(progressSessionId);
921
922           SequenceI[] sequences = new SequenceI[] { selectedSequence };
923
924           ssm.setProgressBar(MessageManager
925                   .getString("status.launching_3d_structure_viewer"));
926           final StructureViewer sViewer = new StructureViewer(ssm);
927           if (pdbEntriesToView.length > 1)
928           {
929             ArrayList<SequenceI[]> seqsMap = new ArrayList<SequenceI[]>();
930             for (SequenceI seq : sequences)
931             {
932               seqsMap.add(new SequenceI[] { seq });
933             }
934             SequenceI[][] collatedSeqs = seqsMap
935                     .toArray(new SequenceI[0][0]);
936             ssm.setProgressBar(null);
937             ssm.setProgressBar(MessageManager
938                     .getString("status.fetching_3d_structures_for_selected_entries"));
939             sViewer.viewStructures(pdbEntriesToView, collatedSeqs, ap);
940           }
941           else
942           {
943             ssm.setProgressBar(null);
944             ssm.setProgressBar(MessageManager.formatMessage(
945                     "status.fetching_3d_structures_for",
946                     pdbEntriesToView[0].getId()));
947             sViewer.viewStructures(pdbEntriesToView[0], sequences, ap);
948           }
949         }
950         closeAction(preferredHeight);
951       }
952     }).start();
953   }
954
955   private String phyre2ResultDirectory;
956
957   @Override
958   public void predict3DModelWithPhyre2()
959   {
960     // TODO implement code for submitting sequence to Phyre2 service, and code
961     // for getting the result directory when the job completes, this is
962     // currently hard-wired to the directory of result for FER_CAPAN/1-144
963     phyre2ResultDirectory = "examples/testdata/phyre2results/56da5616b4559c93/";
964     // String summaryhtml = phyre2ResultDirectory + "summary.html";
965     // // TODO ditch HTML parsing once appropriated data file (i.e. JSON) for
966     // // Phyre2 result summary is made available
967     // List<Phyre2SummaryPojo> phyreResults = Phyre2Client
968     // .parsePhyre2ResultSummaryTable(summaryhtml);
969
970     String crudeListFile = phyre2ResultDirectory + "crudelist";
971     List<Phyre2SummaryPojo> phyreResults = Phyre2Client
972             .parsePhyreCrudeList(crudeListFile);
973
974     getPhyreResultTable()
975             .setModel(Phyre2Client.getTableModel(phyreResults));
976     Phyre2Client.configurePhyreResultTable(getPhyreResultTable());
977   }
978
979   private PDBEntry getFindEntry(String id, Vector<PDBEntry> pdbEntries)
980   {
981     Objects.requireNonNull(id);
982     Objects.requireNonNull(pdbEntries);
983     PDBEntry foundEntry = null;
984     for (PDBEntry entry : pdbEntries)
985     {
986       if (entry.getId().equalsIgnoreCase(id))
987       {
988         return entry;
989       }
990     }
991     return foundEntry;
992   }
993
994   private void launchStructureViewer(StructureSelectionManager ssm,
995           final PDBEntry[] pdbEntriesToView,
996           final AlignmentPanel alignPanel, SequenceI[] sequences)
997   {
998     long progressId = sequences.hashCode();
999     setProgressBar(
1000             MessageManager
1001                     .getString("status.launching_3d_structure_viewer"),
1002             progressId);
1003     final StructureViewer sViewer = new StructureViewer(ssm);
1004     setProgressBar(null, progressId);
1005
1006     if (SiftsSettings.isMapWithSifts())
1007     {
1008       List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<SequenceI>();
1009       int p = 0;
1010       // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1011       // real PDB ID. For moment, we can also safely do this if there is already
1012       // a known mapping between the PDBEntry and the sequence.
1013
1014       for (SequenceI seq : sequences)
1015       {
1016         PDBEntry pdbe = pdbEntriesToView[p++];
1017         if (pdbe != null && pdbe.getFile() != null)
1018         {
1019           StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1020           if (smm != null && smm.length > 0)
1021           {
1022             for (StructureMapping sm : smm)
1023             {
1024               if (sm.getSequence() == seq)
1025               {
1026                 continue;
1027               }
1028             }
1029           }
1030         }
1031         if (seq.getPrimaryDBRefs().size() == 0
1032                 && !ssm.isPhyre2Template(pdbe.getFile()))
1033         {
1034           seqsWithoutSourceDBRef.add(seq);
1035           continue;
1036         }
1037       }
1038       if (!seqsWithoutSourceDBRef.isEmpty())
1039       {
1040         int y = seqsWithoutSourceDBRef.size();
1041         setProgressBar(MessageManager.formatMessage(
1042                 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1043                 y), progressId);
1044         SequenceI[] seqWithoutSrcDBRef = new SequenceI[y];
1045         int x = 0;
1046         for (SequenceI fSeq : seqsWithoutSourceDBRef)
1047         {
1048           seqWithoutSrcDBRef[x++] = fSeq;
1049         }
1050         new DBRefFetcher(seqWithoutSrcDBRef).fetchDBRefs(true);
1051         setProgressBar("Fetch complete.", progressId); // todo i18n
1052       }
1053     }
1054     if (pdbEntriesToView.length > 1)
1055     {
1056       ArrayList<SequenceI[]> seqsMap = new ArrayList<SequenceI[]>();
1057       for (SequenceI seq : sequences)
1058       {
1059         seqsMap.add(new SequenceI[] { seq });
1060       }
1061       SequenceI[][] collatedSeqs = seqsMap.toArray(new SequenceI[0][0]);
1062       setProgressBar(
1063               MessageManager
1064                       .getString("status.fetching_3d_structures_for_selected_entries"),
1065               progressId);
1066       sViewer.viewStructures(pdbEntriesToView, collatedSeqs, alignPanel);
1067     }
1068     else
1069     {
1070       setProgressBar(MessageManager.formatMessage(
1071               "status.fetching_3d_structures_for",
1072               pdbEntriesToView[0].getId()), progressId);
1073       sViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1074     }
1075     setProgressBar(null, progressId);
1076   }
1077
1078   /**
1079    * Populates the combo-box used in associating manually fetched structures to
1080    * a unique sequence when more than one sequence selection is made.
1081    */
1082   @Override
1083   public void populateCmbAssociateSeqOptions(
1084           JComboBox<AssociateSeqOptions> cmb_assSeq, JLabel lbl_associateSeq)
1085   {
1086     cmb_assSeq.removeAllItems();
1087     cmb_assSeq.addItem(new AssociateSeqOptions("-Select Associated Seq-",
1088             null));
1089     lbl_associateSeq.setVisible(false);
1090     if (selectedSequences.length > 1)
1091     {
1092       for (SequenceI seq : selectedSequences)
1093       {
1094         cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1095       }
1096     }
1097     else
1098     {
1099       String seqName = selectedSequence.getDisplayId(false);
1100       seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1101       lbl_associateSeq.setText(seqName);
1102       lbl_associateSeq.setVisible(true);
1103       cmb_assSeq.setVisible(false);
1104     }
1105   }
1106
1107   public boolean isStructuresDiscovered()
1108   {
1109     return discoveredStructuresSet != null
1110             && !discoveredStructuresSet.isEmpty();
1111   }
1112
1113   public Collection<FTSData> getDiscoveredStructuresSet()
1114   {
1115     return discoveredStructuresSet;
1116   }
1117
1118   @Override
1119   protected void txt_search_ActionPerformed()
1120   {
1121     new Thread()
1122     {
1123       @Override
1124       public void run()
1125       {
1126         errorWarning.setLength(0);
1127         isValidPBDEntry = false;
1128         if (txt_search.getText().length() > 0)
1129         {
1130           String searchTerm = txt_search.getText().toLowerCase();
1131           searchTerm = searchTerm.split(":")[0];
1132           // System.out.println(">>>>> search term : " + searchTerm);
1133           List<FTSDataColumnI> wantedFields = new ArrayList<FTSDataColumnI>();
1134           FTSRestRequest pdbRequest = new FTSRestRequest();
1135           pdbRequest.setAllowEmptySeq(false);
1136           pdbRequest.setResponseSize(1);
1137           pdbRequest.setFieldToSearchBy("(pdb_id:");
1138           pdbRequest.setWantedFields(wantedFields);
1139           pdbRequest.setSearchTerm(searchTerm + ")");
1140           pdbRequest.setAssociatedSequence(selectedSequence);
1141           pdbRestCleint = PDBFTSRestClient.getInstance();
1142           wantedFields.add(pdbRestCleint.getPrimaryKeyColumn());
1143           FTSRestResponse resultList;
1144           try
1145           {
1146             resultList = pdbRestCleint.executeRequest(pdbRequest);
1147           } catch (Exception e)
1148           {
1149             errorWarning.append(e.getMessage());
1150             return;
1151           } finally
1152           {
1153             validateSelections();
1154           }
1155           if (resultList.getSearchSummary() != null
1156                   && resultList.getSearchSummary().size() > 0)
1157           {
1158             isValidPBDEntry = true;
1159           }
1160         }
1161         validateSelections();
1162       }
1163     }.start();
1164   }
1165
1166   @Override
1167   public void tabRefresh()
1168   {
1169     if (selectedSequences != null)
1170     {
1171       Thread refreshThread = new Thread(new Runnable()
1172       {
1173         @Override
1174         public void run()
1175         {
1176           fetchStructuresMetaData();
1177           filterResultSet(((FilterOption) cmb_filterOption
1178                   .getSelectedItem()).getValue());
1179         }
1180       });
1181       refreshThread.start();
1182     }
1183   }
1184
1185   public class PDBEntryTableModel extends AbstractTableModel
1186   {
1187     String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type", "File" };
1188
1189     private List<CachedPDB> pdbEntries;
1190
1191     public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1192     {
1193       this.pdbEntries = new ArrayList<CachedPDB>(pdbEntries);
1194     }
1195
1196     @Override
1197     public String getColumnName(int columnIndex)
1198     {
1199       return columns[columnIndex];
1200     }
1201
1202     @Override
1203     public int getRowCount()
1204     {
1205       return pdbEntries.size();
1206     }
1207
1208     @Override
1209     public int getColumnCount()
1210     {
1211       return columns.length;
1212     }
1213
1214     @Override
1215     public boolean isCellEditable(int row, int column)
1216     {
1217       return false;
1218     }
1219
1220     @Override
1221     public Object getValueAt(int rowIndex, int columnIndex)
1222     {
1223       Object value = "??";
1224       CachedPDB entry = pdbEntries.get(rowIndex);
1225       switch (columnIndex)
1226       {
1227       case 0:
1228         value = entry.getSequence();
1229         break;
1230       case 1:
1231         value = entry.getPdbEntry();
1232         break;
1233       case 2:
1234         value = entry.getPdbEntry().getChainCode() == null ? "_" : entry
1235                 .getPdbEntry().getChainCode();
1236         break;
1237       case 3:
1238         value = entry.getPdbEntry().getType();
1239         break;
1240       case 4:
1241         value = entry.getPdbEntry().getFile();
1242         break;
1243       }
1244       return value;
1245     }
1246
1247     @Override
1248     public Class<?> getColumnClass(int columnIndex)
1249     {
1250       return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1251     }
1252
1253     public CachedPDB getPDBEntryAt(int row)
1254     {
1255       return pdbEntries.get(row);
1256     }
1257
1258   }
1259
1260   private class CachedPDB
1261   {
1262     private SequenceI sequence;
1263
1264     private PDBEntry pdbEntry;
1265
1266     public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1267     {
1268       this.sequence = sequence;
1269       this.pdbEntry = pdbEntry;
1270     }
1271
1272     public SequenceI getSequence()
1273     {
1274       return sequence;
1275     }
1276
1277     public PDBEntry getPdbEntry()
1278     {
1279       return pdbEntry;
1280     }
1281
1282   }
1283
1284   private IProgressIndicator progressBar;
1285
1286   @Override
1287   public void setProgressBar(String message, long id)
1288   {
1289     progressBar.setProgressBar(message, id);
1290   }
1291
1292   @Override
1293   public void registerHandler(long id, IProgressIndicatorHandler handler)
1294   {
1295     progressBar.registerHandler(id, handler);
1296   }
1297
1298   @Override
1299   public boolean operationInProgress()
1300   {
1301     return progressBar.operationInProgress();
1302   }
1303 }