bff6d6f5e69a94b28a902c82d6e9d1408d89c900
[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", selectedStructureFileName);
526       validateSelections();
527     }
528   }
529
530   /**
531    * Populates the filter combo-box options dynamically depending on discovered
532    * structures
533    */
534   protected void populateFilterComboBox(boolean haveData,
535           boolean cachedPDBExists)
536   {
537     /*
538      * temporarily suspend the change listener behaviour
539      */
540     cmb_filterOption.removeItemListener(this);
541
542     cmb_filterOption.removeAllItems();
543     if (haveData)
544     {
545       cmb_filterOption.addItem(new FilterOption("Best Quality",
546               "overall_quality", VIEWS_FILTER, false));
547       cmb_filterOption.addItem(new FilterOption("Best Resolution",
548               "resolution", VIEWS_FILTER, false));
549       cmb_filterOption.addItem(new FilterOption("Most Protein Chain",
550               "number_of_protein_chains", VIEWS_FILTER, false));
551       cmb_filterOption.addItem(new FilterOption("Most Bound Molecules",
552               "number_of_bound_molecules", VIEWS_FILTER, false));
553       cmb_filterOption.addItem(new FilterOption("Most Polymer Residues",
554               "number_of_polymer_residues", VIEWS_FILTER, true));
555     }
556     cmb_filterOption.addItem(new FilterOption("Enter PDB Id", "-",
557             VIEWS_ENTER_ID, false));
558     cmb_filterOption.addItem(new FilterOption("From File", "-",
559             VIEWS_FROM_FILE, false));
560
561     if (cachedPDBExists)
562     {
563       FilterOption cachedOption = new FilterOption("Cached PDB Entries",
564               "-", VIEWS_LOCAL_PDB, false);
565       cmb_filterOption.addItem(cachedOption);
566       cmb_filterOption.setSelectedItem(cachedOption);
567     }
568
569     cmb_filterOption.addItem(new FilterOption(
570             "Predict 3D Model with Phyre2", "-", VIEWS_PHYRE2_PREDICTION,
571             false));
572     cmb_filterOption.addItemListener(this);
573   }
574
575   /**
576    * Updates the displayed view based on the selected filter option
577    */
578   protected void updateCurrentView()
579   {
580     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
581             .getSelectedItem());
582     layout_switchableViews.show(pnl_switchableViews,
583             selectedFilterOpt.getView());
584     String filterTitle = mainFrame.getTitle();
585     mainFrame.setTitle(frameTitle);
586     chk_invertFilter.setVisible(false);
587     if (selectedFilterOpt.getView() == VIEWS_FILTER)
588     {
589       mainFrame.setTitle(filterTitle);
590       chk_invertFilter.setVisible(true);
591       filterResultSet(selectedFilterOpt.getValue());
592     }
593     else if (selectedFilterOpt.getView() == VIEWS_PHYRE2_PREDICTION)
594     {
595       mainFrame.setTitle(MessageManager
596               .getString("label.phyre2_model_prediction"));
597       phyre2InputAssSeqPanel.loadCmbAssSeq();
598     }
599     else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
600             || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
601     {
602       mainFrame.setTitle(MessageManager
603               .getString("label.structure_chooser_manual_association"));
604       idInputAssSeqPanel.loadCmbAssSeq();
605       fileChooserAssSeqPanel.loadCmbAssSeq();
606     }
607     validateSelections();
608   }
609
610   /**
611    * Validates user selection and activates the view button if all parameters
612    * are correct
613    */
614   @Override
615   public void validateSelections()
616   {
617     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
618             .getSelectedItem());
619     btn_view.setEnabled(false);
620     String currentView = selectedFilterOpt.getView();
621     if (currentView == VIEWS_FILTER)
622     {
623       if (getResultTable().getSelectedRows().length > 0)
624       {
625         btn_view.setEnabled(true);
626       }
627     }
628     else if (currentView == VIEWS_LOCAL_PDB)
629     {
630       if (tbl_local_pdb.getSelectedRows().length > 0)
631       {
632         btn_view.setEnabled(true);
633       }
634     }
635     else if (currentView == VIEWS_ENTER_ID)
636     {
637       validateAssociationEnterPdb();
638     }
639     else if (currentView == VIEWS_FROM_FILE)
640     {
641       validateAssociationFromFile();
642     }
643     else if (currentView == VIEWS_PHYRE2_PREDICTION)
644     {
645       validateAssociationFromPhyre2();
646       if (getPhyreResultTable().getSelectedRows().length > 0)
647       {
648         btn_view.setEnabled(true);
649       }
650     }
651   }
652
653   /**
654    * Validates inputs from the Manual PDB entry panel
655    */
656   public void validateAssociationEnterPdb()
657   {
658     AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
659             .getCmb_assSeq().getSelectedItem();
660     lbl_pdbManualFetchStatus.setIcon(errorImage);
661     lbl_pdbManualFetchStatus.setToolTipText("");
662     if (txt_search.getText().length() > 0)
663     {
664       lbl_pdbManualFetchStatus
665               .setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager
666                       .formatMessage("info.no_pdb_entry_found_for",
667                               txt_search.getText())));
668     }
669
670     if (errorWarning.length() > 0)
671     {
672       lbl_pdbManualFetchStatus.setIcon(warningImage);
673       lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(
674               true, errorWarning.toString()));
675     }
676
677     if (selectedSequences.length == 1
678             || !assSeqOpt.getName().equalsIgnoreCase(
679                     "-Select Associated Seq-"))
680     {
681       txt_search.setEnabled(true);
682       if (isValidPBDEntry)
683       {
684         btn_view.setEnabled(true);
685         lbl_pdbManualFetchStatus.setToolTipText("");
686         lbl_pdbManualFetchStatus.setIcon(goodImage);
687       }
688     }
689     else
690     {
691       txt_search.setEnabled(false);
692       lbl_pdbManualFetchStatus.setIcon(errorImage);
693     }
694   }
695
696   /**
697    * Validates inputs for the manual PDB file selection options
698    */
699   public void validateAssociationFromFile()
700   {
701     AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
702             .getCmb_assSeq().getSelectedItem();
703     lbl_fromFileStatus.setIcon(errorImage);
704     if (selectedSequences.length == 1
705             || (assSeqOpt != null && !assSeqOpt.getName().equalsIgnoreCase(
706                     "-Select Associated Seq-")))
707     {
708       btn_pdbFromFile.setEnabled(true);
709       if (selectedStructureFileName != null && selectedStructureFileName.length() > 0)
710       {
711         btn_view.setEnabled(true);
712         lbl_fromFileStatus.setIcon(goodImage);
713       }
714     }
715     else
716     {
717       btn_pdbFromFile.setEnabled(false);
718       lbl_fromFileStatus.setIcon(errorImage);
719     }
720   }
721
722   /**
723    * Validates inputs for Phyre2 3D Model prediction
724    */
725   public void validateAssociationFromPhyre2()
726   {
727     AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) phyre2InputAssSeqPanel
728             .getCmb_assSeq().getSelectedItem();
729     if (selectedSequences.length == 1
730             || (assSeqOpt != null && !assSeqOpt.getName().equalsIgnoreCase(
731                     "-Select Associated Seq-")))
732     {
733       btn_runPhyre2Prediction.setEnabled(true);
734     }
735     else
736     {
737       btn_runPhyre2Prediction.setEnabled(false);
738     }
739   }
740
741   @Override
742   public void cmbAssSeqStateChanged()
743   {
744     validateSelections();
745   }
746
747   /**
748    * Handles the state change event for the 'filter' combo-box and 'invert'
749    * check-box
750    */
751   @Override
752   protected void stateChanged(ItemEvent e)
753   {
754     if (e.getSource() instanceof JCheckBox)
755     {
756       updateCurrentView();
757     }
758     else
759     {
760       if (e.getStateChange() == ItemEvent.SELECTED)
761       {
762         updateCurrentView();
763       }
764     }
765
766   }
767
768   /**
769    * Handles action event for btn_ok
770    */
771   @Override
772   public void ok_ActionPerformed()
773   {
774     final StructureSelectionManager ssm = ap.getStructureSelectionManager();
775     final int preferredHeight = pnl_filter.getHeight();
776     ssm.setMappingForPhyre2Model(false);
777     new Thread(new Runnable()
778     {
779       @Override
780       public void run()
781       {
782         FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
783                 .getSelectedItem());
784         String currentView = selectedFilterOpt.getView();
785         if (currentView == VIEWS_FILTER)
786         {
787           int pdbIdColIndex = getResultTable().getColumn("PDB Id")
788                   .getModelIndex();
789           int refSeqColIndex = getResultTable().getColumn("Ref Sequence")
790                   .getModelIndex();
791           int[] selectedRows = getResultTable().getSelectedRows();
792           PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
793           int count = 0;
794           List<SequenceI> selectedSeqsToView = new ArrayList<SequenceI>();
795           for (int row : selectedRows)
796           {
797             String pdbIdStr = getResultTable().getValueAt(row,
798                     pdbIdColIndex).toString();
799             SequenceI selectedSeq = (SequenceI) getResultTable()
800                     .getValueAt(row, refSeqColIndex);
801             selectedSeqsToView.add(selectedSeq);
802             PDBEntry pdbEntry = selectedSeq.getPDBEntry(pdbIdStr);
803             if (pdbEntry == null)
804             {
805               pdbEntry = getFindEntry(pdbIdStr,
806                       selectedSeq.getAllPDBEntries());
807             }
808             if (pdbEntry == null)
809             {
810               pdbEntry = new PDBEntry();
811               pdbEntry.setId(pdbIdStr);
812               pdbEntry.setType(PDBEntry.Type.PDB);
813               selectedSeq.getDatasetSequence().addPDBId(pdbEntry);
814             }
815             pdbEntriesToView[count++] = pdbEntry;
816           }
817           SequenceI[] selectedSeqs = selectedSeqsToView
818                   .toArray(new SequenceI[selectedSeqsToView.size()]);
819           launchStructureViewer(ssm, pdbEntriesToView, ap, selectedSeqs);
820         }
821         else if (currentView == VIEWS_LOCAL_PDB)
822         {
823           int[] selectedRows = tbl_local_pdb.getSelectedRows();
824           PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
825           int count = 0;
826           int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
827                   .getModelIndex();
828           int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
829                   .getModelIndex();
830           List<SequenceI> selectedSeqsToView = new ArrayList<SequenceI>();
831           for (int row : selectedRows)
832           {
833             PDBEntry pdbEntry = (PDBEntry) tbl_local_pdb.getValueAt(row,
834                     pdbIdColIndex);
835             pdbEntriesToView[count++] = pdbEntry;
836             SequenceI selectedSeq = (SequenceI) tbl_local_pdb.getValueAt(
837                     row, refSeqColIndex);
838             selectedSeqsToView.add(selectedSeq);
839           }
840           SequenceI[] selectedSeqs = selectedSeqsToView
841                   .toArray(new SequenceI[selectedSeqsToView.size()]);
842           launchStructureViewer(ssm, pdbEntriesToView, ap, selectedSeqs);
843         }
844         else if (currentView == VIEWS_ENTER_ID)
845         {
846           SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
847                   .getCmb_assSeq().getSelectedItem()).getSequence();
848           if (userSelectedSeq != null)
849           {
850             selectedSequence = userSelectedSeq;
851           }
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,
887                       selectedSequence, true, Desktop.instance);
888
889           launchStructureViewer(ssm,
890                   new PDBEntry[] { fileEntry }, ap,
891                   new SequenceI[] { selectedSequence });
892         }
893         else if (currentView == VIEWS_PHYRE2_PREDICTION)
894         {
895           SequenceI userSelectedSeq = ((AssociateSeqOptions) phyre2InputAssSeqPanel
896                   .getCmb_assSeq().getSelectedItem()).getSequence();
897           if (userSelectedSeq != null)
898           {
899             selectedSequence = userSelectedSeq;
900           }
901           int templateColIndex = getPhyreResultTable()
902                   .getColumn("Template")
903                   .getModelIndex();
904           int[] selectedRows = getPhyreResultTable().getSelectedRows();
905           PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
906           int count = 0;
907           for (int row : selectedRows)
908           {
909             String templateId = getPhyreResultTable().getValueAt(row,
910                     templateColIndex).toString();
911             String structureFile = phyre2ResultDirectory + templateId
912                     + ".pdb";
913             pdbEntriesToView[count++] = new AssociateStructureFileWithSeq()
914                     .associateStructureWithSeq(structureFile,
915                             DataSourceType.FILE, selectedSequence, true,
916                             Desktop.instance);
917           }
918
919           final StructureSelectionManager ssm = ap
920                   .getStructureSelectionManager();
921           ssm.setMappingForPhyre2Model(true);
922           final long progressSessionId = System.currentTimeMillis();
923           ssm.setProgressSessionId(progressSessionId);
924
925           SequenceI[] sequences = new SequenceI[] { selectedSequence };
926
927           ssm.setProgressBar(MessageManager
928                   .getString("status.launching_3d_structure_viewer"));
929           final StructureViewer sViewer = new StructureViewer(ssm);
930           if (pdbEntriesToView.length > 1)
931           {
932             ArrayList<SequenceI[]> seqsMap = new ArrayList<SequenceI[]>();
933             for (SequenceI seq : sequences)
934             {
935               seqsMap.add(new SequenceI[] { seq });
936             }
937             SequenceI[][] collatedSeqs = seqsMap
938                     .toArray(new SequenceI[0][0]);
939             ssm.setProgressBar(null);
940             ssm.setProgressBar(MessageManager
941                     .getString("status.fetching_3d_structures_for_selected_entries"));
942             sViewer.viewStructures(pdbEntriesToView, collatedSeqs, ap);
943           }
944           else
945           {
946             ssm.setProgressBar(null);
947             ssm.setProgressBar(MessageManager.formatMessage(
948                     "status.fetching_3d_structures_for",
949                     pdbEntriesToView[0].getId()));
950             sViewer.viewStructures(pdbEntriesToView[0], sequences, ap);
951           }
952         }
953         closeAction(preferredHeight);
954       }
955     }).start();
956   }
957
958   private String phyre2ResultDirectory;
959
960   @Override
961   public void predict3DModelWithPhyre2()
962   {
963     // TODO implement code for submitting sequence to Phyre2 service, and code
964     // for getting the result directory when the job completes, this is
965     // currently hard-wired to the directory of result for FER_CAPAN/1-144
966     phyre2ResultDirectory = "examples/testdata/phyre2results/56da5616b4559c93/";
967     String summaryhtml = phyre2ResultDirectory + "summary.html";
968     // TODO ditch HTML parsing once appropriated data file (i.e. JSON) for
969     // Phyre2 result summary is made available
970     List<Phyre2SummaryPojo> phyreResults = Phyre2Client
971             .parsePhyre2ResultSummaryTable(summaryhtml);
972     getPhyreResultTable()
973             .setModel(Phyre2Client.getTableModel(phyreResults));
974     Phyre2Client.configurePhyreResultTable(getPhyreResultTable());
975   }
976
977   private PDBEntry getFindEntry(String id, Vector<PDBEntry> pdbEntries)
978   {
979     Objects.requireNonNull(id);
980     Objects.requireNonNull(pdbEntries);
981     PDBEntry foundEntry = null;
982     for (PDBEntry entry : pdbEntries)
983     {
984       if (entry.getId().equalsIgnoreCase(id))
985       {
986         return entry;
987       }
988     }
989     return foundEntry;
990   }
991
992   private void launchStructureViewer(StructureSelectionManager ssm,
993           final PDBEntry[] pdbEntriesToView,
994           final AlignmentPanel alignPanel, SequenceI[] sequences)
995   {
996     long progressId = sequences.hashCode();
997     setProgressBar(MessageManager
998             .getString("status.launching_3d_structure_viewer"), progressId);
999     final StructureViewer sViewer = new StructureViewer(ssm);
1000     setProgressBar(null, progressId);
1001
1002     if (SiftsSettings.isMapWithSifts())
1003     {
1004       List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<SequenceI>();
1005       int p = 0;
1006       // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1007       // real PDB ID. For moment, we can also safely do this if there is already
1008       // a known mapping between the PDBEntry and the sequence.
1009
1010       for (SequenceI seq : sequences)
1011       {
1012         PDBEntry pdbe = pdbEntriesToView[p++];
1013         if (pdbe != null && pdbe.getFile() != null)
1014         {
1015           StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1016           if (smm != null && smm.length > 0)
1017           {
1018             for (StructureMapping sm : smm)
1019             {
1020               if (sm.getSequence() == seq)
1021               {
1022                 continue;
1023               }
1024             }
1025           }
1026         }
1027         if (seq.getPrimaryDBRefs().size() == 0)
1028         {
1029           seqsWithoutSourceDBRef.add(seq);
1030           continue;
1031         }
1032       }
1033       if (!seqsWithoutSourceDBRef.isEmpty())
1034       {
1035         int y = seqsWithoutSourceDBRef.size();
1036         setProgressBar(MessageManager.formatMessage(
1037                 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1038                 y), progressId);
1039         SequenceI[] seqWithoutSrcDBRef = new SequenceI[y];
1040         int x = 0;
1041         for (SequenceI fSeq : seqsWithoutSourceDBRef)
1042         {
1043           seqWithoutSrcDBRef[x++] = fSeq;
1044         }
1045         new DBRefFetcher(seqWithoutSrcDBRef).fetchDBRefs(true);
1046         setProgressBar("Fetch complete.", progressId); // todo i18n
1047       }
1048     }
1049     if (pdbEntriesToView.length > 1)
1050     {
1051       ArrayList<SequenceI[]> seqsMap = new ArrayList<SequenceI[]>();
1052       for (SequenceI seq : sequences)
1053       {
1054         seqsMap.add(new SequenceI[] { seq });
1055       }
1056       SequenceI[][] collatedSeqs = seqsMap.toArray(new SequenceI[0][0]);
1057       setProgressBar(MessageManager
1058                      .getString("status.fetching_3d_structures_for_selected_entries"), progressId);
1059       sViewer.viewStructures(pdbEntriesToView, collatedSeqs, alignPanel);
1060     }
1061     else
1062     {
1063       setProgressBar(MessageManager.formatMessage(
1064               "status.fetching_3d_structures_for",
1065               pdbEntriesToView[0].getId()),progressId);
1066       sViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1067     }
1068     setProgressBar(null, progressId);
1069   }
1070
1071   /**
1072    * Populates the combo-box used in associating manually fetched structures to
1073    * a unique sequence when more than one sequence selection is made.
1074    */
1075   @Override
1076   public void populateCmbAssociateSeqOptions(
1077           JComboBox<AssociateSeqOptions> cmb_assSeq, JLabel lbl_associateSeq)
1078   {
1079     cmb_assSeq.removeAllItems();
1080     cmb_assSeq.addItem(new AssociateSeqOptions("-Select Associated Seq-",
1081             null));
1082     lbl_associateSeq.setVisible(false);
1083     if (selectedSequences.length > 1)
1084     {
1085       for (SequenceI seq : selectedSequences)
1086       {
1087         cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1088       }
1089     }
1090     else
1091     {
1092       String seqName = selectedSequence.getDisplayId(false);
1093       seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1094       lbl_associateSeq.setText(seqName);
1095       lbl_associateSeq.setVisible(true);
1096       cmb_assSeq.setVisible(false);
1097     }
1098   }
1099
1100   public boolean isStructuresDiscovered()
1101   {
1102     return discoveredStructuresSet != null
1103             && !discoveredStructuresSet.isEmpty();
1104   }
1105
1106   public Collection<FTSData> getDiscoveredStructuresSet()
1107   {
1108     return discoveredStructuresSet;
1109   }
1110
1111   @Override
1112   protected void txt_search_ActionPerformed()
1113   {
1114     new Thread()
1115     {
1116       @Override
1117       public void run()
1118       {
1119         errorWarning.setLength(0);
1120         isValidPBDEntry = false;
1121         if (txt_search.getText().length() > 0)
1122         {
1123           String searchTerm = txt_search.getText().toLowerCase();
1124           searchTerm = searchTerm.split(":")[0];
1125           // System.out.println(">>>>> search term : " + searchTerm);
1126           List<FTSDataColumnI> wantedFields = new ArrayList<FTSDataColumnI>();
1127           FTSRestRequest pdbRequest = new FTSRestRequest();
1128           pdbRequest.setAllowEmptySeq(false);
1129           pdbRequest.setResponseSize(1);
1130           pdbRequest.setFieldToSearchBy("(pdb_id:");
1131           pdbRequest.setWantedFields(wantedFields);
1132           pdbRequest.setSearchTerm(searchTerm + ")");
1133           pdbRequest.setAssociatedSequence(selectedSequence);
1134           pdbRestCleint = PDBFTSRestClient.getInstance();
1135           wantedFields.add(pdbRestCleint.getPrimaryKeyColumn());
1136           FTSRestResponse resultList;
1137           try
1138           {
1139             resultList = pdbRestCleint.executeRequest(pdbRequest);
1140           } catch (Exception e)
1141           {
1142             errorWarning.append(e.getMessage());
1143             return;
1144           } finally
1145           {
1146             validateSelections();
1147           }
1148           if (resultList.getSearchSummary() != null
1149                   && resultList.getSearchSummary().size() > 0)
1150           {
1151             isValidPBDEntry = true;
1152           }
1153         }
1154         validateSelections();
1155       }
1156     }.start();
1157   }
1158
1159   @Override
1160   public void tabRefresh()
1161   {
1162     if (selectedSequences != null)
1163     {
1164       Thread refreshThread = new Thread(new Runnable()
1165       {
1166         @Override
1167         public void run()
1168         {
1169           fetchStructuresMetaData();
1170           filterResultSet(((FilterOption) cmb_filterOption
1171                   .getSelectedItem()).getValue());
1172         }
1173       });
1174       refreshThread.start();
1175     }
1176   }
1177
1178   public class PDBEntryTableModel extends AbstractTableModel
1179   {
1180     String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type", "File" };
1181
1182     private List<CachedPDB> pdbEntries;
1183
1184     public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1185     {
1186       this.pdbEntries = new ArrayList<CachedPDB>(pdbEntries);
1187     }
1188
1189     @Override
1190     public String getColumnName(int columnIndex)
1191     {
1192       return columns[columnIndex];
1193     }
1194
1195     @Override
1196     public int getRowCount()
1197     {
1198       return pdbEntries.size();
1199     }
1200
1201     @Override
1202     public int getColumnCount()
1203     {
1204       return columns.length;
1205     }
1206
1207     @Override
1208     public boolean isCellEditable(int row, int column)
1209     {
1210       return false;
1211     }
1212
1213     @Override
1214     public Object getValueAt(int rowIndex, int columnIndex)
1215     {
1216       Object value = "??";
1217       CachedPDB entry = pdbEntries.get(rowIndex);
1218       switch (columnIndex)
1219       {
1220       case 0:
1221         value = entry.getSequence();
1222         break;
1223       case 1:
1224         value = entry.getPdbEntry();
1225         break;
1226       case 2:
1227         value = entry.getPdbEntry().getChainCode() == null ? "_" : entry
1228                 .getPdbEntry().getChainCode();
1229         break;
1230       case 3:
1231         value = entry.getPdbEntry().getType();
1232         break;
1233       case 4:
1234         value = entry.getPdbEntry().getFile();
1235         break;
1236       }
1237       return value;
1238     }
1239
1240     @Override
1241     public Class<?> getColumnClass(int columnIndex)
1242     {
1243       return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1244     }
1245
1246     public CachedPDB getPDBEntryAt(int row)
1247     {
1248       return pdbEntries.get(row);
1249     }
1250
1251   }
1252
1253   private class CachedPDB
1254   {
1255     private SequenceI sequence;
1256
1257     private PDBEntry pdbEntry;
1258
1259     public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1260     {
1261       this.sequence = sequence;
1262       this.pdbEntry = pdbEntry;
1263     }
1264
1265     public SequenceI getSequence()
1266     {
1267       return sequence;
1268     }
1269
1270     public PDBEntry getPdbEntry()
1271     {
1272       return pdbEntry;
1273     }
1274
1275   }
1276
1277   private IProgressIndicator progressBar;
1278
1279   @Override
1280   public void setProgressBar(String message, long id)
1281   {
1282     progressBar.setProgressBar(message, id);
1283   }
1284
1285   @Override
1286   public void registerHandler(long id, IProgressIndicatorHandler handler)
1287   {
1288     progressBar.registerHandler(id, handler);
1289   }
1290
1291   @Override
1292   public boolean operationInProgress()
1293   {
1294     return progressBar.operationInProgress();
1295   }
1296 }