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.util.MessageManager;
31 import jalview.ws.dbsources.PDBRestClient;
32 import jalview.ws.dbsources.PDBRestClient.PDBDocField;
33 import jalview.ws.uimodel.PDBRestRequest;
34 import jalview.ws.uimodel.PDBRestResponse;
35 import jalview.ws.uimodel.PDBRestResponse.PDBResponseSummary;
37 import java.awt.event.ItemEvent;
38 import java.util.ArrayList;
39 import java.util.Collection;
40 import java.util.HashSet;
41 import java.util.LinkedHashSet;
42 import java.util.List;
43 import java.util.Vector;
45 import javax.swing.JCheckBox;
46 import javax.swing.JComboBox;
47 import javax.swing.JLabel;
50 * Provides the behaviors for the Structure chooser Panel
55 @SuppressWarnings("serial")
56 public class StructureChooser extends GStructureChooser
58 private boolean structuresDiscovered = false;
60 private SequenceI selectedSequence;
62 private SequenceI[] selectedSequences;
64 private IProgressIndicator progressIndicator;
66 private Collection<PDBResponseSummary> discoveredStructuresSet;
68 private PDBRestRequest lastPdbRequest;
70 private PDBRestClient pdbRestCleint;
72 private String selectedPdbFileName;
74 private boolean isValidPBDEntry;
76 public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
80 this.selectedSequence = selectedSeq;
81 this.selectedSequences = selectedSeqs;
82 this.progressIndicator = (ap == null) ? null : ap.alignFrame;
87 * Initializes parameters used by the Structure Chooser Panel
91 Thread discoverPDBStructuresThread = new Thread(new Runnable()
96 long startTime = System.currentTimeMillis();
97 String msg = MessageManager.getString("status.fetching_db_refs");
98 updateProgressIndicator(msg, startTime);
99 fetchStructuresMetaData();
100 populateFilterComboBox();
101 updateProgressIndicator(null, startTime);
102 mainFrame.setVisible(true);
106 discoverPDBStructuresThread.start();
110 * Updates the progress indicator with the specified message
113 * displayed message for the operation
115 * unique handle for this indicator
117 public void updateProgressIndicator(String message, long id)
119 if (progressIndicator != null)
121 progressIndicator.setProgressBar(message, id);
126 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
129 public void fetchStructuresMetaData()
131 long startTime = System.currentTimeMillis();
132 Collection<PDBDocField> wantedFields = PDBDocFieldPreferences
133 .getStructureSummaryFields();
135 discoveredStructuresSet = new LinkedHashSet<PDBResponseSummary>();
136 for (SequenceI seq : selectedSequences)
138 PDBRestRequest pdbRequest = new PDBRestRequest();
139 pdbRequest.setAllowEmptySeq(false);
140 pdbRequest.setResponseSize(500);
141 pdbRequest.setFieldToSearchBy("(text:");
142 pdbRequest.setWantedFields(wantedFields);
143 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
144 pdbRequest.setAssociatedSequence(seq.getName());
145 pdbRestCleint = new PDBRestClient();
146 PDBRestResponse resultList = pdbRestCleint.executeRequest(pdbRequest);
147 lastPdbRequest = pdbRequest;
148 if (resultList.getSearchSummary() != null
149 && !resultList.getSearchSummary().isEmpty())
151 discoveredStructuresSet.addAll(resultList.getSearchSummary());
152 updateSequenceDbRef(seq, resultList.getSearchSummary());
156 int noOfStructuresFound = 0;
157 if (discoveredStructuresSet != null
158 && !discoveredStructuresSet.isEmpty())
160 tbl_summary.setModel(PDBRestResponse.getTableModel(lastPdbRequest,
161 discoveredStructuresSet));
162 structuresDiscovered = true;
163 noOfStructuresFound = discoveredStructuresSet.size();
165 String totalTime = (System.currentTimeMillis() - startTime)
167 mainFrame.setTitle("Structure Chooser - " + noOfStructuresFound
168 + " Found (" + totalTime + ")");
172 * Update the DBRef entry for a given sequence with values retrieved from
176 * the Sequence to update its DBRef entry
177 * @param responseSummaries
178 * a collection of PDBResponseSummary
180 public void updateSequenceDbRef(SequenceI seq,
181 Collection<PDBResponseSummary> responseSummaries)
183 for (PDBResponseSummary response : responseSummaries)
185 PDBEntry newEntry = new PDBEntry();
186 newEntry.setId(response.getPdbId());
187 newEntry.setType("PDB");
188 seq.getDatasetSequence().addPDBId(newEntry);
193 * Builds a query string for a given sequences using its DBRef entries
196 * the sequences to build a query for
197 * @return the built query string
199 @SuppressWarnings("unchecked")
200 public static String buildQuery(SequenceI seq)
202 String query = seq.getName();
203 StringBuilder queryBuilder = new StringBuilder();
206 if (seq.getPDBId() != null)
208 for (PDBEntry entry : (Vector<PDBEntry>) seq.getPDBId())
210 queryBuilder.append("text:").append(entry.getId()).append(" OR ");
214 if (seq.getDBRef() != null && seq.getDBRef().length != 0)
216 for (DBRefEntry dbRef : seq.getDBRef())
218 queryBuilder.append("text:")
219 .append(dbRef.getAccessionId().replaceAll("GO:", ""))
227 int endIndex = queryBuilder.lastIndexOf(" OR ");
228 query = queryBuilder.toString().substring(5, endIndex);
234 * Filters a given list of discovered structures based on supplied argument
236 * @param fieldToFilterBy
237 * the field to filter by
239 public void filterResultSet(final String fieldToFilterBy)
242 // SwingWorker aWorker = new SwingWorker()
244 // long startTime = System.currentTimeMillis();
247 // protected Object doInBackground() throws Exception
249 // lbl_loading.setVisible(true);
251 // Collection<PDBDocField> wantedFields = PDBDocFieldPreferences
252 // .getStructureSummaryFields();
253 // Collection<PDBResponseSummary> filteredResponse = new
254 // HashSet<PDBResponseSummary>();
255 // for (SequenceI seq : selectedSequences)
257 // PDBRestRequest pdbRequest = new PDBRestRequest();
258 // pdbRequest.setAllowEmptySeq(false);
259 // pdbRequest.setResponseSize(1);
260 // pdbRequest.setFieldToSearchBy("(text:");
261 // pdbRequest.setFieldToSortBy(fieldToFilterBy,
262 // !chk_invertFilter.isSelected());
263 // pdbRequest.setSearchTerm(buildQuery(seq) + ")");
264 // pdbRequest.setWantedFields(wantedFields);
265 // pdbRequest.setAssociatedSequence(seq.getName());
266 // pdbRestCleint = new PDBRestClient();
267 // PDBRestResponse resultList = pdbRestCleint
268 // .executeRequest(pdbRequest);
269 // lastPdbRequest = pdbRequest;
270 // if (resultList.getSearchSummary() != null
271 // && !resultList.getSearchSummary().isEmpty())
273 // filteredResponse.addAll(resultList.getSearchSummary());
277 // if (!filteredResponse.isEmpty())
279 // final int filterResponseCount = filteredResponse.size();
280 // Collection<PDBResponseSummary> reorderedStructuresSet = new
281 // LinkedHashSet<PDBResponseSummary>();
282 // reorderedStructuresSet.addAll(filteredResponse);
283 // reorderedStructuresSet.addAll(discoveredStructuresSet);
284 // tbl_summary.setModel(PDBRestResponse.getTableModel(
285 // lastPdbRequest, reorderedStructuresSet));
287 // // Update the model here
288 // // ListSelectionModel model = tbl_summary.getSelectionModel();
289 // // model.clearSelection();
290 // // model.addSelectionInterval(0, filterResponseCount - 1);
291 // // EventQueue.invokeLater(new Runnable()
293 // // public void run()
295 // // tbl_summary.addRowSelectionInterval(0, filterResponseCount - 1);
299 // // Discard unwanted objects to make them eligible for garbage
301 // reorderedStructuresSet = null;
306 // public void done()
308 // lbl_loading.setVisible(false);
309 // tbl_summary.addRowSelectionInterval(0, 2);
310 // String totalTime = (System.currentTimeMillis() - startTime)
312 // mainFrame.setTitle("Structure Chooser - Filter time (" + totalTime
314 // validateSelections();
317 // aWorker.execute();
319 Thread filterThread = new Thread(new Runnable()
324 long startTime = System.currentTimeMillis();
327 lbl_loading.setVisible(true);
329 Collection<PDBDocField> wantedFields = PDBDocFieldPreferences
330 .getStructureSummaryFields();
331 Collection<PDBResponseSummary> filteredResponse = new HashSet<PDBResponseSummary>();
332 for (SequenceI seq : selectedSequences)
334 PDBRestRequest pdbRequest = new PDBRestRequest();
335 pdbRequest.setAllowEmptySeq(false);
336 pdbRequest.setResponseSize(1);
337 pdbRequest.setFieldToSearchBy("(text:");
338 pdbRequest.setFieldToSortBy(fieldToFilterBy,
339 !chk_invertFilter.isSelected());
340 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
341 pdbRequest.setWantedFields(wantedFields);
342 pdbRequest.setAssociatedSequence(seq.getName());
343 pdbRestCleint = new PDBRestClient();
344 PDBRestResponse resultList = pdbRestCleint
345 .executeRequest(pdbRequest);
346 lastPdbRequest = pdbRequest;
347 if (resultList.getSearchSummary() != null
348 && !resultList.getSearchSummary().isEmpty())
350 filteredResponse.addAll(resultList.getSearchSummary());
354 if (!filteredResponse.isEmpty())
356 final int filterResponseCount = filteredResponse.size();
357 Collection<PDBResponseSummary> reorderedStructuresSet = new LinkedHashSet<PDBResponseSummary>();
358 reorderedStructuresSet.addAll(filteredResponse);
359 reorderedStructuresSet.addAll(discoveredStructuresSet);
360 tbl_summary.setModel(PDBRestResponse.getTableModel(
361 lastPdbRequest, reorderedStructuresSet));
363 // Update the model here
364 // ListSelectionModel model = tbl_summary.getSelectionModel();
365 // model.clearSelection();
366 // model.addSelectionInterval(0, filterResponseCount - 1);
367 // EventQueue.invokeLater(new Runnable()
371 tbl_summary.addRowSelectionInterval(0, filterResponseCount - 1);
375 // Discard unwanted objects to make them eligible for garbage
377 reorderedStructuresSet = null;
380 lbl_loading.setVisible(false);
381 String totalTime = (System.currentTimeMillis() - startTime)
383 mainFrame.setTitle("Structure Chooser - Filter time ("
386 validateSelections();
387 } catch (Exception e)
393 filterThread.start();
398 * Handles action event for btn_pdbFromFile
400 public void pdbFromFile_actionPerformed()
402 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
403 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
404 chooser.setFileView(new jalview.io.JalviewFileView());
405 chooser.setDialogTitle(MessageManager.formatMessage(
406 "label.select_pdb_file_for", new String[]
407 { selectedSequence.getDisplayId(false) }));
408 chooser.setToolTipText(MessageManager.formatMessage(
409 "label.load_pdb_file_associate_with_sequence", new String[]
410 { selectedSequence.getDisplayId(false) }));
412 int value = chooser.showOpenDialog(null);
413 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
415 selectedPdbFileName = chooser.getSelectedFile().getPath();
416 jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
417 validateSelections();
422 * Populates the filter combo-box options dynamically depending on discovered
425 protected void populateFilterComboBox()
427 if (isStructuresDiscovered())
429 cmb_filterOption.addItem(new FilterOption("Best Quality",
430 PDBDocField.OVERALL_QUALITY.getCode(), VIEWS_FILTER));
431 cmb_filterOption.addItem(new FilterOption("Best UniProt Coverage",
432 PDBDocField.UNIPROT_COVERAGE.getCode(), VIEWS_FILTER));
433 cmb_filterOption.addItem(new FilterOption("Highest Resolution",
434 PDBDocField.RESOLUTION.getCode(), VIEWS_FILTER));
435 cmb_filterOption.addItem(new FilterOption("Highest Protein Chain",
436 PDBDocField.PROTEIN_CHAIN_COUNT.getCode(), VIEWS_FILTER));
437 cmb_filterOption.addItem(new FilterOption("Highest Bound Molecules",
438 PDBDocField.BOUND_MOLECULE_COUNT.getCode(), VIEWS_FILTER));
439 cmb_filterOption.addItem(new FilterOption("Highest Polymer Residues",
440 PDBDocField.POLYMER_RESIDUE_COUNT.getCode(), VIEWS_FILTER));
442 cmb_filterOption.addItem(new FilterOption("Enter PDB Id", "-",
444 cmb_filterOption.addItem(new FilterOption("From File", "-",
449 * Updates the displayed view based on the selected filter option
451 protected void updateCurrentView()
453 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
455 layout_switchableViews.show(pnl_switchableViews,
456 selectedFilterOpt.getView());
457 String filterTitle = mainFrame.getTitle();
458 mainFrame.setTitle(frameTitle);
459 chk_invertFilter.setVisible(false);
460 if (selectedFilterOpt.getView() == VIEWS_FILTER)
462 mainFrame.setTitle(filterTitle);
463 chk_invertFilter.setVisible(true);
464 filterResultSet(selectedFilterOpt.getValue());
468 idInputAssSeqPanel.loadCmbAssSeq();
469 fileChooserAssSeqPanel.loadCmbAssSeq();
471 validateSelections();
475 * Validates user selection and activates the view button if all parameters
478 public void validateSelections()
480 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
482 btn_view.setEnabled(false);
483 String currentView = selectedFilterOpt.getView();
484 if (currentView == VIEWS_FILTER)
486 if (tbl_summary.getSelectedRows().length > 0)
488 btn_view.setEnabled(true);
491 else if (currentView == VIEWS_ENTER_ID)
493 validateAssociationEnterPdb();
495 else if (currentView == VIEWS_FROM_FILE)
497 validateAssociationFromFile();
502 * Validates inputs from the Manual PDB entry panel
504 public void validateAssociationEnterPdb()
506 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
507 .getCmb_assSeq().getSelectedItem();
508 lbl_pdbManualFetchStatus.setIcon(errorImage);
509 if (selectedSequences.length == 1
510 || !assSeqOpt.getName().equalsIgnoreCase(
511 "-Select Associated Seq-"))
513 txt_search.setEnabled(true);
516 btn_view.setEnabled(true);
517 lbl_pdbManualFetchStatus.setIcon(goodImage);
522 txt_search.setEnabled(false);
523 lbl_pdbManualFetchStatus.setIcon(errorImage);
528 * Validates inputs for the manual PDB file selection options
530 public void validateAssociationFromFile()
532 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
533 .getCmb_assSeq().getSelectedItem();
534 lbl_fromFileStatus.setIcon(errorImage);
535 if (selectedSequences.length == 1
536 || (assSeqOpt != null
537 && !assSeqOpt.getName().equalsIgnoreCase(
538 "-Select Associated Seq-")))
540 btn_pdbFromFile.setEnabled(true);
541 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
543 btn_view.setEnabled(true);
544 lbl_fromFileStatus.setIcon(goodImage);
549 btn_pdbFromFile.setEnabled(false);
550 lbl_fromFileStatus.setIcon(errorImage);
555 public void cmbAssSeqStateChanged()
557 validateSelections();
561 * Handles the state change event for the 'filter' combo-box and 'invert'
565 protected void stateChanged(ItemEvent e)
567 if (e.getSource() instanceof JCheckBox)
573 if (e.getStateChange() == ItemEvent.SELECTED)
582 * Handles action event for btn_ok
585 public void ok_ActionPerformed()
587 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
589 String currentView = selectedFilterOpt.getView();
590 if (currentView == VIEWS_FILTER)
592 int pdbIdCol = PDBRestClient.getPDBIdColumIndex(
593 lastPdbRequest.getWantedFields(), true);
594 int[] selectedRows = tbl_summary.getSelectedRows();
595 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
597 for (int summaryRow : selectedRows)
599 String pdbIdStr = tbl_summary.getValueAt(summaryRow, pdbIdCol)
601 PDBEntry pdbEntry = new PDBEntry();
602 pdbEntry.setId(pdbIdStr);
603 pdbEntry.setType("PDB");
604 pdbEntriesToView[count++] = pdbEntry;
606 new StructureViewer(ap.getStructureSelectionManager())
607 .viewStructures(ap, pdbEntriesToView,
608 ap.av.collateForPDB(pdbEntriesToView));
610 else if (currentView == VIEWS_ENTER_ID)
612 selectedSequence = ((AssociateSeqOptions) idInputAssSeqPanel
613 .getCmb_assSeq().getSelectedItem()).getSequence();
614 PDBEntry pdbEntry = new PDBEntry();
615 pdbEntry.setId(txt_search.getText());
616 pdbEntry.setType("PDB");
617 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
618 PDBEntry[] pdbEntriesToView = new PDBEntry[]
620 new StructureViewer(ap.getStructureSelectionManager())
621 .viewStructures(ap, pdbEntriesToView,
622 ap.av.collateForPDB(pdbEntriesToView));
624 else if (currentView == VIEWS_FROM_FILE)
626 selectedSequence = ((AssociateSeqOptions) fileChooserAssSeqPanel
627 .getCmb_assSeq().getSelectedItem()).getSequence();
628 new AssociatePdbFileWithSeq().associatePdbWithSeq(
629 selectedPdbFileName, jalview.io.AppletFormatAdapter.FILE,
630 selectedSequence, true, Desktop.instance);
636 * Populates the combo-box used in associating manually fetched structures to
637 * a unique sequence when more than one sequence selection is made.
639 public void populateCmbAssociateSeqOptions(
640 JComboBox<AssociateSeqOptions> cmb_assSeq, JLabel lbl_associateSeq)
642 cmb_assSeq.removeAllItems();
643 cmb_assSeq.addItem(new AssociateSeqOptions("-Select Associated Seq-",
645 // cmb_assSeq.addItem(new AssociateSeqOptions("Auto Detect", null));
646 lbl_associateSeq.setVisible(false);
647 if (selectedSequences.length > 1)
649 for (SequenceI seq : selectedSequences)
651 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
656 String seqName = selectedSequence.getDisplayId(false);
657 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
658 lbl_associateSeq.setText(seqName);
659 lbl_associateSeq.setVisible(true);
660 cmb_assSeq.setVisible(false);
664 public boolean isStructuresDiscovered()
666 return structuresDiscovered;
669 public void setStructuresDiscovered(boolean structuresDiscovered)
671 this.structuresDiscovered = structuresDiscovered;
674 public Collection<PDBResponseSummary> getDiscoveredStructuresSet()
676 return discoveredStructuresSet;
680 protected void txt_search_ActionPerformed()
682 isValidPBDEntry = false;
683 if (txt_search.getText().length() > 0)
685 List<PDBDocField> wantedFields = new ArrayList<PDBDocField>();
686 wantedFields.add(PDBDocField.PDB_ID);
687 PDBRestRequest pdbRequest = new PDBRestRequest();
688 pdbRequest.setAllowEmptySeq(false);
689 pdbRequest.setResponseSize(1);
690 pdbRequest.setFieldToSearchBy("(pdb_id:");
691 pdbRequest.setWantedFields(wantedFields);
692 pdbRequest.setSearchTerm(txt_search.getText() + ")");
693 pdbRequest.setAssociatedSequence(selectedSequence.getName());
694 pdbRestCleint = new PDBRestClient();
695 PDBRestResponse resultList = pdbRestCleint.executeRequest(pdbRequest);
696 if (resultList.getSearchSummary() != null
697 && resultList.getSearchSummary().size() > 0)
699 isValidPBDEntry = true;
702 validateSelections();
706 public void tabRefresh()
708 if (selectedSequences != null)
710 Thread refreshThread = new Thread(new Runnable()
715 fetchStructuresMetaData();
716 filterResultSet(((FilterOption) cmb_filterOption
717 .getSelectedItem()).getValue());
720 refreshThread.start();