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.table.DefaultTableModel;
53 * Provides the behaviors for the Structure chooser Panel
58 @SuppressWarnings("serial")
59 public class StructureChooser extends GStructureChooser
61 private boolean structuresDiscovered = false;
63 private SequenceI selectedSequence;
65 private SequenceI[] selectedSequences;
67 private IProgressIndicator progressIndicator;
69 private Collection<PDBResponseSummary> discoveredStructuresSet;
71 private PDBRestRequest lastPdbRequest;
73 private PDBRestClient pdbRestCleint;
75 private String selectedPdbFileName;
77 private boolean isValidPBDEntry;
79 private static Hashtable<String, PDBEntry> cachedEntryMap;
81 public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
85 this.selectedSequence = selectedSeq;
86 this.selectedSequences = selectedSeqs;
87 this.progressIndicator = (ap == null) ? null : ap.alignFrame;
92 * Initializes parameters used by the Structure Chooser Panel
96 Thread discoverPDBStructuresThread = new Thread(new Runnable()
101 long startTime = System.currentTimeMillis();
102 String msg = MessageManager.getString("status.fetching_db_refs");
103 updateProgressIndicator(msg, startTime);
104 loadLocalCachedPDBEntries();
105 fetchStructuresMetaData();
106 populateFilterComboBox();
107 updateProgressIndicator(null, startTime);
108 mainFrame.setVisible(true);
112 discoverPDBStructuresThread.start();
116 * Updates the progress indicator with the specified message
119 * displayed message for the operation
121 * unique handle for this indicator
123 public void updateProgressIndicator(String message, long id)
125 if (progressIndicator != null)
127 progressIndicator.setProgressBar(message, id);
132 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
135 public void fetchStructuresMetaData()
137 long startTime = System.currentTimeMillis();
138 Collection<PDBDocField> wantedFields = PDBDocFieldPreferences
139 .getStructureSummaryFields();
141 discoveredStructuresSet = new LinkedHashSet<PDBResponseSummary>();
142 for (SequenceI seq : selectedSequences)
144 PDBRestRequest pdbRequest = new PDBRestRequest();
145 pdbRequest.setAllowEmptySeq(false);
146 pdbRequest.setResponseSize(500);
147 pdbRequest.setFieldToSearchBy("(text:");
148 pdbRequest.setWantedFields(wantedFields);
149 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
150 pdbRequest.setAssociatedSequence(seq.getName());
151 pdbRestCleint = new PDBRestClient();
152 PDBRestResponse resultList = pdbRestCleint.executeRequest(pdbRequest);
153 lastPdbRequest = pdbRequest;
154 if (resultList.getSearchSummary() != null
155 && !resultList.getSearchSummary().isEmpty())
157 discoveredStructuresSet.addAll(resultList.getSearchSummary());
158 updateSequenceDbRef(seq, resultList.getSearchSummary());
162 int noOfStructuresFound = 0;
163 if (discoveredStructuresSet != null
164 && !discoveredStructuresSet.isEmpty())
166 tbl_summary.setModel(PDBRestResponse.getTableModel(lastPdbRequest,
167 discoveredStructuresSet));
168 structuresDiscovered = true;
169 noOfStructuresFound = discoveredStructuresSet.size();
171 String totalTime = (System.currentTimeMillis() - startTime)
173 mainFrame.setTitle("Structure Chooser - " + noOfStructuresFound
174 + " Found (" + totalTime + ")");
177 public void loadLocalCachedPDBEntries()
179 DefaultTableModel tableModel = new DefaultTableModel();
180 tableModel.addColumn("Sequence");
181 tableModel.addColumn("PDB Id");
182 tableModel.addColumn("Type");
183 tableModel.addColumn("File");
184 cachedEntryMap = new Hashtable<String, PDBEntry>();
185 for (SequenceI seq : selectedSequences)
187 if (seq.getDatasetSequence() != null
188 && seq.getDatasetSequence().getPDBId() != null)
190 for (PDBEntry pdbEntry : seq.getDatasetSequence().getPDBId())
192 String[] pdbEntryRowData = new String[]
193 { seq.getDisplayId(false), pdbEntry.getId(), pdbEntry.getType(),
194 pdbEntry.getFile() };
195 tableModel.addRow(pdbEntryRowData);
196 cachedEntryMap.put(seq.getDisplayId(false) + pdbEntry.getId(),
201 tbl_local_pdb.setModel(tableModel);
205 * Update the DBRef entry for a given sequence with values retrieved from
209 * the Sequence to update its DBRef entry
210 * @param responseSummaries
211 * a collection of PDBResponseSummary
213 public void updateSequenceDbRef(SequenceI seq,
214 Collection<PDBResponseSummary> responseSummaries)
216 for (PDBResponseSummary response : responseSummaries)
218 PDBEntry newEntry = new PDBEntry();
219 newEntry.setId(response.getPdbId());
220 newEntry.setType("PDB");
221 seq.getDatasetSequence().addPDBId(newEntry);
226 * Builds a query string for a given sequences using its DBRef entries
229 * the sequences to build a query for
230 * @return the built query string
233 public static String buildQuery(SequenceI seq)
235 String query = seq.getName();
236 StringBuilder queryBuilder = new StringBuilder();
239 if (seq.getPDBId() != null)
241 for (PDBEntry entry : seq.getPDBId())
243 queryBuilder.append("text:").append(entry.getId()).append(" OR ");
247 if (seq.getDBRef() != null && seq.getDBRef().length != 0)
249 for (DBRefEntry dbRef : seq.getDBRef())
251 queryBuilder.append("text:")
252 .append(dbRef.getAccessionId().replaceAll("GO:", ""))
260 int endIndex = queryBuilder.lastIndexOf(" OR ");
261 query = queryBuilder.toString().substring(5, endIndex);
267 * Filters a given list of discovered structures based on supplied argument
269 * @param fieldToFilterBy
270 * the field to filter by
272 public void filterResultSet(final String fieldToFilterBy)
274 Thread filterThread = new Thread(new Runnable()
279 long startTime = System.currentTimeMillis();
282 lbl_loading.setVisible(true);
284 Collection<PDBDocField> wantedFields = PDBDocFieldPreferences
285 .getStructureSummaryFields();
286 Collection<PDBResponseSummary> filteredResponse = new HashSet<PDBResponseSummary>();
287 for (SequenceI seq : selectedSequences)
289 PDBRestRequest pdbRequest = new PDBRestRequest();
290 pdbRequest.setAllowEmptySeq(false);
291 pdbRequest.setResponseSize(1);
292 pdbRequest.setFieldToSearchBy("(text:");
293 pdbRequest.setFieldToSortBy(fieldToFilterBy,
294 !chk_invertFilter.isSelected());
295 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
296 pdbRequest.setWantedFields(wantedFields);
297 pdbRequest.setAssociatedSequence(seq.getName());
298 pdbRestCleint = new PDBRestClient();
299 PDBRestResponse resultList = pdbRestCleint
300 .executeRequest(pdbRequest);
301 lastPdbRequest = pdbRequest;
302 if (resultList.getSearchSummary() != null
303 && !resultList.getSearchSummary().isEmpty())
305 filteredResponse.addAll(resultList.getSearchSummary());
309 if (!filteredResponse.isEmpty())
311 final int filterResponseCount = filteredResponse.size();
312 Collection<PDBResponseSummary> reorderedStructuresSet = new LinkedHashSet<PDBResponseSummary>();
313 reorderedStructuresSet.addAll(filteredResponse);
314 reorderedStructuresSet.addAll(discoveredStructuresSet);
315 tbl_summary.setModel(PDBRestResponse.getTableModel(
316 lastPdbRequest, reorderedStructuresSet));
318 // Update table selection model here
319 tbl_summary.addRowSelectionInterval(0, filterResponseCount - 1);
323 lbl_loading.setVisible(false);
324 String totalTime = (System.currentTimeMillis() - startTime)
326 mainFrame.setTitle("Structure Chooser - Filter time ("
329 validateSelections();
330 } catch (Exception e)
336 filterThread.start();
341 * Handles action event for btn_pdbFromFile
343 public void pdbFromFile_actionPerformed()
345 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
346 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
347 chooser.setFileView(new jalview.io.JalviewFileView());
348 chooser.setDialogTitle(MessageManager.formatMessage(
349 "label.select_pdb_file_for", new String[]
350 { selectedSequence.getDisplayId(false) }));
351 chooser.setToolTipText(MessageManager.formatMessage(
352 "label.load_pdb_file_associate_with_sequence", new String[]
353 { selectedSequence.getDisplayId(false) }));
355 int value = chooser.showOpenDialog(null);
356 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
358 selectedPdbFileName = chooser.getSelectedFile().getPath();
359 jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
360 validateSelections();
365 * Populates the filter combo-box options dynamically depending on discovered
368 protected void populateFilterComboBox()
370 if (isStructuresDiscovered())
372 cmb_filterOption.addItem(new FilterOption("Best Quality",
373 PDBDocField.OVERALL_QUALITY.getCode(), VIEWS_FILTER));
374 cmb_filterOption.addItem(new FilterOption("Best UniProt Coverage",
375 PDBDocField.UNIPROT_COVERAGE.getCode(), VIEWS_FILTER));
376 cmb_filterOption.addItem(new FilterOption("Highest Resolution",
377 PDBDocField.RESOLUTION.getCode(), VIEWS_FILTER));
378 cmb_filterOption.addItem(new FilterOption("Highest Protein Chain",
379 PDBDocField.PROTEIN_CHAIN_COUNT.getCode(), VIEWS_FILTER));
380 cmb_filterOption.addItem(new FilterOption("Highest Bound Molecules",
381 PDBDocField.BOUND_MOLECULE_COUNT.getCode(), VIEWS_FILTER));
382 cmb_filterOption.addItem(new FilterOption("Highest Polymer Residues",
383 PDBDocField.POLYMER_RESIDUE_COUNT.getCode(), VIEWS_FILTER));
385 cmb_filterOption.addItem(new FilterOption("Enter PDB Id", "-",
387 cmb_filterOption.addItem(new FilterOption("From File", "-",
389 cmb_filterOption.addItem(new FilterOption("Cached PDB Entries", "-",
394 * Updates the displayed view based on the selected filter option
396 protected void updateCurrentView()
398 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
400 layout_switchableViews.show(pnl_switchableViews,
401 selectedFilterOpt.getView());
402 String filterTitle = mainFrame.getTitle();
403 mainFrame.setTitle(frameTitle);
404 chk_invertFilter.setVisible(false);
405 if (selectedFilterOpt.getView() == VIEWS_FILTER)
407 mainFrame.setTitle(filterTitle);
408 chk_invertFilter.setVisible(true);
409 filterResultSet(selectedFilterOpt.getValue());
411 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
412 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
414 idInputAssSeqPanel.loadCmbAssSeq();
415 fileChooserAssSeqPanel.loadCmbAssSeq();
417 validateSelections();
421 * Validates user selection and activates the view button if all parameters
424 public void validateSelections()
426 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
428 btn_view.setEnabled(false);
429 String currentView = selectedFilterOpt.getView();
430 if (currentView == VIEWS_FILTER)
432 if (tbl_summary.getSelectedRows().length > 0)
434 btn_view.setEnabled(true);
437 else if (currentView == VIEWS_LOCAL_PDB)
439 if (tbl_local_pdb.getSelectedRows().length > 0)
441 btn_view.setEnabled(true);
444 else if (currentView == VIEWS_ENTER_ID)
446 validateAssociationEnterPdb();
448 else if (currentView == VIEWS_FROM_FILE)
450 validateAssociationFromFile();
455 * Validates inputs from the Manual PDB entry panel
457 public void validateAssociationEnterPdb()
459 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
460 .getCmb_assSeq().getSelectedItem();
461 lbl_pdbManualFetchStatus.setIcon(errorImage);
462 if (selectedSequences.length == 1
463 || !assSeqOpt.getName().equalsIgnoreCase(
464 "-Select Associated Seq-"))
466 txt_search.setEnabled(true);
469 btn_view.setEnabled(true);
470 lbl_pdbManualFetchStatus.setIcon(goodImage);
475 txt_search.setEnabled(false);
476 lbl_pdbManualFetchStatus.setIcon(errorImage);
481 * Validates inputs for the manual PDB file selection options
483 public void validateAssociationFromFile()
485 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
486 .getCmb_assSeq().getSelectedItem();
487 lbl_fromFileStatus.setIcon(errorImage);
488 if (selectedSequences.length == 1
489 || (assSeqOpt != null
490 && !assSeqOpt.getName().equalsIgnoreCase(
491 "-Select Associated Seq-")))
493 btn_pdbFromFile.setEnabled(true);
494 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
496 btn_view.setEnabled(true);
497 lbl_fromFileStatus.setIcon(goodImage);
502 btn_pdbFromFile.setEnabled(false);
503 lbl_fromFileStatus.setIcon(errorImage);
508 public void cmbAssSeqStateChanged()
510 validateSelections();
514 * Handles the state change event for the 'filter' combo-box and 'invert'
518 protected void stateChanged(ItemEvent e)
520 if (e.getSource() instanceof JCheckBox)
526 if (e.getStateChange() == ItemEvent.SELECTED)
535 * Handles action event for btn_ok
538 public void ok_ActionPerformed()
540 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
542 String currentView = selectedFilterOpt.getView();
543 if (currentView == VIEWS_FILTER)
545 int pdbIdCol = PDBRestClient.getPDBIdColumIndex(
546 lastPdbRequest.getWantedFields(), true);
547 int[] selectedRows = tbl_summary.getSelectedRows();
548 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
550 for (int summaryRow : selectedRows)
552 String pdbIdStr = tbl_summary.getValueAt(summaryRow, pdbIdCol)
554 PDBEntry pdbEntry = new PDBEntry();
555 pdbEntry.setId(pdbIdStr);
556 pdbEntry.setType("PDB");
557 pdbEntriesToView[count++] = pdbEntry;
560 launchStructureViewer(ap.getStructureSelectionManager(),
561 pdbEntriesToView, ap, selectedSequences);
563 else if(currentView == VIEWS_LOCAL_PDB){
564 int[] selectedRows = tbl_local_pdb.getSelectedRows();
565 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
567 for (int row : selectedRows)
569 String entryKey = tbl_local_pdb.getValueAt(row, 0).toString() + tbl_local_pdb.getValueAt(row, 1).toString();
570 pdbEntriesToView[count++] = cachedEntryMap.get(entryKey);
572 launchStructureViewer(ap.getStructureSelectionManager(),
573 pdbEntriesToView, ap, selectedSequences);
575 else if (currentView == VIEWS_ENTER_ID)
577 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
578 .getCmb_assSeq().getSelectedItem()).getSequence();
579 if (userSelectedSeq != null)
581 selectedSequence = userSelectedSeq;
583 PDBEntry pdbEntry = new PDBEntry();
584 pdbEntry.setId(txt_search.getText());
585 pdbEntry.setType("PDB");
586 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
587 PDBEntry[] pdbEntriesToView = new PDBEntry[]
589 launchStructureViewer(ap.getStructureSelectionManager(),
590 pdbEntriesToView, ap, new SequenceI[]
591 { selectedSequence });
593 else if (currentView == VIEWS_FROM_FILE)
595 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
596 .getCmb_assSeq().getSelectedItem()).getSequence();
597 if (userSelectedSeq != null)
599 selectedSequence = userSelectedSeq;
601 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
602 .associatePdbWithSeq(
603 selectedPdbFileName, jalview.io.AppletFormatAdapter.FILE,
604 selectedSequence, true, Desktop.instance);
606 launchStructureViewer(ap.getStructureSelectionManager(),
608 { fileEntry }, ap, new SequenceI[]
609 { selectedSequence });
614 private void launchStructureViewer(StructureSelectionManager ssm,
615 PDBEntry[] pdbEntriesToView, AlignmentPanel alignPanel,
616 SequenceI[] selectedSequences)
618 StructureViewer sViewer = new StructureViewer(ssm);
619 if (pdbEntriesToView.length > 1)
621 sViewer.viewStructures(alignPanel, pdbEntriesToView,
622 alignPanel.av.collateForPDB(pdbEntriesToView));
626 sViewer.viewStructures(pdbEntriesToView[0], selectedSequences, null,
632 * Populates the combo-box used in associating manually fetched structures to
633 * a unique sequence when more than one sequence selection is made.
635 public void populateCmbAssociateSeqOptions(
636 JComboBox<AssociateSeqOptions> cmb_assSeq, JLabel lbl_associateSeq)
638 cmb_assSeq.removeAllItems();
639 cmb_assSeq.addItem(new AssociateSeqOptions("-Select Associated Seq-",
641 // cmb_assSeq.addItem(new AssociateSeqOptions("Auto Detect", null));
642 lbl_associateSeq.setVisible(false);
643 if (selectedSequences.length > 1)
645 for (SequenceI seq : selectedSequences)
647 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
652 String seqName = selectedSequence.getDisplayId(false);
653 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
654 lbl_associateSeq.setText(seqName);
655 lbl_associateSeq.setVisible(true);
656 cmb_assSeq.setVisible(false);
660 public boolean isStructuresDiscovered()
662 return structuresDiscovered;
665 public void setStructuresDiscovered(boolean structuresDiscovered)
667 this.structuresDiscovered = structuresDiscovered;
670 public Collection<PDBResponseSummary> getDiscoveredStructuresSet()
672 return discoveredStructuresSet;
676 protected void txt_search_ActionPerformed()
678 isValidPBDEntry = false;
679 if (txt_search.getText().length() > 0)
681 List<PDBDocField> wantedFields = new ArrayList<PDBDocField>();
682 wantedFields.add(PDBDocField.PDB_ID);
683 PDBRestRequest pdbRequest = new PDBRestRequest();
684 pdbRequest.setAllowEmptySeq(false);
685 pdbRequest.setResponseSize(1);
686 pdbRequest.setFieldToSearchBy("(pdb_id:");
687 pdbRequest.setWantedFields(wantedFields);
688 pdbRequest.setSearchTerm(txt_search.getText() + ")");
689 pdbRequest.setAssociatedSequence(selectedSequence.getName());
690 pdbRestCleint = new PDBRestClient();
691 PDBRestResponse resultList = pdbRestCleint.executeRequest(pdbRequest);
692 if (resultList.getSearchSummary() != null
693 && resultList.getSearchSummary().size() > 0)
695 isValidPBDEntry = true;
698 validateSelections();
702 public void tabRefresh()
704 if (selectedSequences != null)
706 Thread refreshThread = new Thread(new Runnable()
711 fetchStructuresMetaData();
712 filterResultSet(((FilterOption) cmb_filterOption
713 .getSelectedItem()).getValue());
716 refreshThread.start();