3 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
4 * Copyright (C) 2014 The Jalview Authors
6 * This file is part of Jalview.
8 * Jalview is free software: you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation, either version 3
11 * of the License, or (at your option) any later version.
13 * Jalview is distributed in the hope that it will be useful, but
14 * WITHOUT ANY WARRANTY; without even the implied warranty
15 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
16 * PURPOSE. See the GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
20 * The Jalview Authors are detailed in the 'AUTHORS' file.
25 import jalview.datamodel.DBRefEntry;
26 import jalview.datamodel.PDBEntry;
27 import jalview.datamodel.SequenceI;
28 import jalview.jbgui.GStructureChooser;
29 import jalview.jbgui.PDBDocFieldPreferences;
30 import jalview.structure.StructureSelectionManager;
31 import jalview.util.MessageManager;
32 import jalview.ws.dbsources.PDBRestClient;
33 import jalview.ws.dbsources.PDBRestClient.PDBDocField;
34 import jalview.ws.uimodel.PDBRestRequest;
35 import jalview.ws.uimodel.PDBRestResponse;
36 import jalview.ws.uimodel.PDBRestResponse.PDBResponseSummary;
38 import java.awt.event.ItemEvent;
39 import java.util.ArrayList;
40 import java.util.Collection;
41 import java.util.HashSet;
42 import java.util.Hashtable;
43 import java.util.LinkedHashSet;
44 import java.util.List;
46 import javax.swing.JCheckBox;
47 import javax.swing.JComboBox;
48 import javax.swing.JLabel;
49 import javax.swing.JOptionPane;
50 import javax.swing.table.DefaultTableModel;
54 * Provides the behaviors for the Structure chooser Panel
59 @SuppressWarnings("serial")
60 public class StructureChooser extends GStructureChooser
62 private boolean structuresDiscovered = false;
64 private SequenceI selectedSequence;
66 private SequenceI[] selectedSequences;
68 private IProgressIndicator progressIndicator;
70 private Collection<PDBResponseSummary> discoveredStructuresSet;
72 private PDBRestRequest lastPdbRequest;
74 private PDBRestClient pdbRestCleint;
76 private String selectedPdbFileName;
78 private boolean isValidPBDEntry;
80 private static Hashtable<String, PDBEntry> cachedEntryMap;
82 public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
86 this.selectedSequence = selectedSeq;
87 this.selectedSequences = selectedSeqs;
88 this.progressIndicator = (ap == null) ? null : ap.alignFrame;
93 * Initializes parameters used by the Structure Chooser Panel
97 Thread discoverPDBStructuresThread = new Thread(new Runnable()
102 long startTime = System.currentTimeMillis();
103 String msg = MessageManager.getString("status.fetching_db_refs");
104 updateProgressIndicator(msg, startTime);
105 loadLocalCachedPDBEntries();
106 fetchStructuresMetaData();
107 populateFilterComboBox();
108 updateProgressIndicator(null, startTime);
109 mainFrame.setVisible(true);
113 discoverPDBStructuresThread.start();
117 * Updates the progress indicator with the specified message
120 * displayed message for the operation
122 * unique handle for this indicator
124 public void updateProgressIndicator(String message, long id)
126 if (progressIndicator != null)
128 progressIndicator.setProgressBar(message, id);
133 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
136 public void fetchStructuresMetaData()
138 long startTime = System.currentTimeMillis();
139 Collection<PDBDocField> wantedFields = PDBDocFieldPreferences
140 .getStructureSummaryFields();
142 discoveredStructuresSet = new LinkedHashSet<PDBResponseSummary>();
143 HashSet<String> errors = new HashSet<String>();
144 for (SequenceI seq : selectedSequences)
146 PDBRestRequest pdbRequest = new PDBRestRequest();
147 pdbRequest.setAllowEmptySeq(false);
148 pdbRequest.setResponseSize(500);
149 pdbRequest.setFieldToSearchBy("(text:");
150 pdbRequest.setWantedFields(wantedFields);
151 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
152 pdbRequest.setAssociatedSequence(seq.getName());
153 pdbRestCleint = new PDBRestClient();
154 PDBRestResponse resultList;
157 resultList = pdbRestCleint.executeRequest(pdbRequest);
158 } catch (Exception e)
160 errors.add(e.getMessage());
163 lastPdbRequest = pdbRequest;
164 if (resultList.getSearchSummary() != null
165 && !resultList.getSearchSummary().isEmpty())
167 discoveredStructuresSet.addAll(resultList.getSearchSummary());
168 updateSequenceDbRef(seq, resultList.getSearchSummary());
172 int noOfStructuresFound = 0;
173 String totalTime = (System.currentTimeMillis() - startTime)
175 if (discoveredStructuresSet != null
176 && !discoveredStructuresSet.isEmpty())
178 tbl_summary.setModel(PDBRestResponse.getTableModel(lastPdbRequest,
179 discoveredStructuresSet));
180 structuresDiscovered = true;
181 noOfStructuresFound = discoveredStructuresSet.size();
182 mainFrame.setTitle("Structure Chooser - " + noOfStructuresFound
183 + " Found (" + totalTime + ")");
188 .setTitle("Structure Chooser - Manual association");
189 if (errors.size() > 0)
191 StringBuilder errorMsg = new StringBuilder(
192 "Operation was unsucessful due to the following: \n");
193 for (String error : errors)
195 errorMsg.append(error).append("\n");
197 JOptionPane.showMessageDialog(this, errorMsg.toString(),
198 "PDB Web-service Error", JOptionPane.ERROR_MESSAGE);
203 public void loadLocalCachedPDBEntries()
205 DefaultTableModel tableModel = new DefaultTableModel();
206 tableModel.addColumn("Sequence");
207 tableModel.addColumn("PDB Id");
208 tableModel.addColumn("Chain");
209 tableModel.addColumn("Type");
210 tableModel.addColumn("File");
211 cachedEntryMap = new Hashtable<String, PDBEntry>();
212 for (SequenceI seq : selectedSequences)
214 if (seq.getDatasetSequence() != null
215 && seq.getDatasetSequence().getPDBId() != null)
217 for (PDBEntry pdbEntry : seq.getDatasetSequence().getPDBId())
219 String chain = pdbEntry.getChainCode() == null ? "_" : pdbEntry
221 String[] pdbEntryRowData = new String[]
222 { seq.getDisplayId(false), pdbEntry.getId(),
225 pdbEntry.getFile() };
226 tableModel.addRow(pdbEntryRowData);
227 cachedEntryMap.put(seq.getDisplayId(false) + pdbEntry.getId(),
232 tbl_local_pdb.setModel(tableModel);
236 * Update the DBRef entry for a given sequence with values retrieved from
240 * the Sequence to update its DBRef entry
241 * @param responseSummaries
242 * a collection of PDBResponseSummary
244 public void updateSequenceDbRef(SequenceI seq,
245 Collection<PDBResponseSummary> responseSummaries)
247 for (PDBResponseSummary response : responseSummaries)
249 PDBEntry newEntry = new PDBEntry();
250 newEntry.setId(response.getPdbId());
251 newEntry.setType(PDBEntry.Type.PDB);
252 seq.getDatasetSequence().addPDBId(newEntry);
257 * Builds a query string for a given sequences using its DBRef entries
260 * the sequences to build a query for
261 * @return the built query string
264 public static String buildQuery(SequenceI seq)
266 HashSet<String> seqRefs = new LinkedHashSet<String>();
267 String seqName = seq.getName();
268 String[] names = seqName.toLowerCase().split("\\|");
269 for (String name : names)
271 // System.out.println("Found name : " + name);
273 if (isValidSeqName(name))
279 if (seq.getPDBId() != null)
281 for (PDBEntry entry : seq.getPDBId())
283 seqRefs.add(entry.getId());
287 if (seq.getDBRef() != null && seq.getDBRef().length != 0)
290 for (DBRefEntry dbRef : seq.getDBRef())
292 seqRefs.add(getDBRefId(dbRef));
301 StringBuilder queryBuilder = new StringBuilder();
302 for (String seqRef : seqRefs)
304 queryBuilder.append("text:").append(seqRef).append(" OR ");
306 int endIndex = queryBuilder.lastIndexOf(" OR ");
307 String query = queryBuilder.toString().substring(5, endIndex);
312 * Ensures sequence ref names are not less than 3 characters and does not
313 * contain a database name
318 public static boolean isValidSeqName(String seqName)
320 String ignoreList = "pdb,uniprot";
321 if (seqName.length() < 3)
325 for (String ignoredEntry : ignoreList.split(","))
327 if (seqName.equalsIgnoreCase(ignoredEntry))
335 public static String getDBRefId(DBRefEntry dbRef)
337 String ref = dbRef.getAccessionId().replaceAll("GO:", "");
342 * Filters a given list of discovered structures based on supplied argument
344 * @param fieldToFilterBy
345 * the field to filter by
347 public void filterResultSet(final String fieldToFilterBy)
349 Thread filterThread = new Thread(new Runnable()
354 long startTime = System.currentTimeMillis();
355 lbl_loading.setVisible(true);
356 Collection<PDBDocField> wantedFields = PDBDocFieldPreferences
357 .getStructureSummaryFields();
358 Collection<PDBResponseSummary> filteredResponse = new HashSet<PDBResponseSummary>();
359 HashSet<String> errors = new HashSet<String>();
360 for (SequenceI seq : selectedSequences)
362 PDBRestRequest pdbRequest = new PDBRestRequest();
363 pdbRequest.setAllowEmptySeq(false);
364 pdbRequest.setResponseSize(1);
365 pdbRequest.setFieldToSearchBy("(text:");
366 pdbRequest.setFieldToSortBy(fieldToFilterBy,
367 !chk_invertFilter.isSelected());
368 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
369 pdbRequest.setWantedFields(wantedFields);
370 pdbRequest.setAssociatedSequence(seq.getName());
371 pdbRestCleint = new PDBRestClient();
372 PDBRestResponse resultList;
375 resultList = pdbRestCleint.executeRequest(pdbRequest);
376 } catch (Exception e)
378 errors.add(e.getMessage());
381 lastPdbRequest = pdbRequest;
382 if (resultList.getSearchSummary() != null
383 && !resultList.getSearchSummary().isEmpty())
385 filteredResponse.addAll(resultList.getSearchSummary());
389 String totalTime = (System.currentTimeMillis() - startTime)
391 if (!filteredResponse.isEmpty())
393 final int filterResponseCount = filteredResponse.size();
394 Collection<PDBResponseSummary> reorderedStructuresSet = new LinkedHashSet<PDBResponseSummary>();
395 reorderedStructuresSet.addAll(filteredResponse);
396 reorderedStructuresSet.addAll(discoveredStructuresSet);
397 tbl_summary.setModel(PDBRestResponse.getTableModel(
398 lastPdbRequest, reorderedStructuresSet));
400 // Update table selection model here
401 tbl_summary.addRowSelectionInterval(0, filterResponseCount - 1);
403 mainFrame.setTitle("Structure Chooser - Filter time ("
408 mainFrame.setTitle("Structure Chooser - Filter time ("
410 if (errors.size() > 0)
412 StringBuilder errorMsg = new StringBuilder(
413 "Operation unsucessful due to the following: \n");
414 for (String error : errors)
416 errorMsg.append(error).append("\n");
418 JOptionPane.showMessageDialog(null, errorMsg.toString(),
419 "PDB Web-service Error", JOptionPane.ERROR_MESSAGE);
423 lbl_loading.setVisible(false);
425 validateSelections();
428 filterThread.start();
433 * Handles action event for btn_pdbFromFile
435 public void pdbFromFile_actionPerformed()
437 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
438 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
439 chooser.setFileView(new jalview.io.JalviewFileView());
440 chooser.setDialogTitle(MessageManager.formatMessage(
441 "label.select_pdb_file_for", new String[]
442 { selectedSequence.getDisplayId(false) }));
443 chooser.setToolTipText(MessageManager.formatMessage(
444 "label.load_pdb_file_associate_with_sequence", new String[]
445 { selectedSequence.getDisplayId(false) }));
447 int value = chooser.showOpenDialog(null);
448 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
450 selectedPdbFileName = chooser.getSelectedFile().getPath();
451 jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
452 validateSelections();
457 * Populates the filter combo-box options dynamically depending on discovered
460 protected void populateFilterComboBox()
462 if (isStructuresDiscovered())
464 cmb_filterOption.addItem(new FilterOption("Best Quality",
465 PDBDocField.OVERALL_QUALITY.getCode(), VIEWS_FILTER));
466 cmb_filterOption.addItem(new FilterOption("Best UniProt Coverage",
467 PDBDocField.UNIPROT_COVERAGE.getCode(), VIEWS_FILTER));
468 cmb_filterOption.addItem(new FilterOption("Highest Resolution",
469 PDBDocField.RESOLUTION.getCode(), VIEWS_FILTER));
470 cmb_filterOption.addItem(new FilterOption("Highest Protein Chain",
471 PDBDocField.PROTEIN_CHAIN_COUNT.getCode(), VIEWS_FILTER));
472 cmb_filterOption.addItem(new FilterOption("Highest Bound Molecules",
473 PDBDocField.BOUND_MOLECULE_COUNT.getCode(), VIEWS_FILTER));
474 cmb_filterOption.addItem(new FilterOption("Highest Polymer Residues",
475 PDBDocField.POLYMER_RESIDUE_COUNT.getCode(), VIEWS_FILTER));
477 cmb_filterOption.addItem(new FilterOption("Enter PDB Id", "-",
479 cmb_filterOption.addItem(new FilterOption("From File", "-",
481 cmb_filterOption.addItem(new FilterOption("Cached PDB Entries", "-",
486 * Updates the displayed view based on the selected filter option
488 protected void updateCurrentView()
490 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
492 layout_switchableViews.show(pnl_switchableViews,
493 selectedFilterOpt.getView());
494 String filterTitle = mainFrame.getTitle();
495 mainFrame.setTitle(frameTitle);
496 chk_invertFilter.setVisible(false);
497 if (selectedFilterOpt.getView() == VIEWS_FILTER)
499 mainFrame.setTitle(filterTitle);
500 chk_invertFilter.setVisible(true);
501 filterResultSet(selectedFilterOpt.getValue());
503 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
504 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
506 mainFrame.setTitle(filterTitle);
507 idInputAssSeqPanel.loadCmbAssSeq();
508 fileChooserAssSeqPanel.loadCmbAssSeq();
510 validateSelections();
514 * Validates user selection and activates the view button if all parameters
517 public void validateSelections()
519 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
521 btn_view.setEnabled(false);
522 String currentView = selectedFilterOpt.getView();
523 if (currentView == VIEWS_FILTER)
525 if (tbl_summary.getSelectedRows().length > 0)
527 btn_view.setEnabled(true);
530 else if (currentView == VIEWS_LOCAL_PDB)
532 if (tbl_local_pdb.getSelectedRows().length > 0)
534 btn_view.setEnabled(true);
537 else if (currentView == VIEWS_ENTER_ID)
539 validateAssociationEnterPdb();
541 else if (currentView == VIEWS_FROM_FILE)
543 validateAssociationFromFile();
548 * Validates inputs from the Manual PDB entry panel
550 public void validateAssociationEnterPdb()
552 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
553 .getCmb_assSeq().getSelectedItem();
554 lbl_pdbManualFetchStatus.setIcon(errorImage);
555 if (selectedSequences.length == 1
556 || !assSeqOpt.getName().equalsIgnoreCase(
557 "-Select Associated Seq-"))
559 txt_search.setEnabled(true);
562 btn_view.setEnabled(true);
563 lbl_pdbManualFetchStatus.setIcon(goodImage);
568 txt_search.setEnabled(false);
569 lbl_pdbManualFetchStatus.setIcon(errorImage);
574 * Validates inputs for the manual PDB file selection options
576 public void validateAssociationFromFile()
578 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
579 .getCmb_assSeq().getSelectedItem();
580 lbl_fromFileStatus.setIcon(errorImage);
581 if (selectedSequences.length == 1
582 || (assSeqOpt != null
583 && !assSeqOpt.getName().equalsIgnoreCase(
584 "-Select Associated Seq-")))
586 btn_pdbFromFile.setEnabled(true);
587 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
589 btn_view.setEnabled(true);
590 lbl_fromFileStatus.setIcon(goodImage);
595 btn_pdbFromFile.setEnabled(false);
596 lbl_fromFileStatus.setIcon(errorImage);
601 public void cmbAssSeqStateChanged()
603 validateSelections();
607 * Handles the state change event for the 'filter' combo-box and 'invert'
611 protected void stateChanged(ItemEvent e)
613 if (e.getSource() instanceof JCheckBox)
619 if (e.getStateChange() == ItemEvent.SELECTED)
628 * Handles action event for btn_ok
631 public void ok_ActionPerformed()
633 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
635 String currentView = selectedFilterOpt.getView();
636 if (currentView == VIEWS_FILTER)
638 int pdbIdCol = PDBRestClient.getPDBIdColumIndex(
639 lastPdbRequest.getWantedFields(), true);
640 int[] selectedRows = tbl_summary.getSelectedRows();
641 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
643 for (int summaryRow : selectedRows)
645 String pdbIdStr = tbl_summary.getValueAt(summaryRow, pdbIdCol)
647 PDBEntry pdbEntry = new PDBEntry();
648 pdbEntry.setId(pdbIdStr);
649 pdbEntry.setType(PDBEntry.Type.PDB);
650 pdbEntriesToView[count++] = pdbEntry;
653 launchStructureViewer(ap.getStructureSelectionManager(),
654 pdbEntriesToView, ap, selectedSequences);
656 else if(currentView == VIEWS_LOCAL_PDB){
657 int[] selectedRows = tbl_local_pdb.getSelectedRows();
658 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
660 for (int row : selectedRows)
662 String entryKey = tbl_local_pdb.getValueAt(row, 0).toString() + tbl_local_pdb.getValueAt(row, 1).toString();
663 pdbEntriesToView[count++] = cachedEntryMap.get(entryKey);
665 launchStructureViewer(ap.getStructureSelectionManager(),
666 pdbEntriesToView, ap, selectedSequences);
668 else if (currentView == VIEWS_ENTER_ID)
670 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
671 .getCmb_assSeq().getSelectedItem()).getSequence();
672 if (userSelectedSeq != null)
674 selectedSequence = userSelectedSeq;
676 PDBEntry pdbEntry = new PDBEntry();
677 pdbEntry.setId(txt_search.getText());
678 pdbEntry.setType(PDBEntry.Type.PDB);
679 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
680 PDBEntry[] pdbEntriesToView = new PDBEntry[]
682 launchStructureViewer(ap.getStructureSelectionManager(),
683 pdbEntriesToView, ap, new SequenceI[]
684 { selectedSequence });
686 else if (currentView == VIEWS_FROM_FILE)
688 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
689 .getCmb_assSeq().getSelectedItem()).getSequence();
690 if (userSelectedSeq != null)
692 selectedSequence = userSelectedSeq;
694 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
695 .associatePdbWithSeq(
696 selectedPdbFileName, jalview.io.AppletFormatAdapter.FILE,
697 selectedSequence, true, Desktop.instance);
699 launchStructureViewer(ap.getStructureSelectionManager(),
701 { fileEntry }, ap, new SequenceI[]
702 { selectedSequence });
707 private void launchStructureViewer(StructureSelectionManager ssm,
708 PDBEntry[] pdbEntriesToView, AlignmentPanel alignPanel,
709 SequenceI[] selectedSequences)
711 StructureViewer sViewer = new StructureViewer(ssm);
712 if (pdbEntriesToView.length > 1)
714 sViewer.viewStructures(alignPanel, pdbEntriesToView,
715 alignPanel.av.collateForPDB(pdbEntriesToView));
719 sViewer.viewStructures(pdbEntriesToView[0], selectedSequences, null,
725 * Populates the combo-box used in associating manually fetched structures to
726 * a unique sequence when more than one sequence selection is made.
728 public void populateCmbAssociateSeqOptions(
729 JComboBox<AssociateSeqOptions> cmb_assSeq, JLabel lbl_associateSeq)
731 cmb_assSeq.removeAllItems();
732 cmb_assSeq.addItem(new AssociateSeqOptions("-Select Associated Seq-",
734 // cmb_assSeq.addItem(new AssociateSeqOptions("Auto Detect", null));
735 lbl_associateSeq.setVisible(false);
736 if (selectedSequences.length > 1)
738 for (SequenceI seq : selectedSequences)
740 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
745 String seqName = selectedSequence.getDisplayId(false);
746 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
747 lbl_associateSeq.setText(seqName);
748 lbl_associateSeq.setVisible(true);
749 cmb_assSeq.setVisible(false);
753 public boolean isStructuresDiscovered()
755 return structuresDiscovered;
758 public void setStructuresDiscovered(boolean structuresDiscovered)
760 this.structuresDiscovered = structuresDiscovered;
763 public Collection<PDBResponseSummary> getDiscoveredStructuresSet()
765 return discoveredStructuresSet;
769 protected void txt_search_ActionPerformed()
771 isValidPBDEntry = false;
772 if (txt_search.getText().length() > 0)
774 List<PDBDocField> wantedFields = new ArrayList<PDBDocField>();
775 wantedFields.add(PDBDocField.PDB_ID);
776 PDBRestRequest pdbRequest = new PDBRestRequest();
777 pdbRequest.setAllowEmptySeq(false);
778 pdbRequest.setResponseSize(1);
779 pdbRequest.setFieldToSearchBy("(pdb_id:");
780 pdbRequest.setWantedFields(wantedFields);
781 pdbRequest.setSearchTerm(txt_search.getText() + ")");
782 pdbRequest.setAssociatedSequence(selectedSequence.getName());
783 pdbRestCleint = new PDBRestClient();
784 PDBRestResponse resultList;
787 resultList = pdbRestCleint.executeRequest(pdbRequest);
788 } catch (Exception e)
790 JOptionPane.showMessageDialog(this, e.getMessage(),
791 "PDB Web-service Error", JOptionPane.ERROR_MESSAGE);
795 System.out.println(">>>>> executing finally block");
796 validateSelections();
798 if (resultList.getSearchSummary() != null
799 && resultList.getSearchSummary().size() > 0)
801 isValidPBDEntry = true;
804 validateSelections();
808 public void tabRefresh()
810 if (selectedSequences != null)
812 Thread refreshThread = new Thread(new Runnable()
817 fetchStructuresMetaData();
818 filterResultSet(((FilterOption) cmb_filterOption
819 .getSelectedItem()).getValue());
822 refreshThread.start();