2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
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;
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;
53 import java.util.Vector;
55 import javax.swing.JCheckBox;
56 import javax.swing.JComboBox;
57 import javax.swing.JLabel;
58 import javax.swing.table.AbstractTableModel;
61 * Provides the behaviors for the Structure chooser Panel
66 @SuppressWarnings("serial")
67 public class StructureChooser extends GStructureChooser implements
70 private static int MAX_QLENGTH = 7820;
72 private SequenceI selectedSequence;
74 private SequenceI[] selectedSequences;
76 private IProgressIndicator progressIndicator;
78 private Collection<FTSData> discoveredStructuresSet;
80 private FTSRestRequest lastPdbRequest;
82 private FTSRestClientI pdbRestCleint;
84 private String selectedStructureFileName;
86 private boolean isValidPBDEntry;
88 private boolean cachedPDBExists;
90 public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
94 this.selectedSequence = selectedSeq;
95 this.selectedSequences = selectedSeqs;
96 this.progressIndicator = (ap == null) ? null : ap.alignFrame;
101 * Initializes parameters used by the Structure Chooser Panel
105 if (!Jalview.isHeadlessMode())
107 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
110 // ensure a filter option is in force for search
111 populateFilterComboBox(true, cachedPDBExists);
112 Thread discoverPDBStructuresThread = new Thread(new Runnable()
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"),
125 fetchStructuresMetaData();
126 // revise filter options if no results were found
127 populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
128 updateProgressIndicator(null, startTime);
129 mainFrame.setVisible(true);
133 discoverPDBStructuresThread.start();
137 * Updates the progress indicator with the specified message
140 * displayed message for the operation
142 * unique handle for this indicator
144 public void updateProgressIndicator(String message, long id)
146 if (progressIndicator != null)
148 progressIndicator.setProgressBar(message, id);
153 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
156 public void fetchStructuresMetaData()
158 long startTime = System.currentTimeMillis();
159 pdbRestCleint = PDBFTSRestClient.getInstance();
160 Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
161 .getStructureSummaryFields();
163 discoveredStructuresSet = new LinkedHashSet<FTSData>();
164 HashSet<String> errors = new HashSet<String>();
165 for (SequenceI seq : selectedSequences)
167 FTSRestRequest pdbRequest = new FTSRestRequest();
168 pdbRequest.setAllowEmptySeq(false);
169 pdbRequest.setResponseSize(500);
170 pdbRequest.setFieldToSearchBy("(");
171 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
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;
181 resultList = pdbRestCleint.executeRequest(pdbRequest);
182 } catch (Exception e)
185 errors.add(e.getMessage());
188 lastPdbRequest = pdbRequest;
189 if (resultList.getSearchSummary() != null
190 && !resultList.getSearchSummary().isEmpty())
192 discoveredStructuresSet.addAll(resultList.getSearchSummary());
196 int noOfStructuresFound = 0;
197 String totalTime = (System.currentTimeMillis() - startTime)
199 if (discoveredStructuresSet != null
200 && !discoveredStructuresSet.isEmpty())
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));
212 mainFrame.setTitle(MessageManager
213 .getString("label.structure_chooser_manual_association"));
214 if (errors.size() > 0)
216 StringBuilder errorMsg = new StringBuilder();
217 for (String error : errors)
219 errorMsg.append(error).append("\n");
221 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
222 MessageManager.getString("label.pdb_web-service_error"),
223 JvOptionPane.ERROR_MESSAGE);
228 public void loadLocalCachedPDBEntries()
230 ArrayList<CachedPDB> entries = new ArrayList<CachedPDB>();
231 for (SequenceI seq : selectedSequences)
233 if (seq.getDatasetSequence() != null
234 && seq.getDatasetSequence().getAllPDBEntries() != null)
236 for (PDBEntry pdbEntry : seq.getDatasetSequence()
239 if (pdbEntry.getFile() != null)
241 entries.add(new CachedPDB(seq, pdbEntry));
246 cachedPDBExists = !entries.isEmpty();
247 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
248 tbl_local_pdb.setModel(tableModelx);
252 * Builds a query string for a given sequences using its DBRef entries
255 * the sequences to build a query for
256 * @return the built query string
259 public static String buildQuery(SequenceI seq)
261 boolean isPDBRefsFound = false;
262 boolean isUniProtRefsFound = false;
263 StringBuilder queryBuilder = new StringBuilder();
264 Set<String> seqRefs = new LinkedHashSet<String>();
266 if (seq.getAllPDBEntries() != null
267 && queryBuilder.length() < MAX_QLENGTH)
269 for (PDBEntry entry : seq.getAllPDBEntries())
271 if (isValidSeqName(entry.getId()))
273 queryBuilder.append("pdb_id:")
274 .append(entry.getId().toLowerCase()).append(" OR ");
275 isPDBRefsFound = true;
280 if (seq.getDBRefs() != null && seq.getDBRefs().length != 0)
282 for (DBRefEntry dbRef : seq.getDBRefs())
284 if (isValidSeqName(getDBRefId(dbRef))
285 && queryBuilder.length() < MAX_QLENGTH)
287 if (dbRef.getSource().equalsIgnoreCase(DBRefSource.UNIPROT))
289 queryBuilder.append("uniprot_accession:")
290 .append(getDBRefId(dbRef)).append(" OR ");
291 queryBuilder.append("uniprot_id:").append(getDBRefId(dbRef))
293 isUniProtRefsFound = true;
295 else if (dbRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
298 queryBuilder.append("pdb_id:")
299 .append(getDBRefId(dbRef).toLowerCase()).append(" OR ");
300 isPDBRefsFound = true;
304 seqRefs.add(getDBRefId(dbRef));
310 if (!isPDBRefsFound && !isUniProtRefsFound)
312 String seqName = seq.getName();
313 seqName = sanitizeSeqName(seqName);
314 String[] names = seqName.toLowerCase().split("\\|");
315 for (String name : names)
317 // System.out.println("Found name : " + name);
319 if (isValidSeqName(name))
325 for (String seqRef : seqRefs)
327 queryBuilder.append("text:").append(seqRef).append(" OR ");
331 int endIndex = queryBuilder.lastIndexOf(" OR ");
332 if (queryBuilder.toString().length() < 6)
336 String query = queryBuilder.toString().substring(0, endIndex);
341 * Remove the following special characters from input string +, -, &, !, (, ),
342 * {, }, [, ], ^, ", ~, *, ?, :, \
347 static String sanitizeSeqName(String seqName)
349 Objects.requireNonNull(seqName);
350 return seqName.replaceAll("\\[\\d*\\]", "")
351 .replaceAll("[^\\dA-Za-z|_]", "").replaceAll("\\s+", "+");
355 * Ensures sequence ref names are not less than 3 characters and does not
356 * contain a database name
361 public static boolean isValidSeqName(String seqName)
363 // System.out.println("seqName : " + seqName);
364 String ignoreList = "pdb,uniprot,swiss-prot";
365 if (seqName.length() < 3)
369 if (seqName.contains(":"))
373 seqName = seqName.toLowerCase();
374 for (String ignoredEntry : ignoreList.split(","))
376 if (seqName.contains(ignoredEntry))
384 public static String getDBRefId(DBRefEntry dbRef)
386 String ref = dbRef.getAccessionId().replaceAll("GO:", "");
391 * Filters a given list of discovered structures based on supplied argument
393 * @param fieldToFilterBy
394 * the field to filter by
396 public void filterResultSet(final String fieldToFilterBy)
398 Thread filterThread = new Thread(new Runnable()
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>();
411 for (SequenceI seq : selectedSequences)
413 FTSRestRequest pdbRequest = new FTSRestRequest();
414 if (fieldToFilterBy.equalsIgnoreCase("uniprot_coverage"))
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);
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);
437 FTSRestResponse resultList;
440 resultList = pdbRestCleint.executeRequest(pdbRequest);
441 } catch (Exception e)
444 errors.add(e.getMessage());
447 lastPdbRequest = pdbRequest;
448 if (resultList.getSearchSummary() != null
449 && !resultList.getSearchSummary().isEmpty())
451 filteredResponse.addAll(resultList.getSearchSummary());
455 String totalTime = (System.currentTimeMillis() - startTime)
457 if (!filteredResponse.isEmpty())
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));
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));
480 mainFrame.setTitle(MessageManager.formatMessage(
481 "label.structure_chooser_filter_time", totalTime));
482 if (errors.size() > 0)
484 StringBuilder errorMsg = new StringBuilder();
485 for (String error : errors)
487 errorMsg.append(error).append("\n");
489 JvOptionPane.showMessageDialog(
492 MessageManager.getString("label.pdb_web-service_error"),
493 JvOptionPane.ERROR_MESSAGE);
497 lbl_loading.setVisible(false);
499 validateSelections();
502 filterThread.start();
506 * Handles action event for btn_pdbFromFile
509 public void pdbFromFile_actionPerformed()
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)));
521 int value = chooser.showOpenDialog(null);
522 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
524 selectedStructureFileName = chooser.getSelectedFile().getPath();
525 jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedStructureFileName);
526 validateSelections();
531 * Populates the filter combo-box options dynamically depending on discovered
534 protected void populateFilterComboBox(boolean haveData,
535 boolean cachedPDBExists)
538 * temporarily suspend the change listener behaviour
540 cmb_filterOption.removeItemListener(this);
542 cmb_filterOption.removeAllItems();
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));
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));
563 FilterOption cachedOption = new FilterOption("Cached PDB Entries",
564 "-", VIEWS_LOCAL_PDB, false);
565 cmb_filterOption.addItem(cachedOption);
566 cmb_filterOption.setSelectedItem(cachedOption);
569 cmb_filterOption.addItem(new FilterOption(
570 "Predict 3D Model with Phyre2", "-", VIEWS_PHYRE2_PREDICTION,
572 cmb_filterOption.addItemListener(this);
576 * Updates the displayed view based on the selected filter option
578 protected void updateCurrentView()
580 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
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)
589 mainFrame.setTitle(filterTitle);
590 chk_invertFilter.setVisible(true);
591 filterResultSet(selectedFilterOpt.getValue());
593 else if (selectedFilterOpt.getView() == VIEWS_PHYRE2_PREDICTION)
595 mainFrame.setTitle(MessageManager
596 .getString("label.phyre2_model_prediction"));
597 phyre2InputAssSeqPanel.loadCmbAssSeq();
599 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
600 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
602 mainFrame.setTitle(MessageManager
603 .getString("label.structure_chooser_manual_association"));
604 idInputAssSeqPanel.loadCmbAssSeq();
605 fileChooserAssSeqPanel.loadCmbAssSeq();
607 validateSelections();
611 * Validates user selection and activates the view button if all parameters
615 public void validateSelections()
617 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
619 btn_view.setEnabled(false);
620 String currentView = selectedFilterOpt.getView();
621 if (currentView == VIEWS_FILTER)
623 if (getResultTable().getSelectedRows().length > 0)
625 btn_view.setEnabled(true);
628 else if (currentView == VIEWS_LOCAL_PDB)
630 if (tbl_local_pdb.getSelectedRows().length > 0)
632 btn_view.setEnabled(true);
635 else if (currentView == VIEWS_ENTER_ID)
637 validateAssociationEnterPdb();
639 else if (currentView == VIEWS_FROM_FILE)
641 validateAssociationFromFile();
643 else if (currentView == VIEWS_PHYRE2_PREDICTION)
645 validateAssociationFromPhyre2();
646 if (getPhyreResultTable().getSelectedRows().length > 0)
648 btn_view.setEnabled(true);
654 * Validates inputs from the Manual PDB entry panel
656 public void validateAssociationEnterPdb()
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)
664 lbl_pdbManualFetchStatus
665 .setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager
666 .formatMessage("info.no_pdb_entry_found_for",
667 txt_search.getText())));
670 if (errorWarning.length() > 0)
672 lbl_pdbManualFetchStatus.setIcon(warningImage);
673 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(
674 true, errorWarning.toString()));
677 if (selectedSequences.length == 1
678 || !assSeqOpt.getName().equalsIgnoreCase(
679 "-Select Associated Seq-"))
681 txt_search.setEnabled(true);
684 btn_view.setEnabled(true);
685 lbl_pdbManualFetchStatus.setToolTipText("");
686 lbl_pdbManualFetchStatus.setIcon(goodImage);
691 txt_search.setEnabled(false);
692 lbl_pdbManualFetchStatus.setIcon(errorImage);
697 * Validates inputs for the manual PDB file selection options
699 public void validateAssociationFromFile()
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-")))
708 btn_pdbFromFile.setEnabled(true);
709 if (selectedStructureFileName != null && selectedStructureFileName.length() > 0)
711 btn_view.setEnabled(true);
712 lbl_fromFileStatus.setIcon(goodImage);
717 btn_pdbFromFile.setEnabled(false);
718 lbl_fromFileStatus.setIcon(errorImage);
723 * Validates inputs for Phyre2 3D Model prediction
725 public void validateAssociationFromPhyre2()
727 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) phyre2InputAssSeqPanel
728 .getCmb_assSeq().getSelectedItem();
729 if (selectedSequences.length == 1
730 || (assSeqOpt != null && !assSeqOpt.getName().equalsIgnoreCase(
731 "-Select Associated Seq-")))
733 btn_runPhyre2Prediction.setEnabled(true);
737 btn_runPhyre2Prediction.setEnabled(false);
742 public void cmbAssSeqStateChanged()
744 validateSelections();
748 * Handles the state change event for the 'filter' combo-box and 'invert'
752 protected void stateChanged(ItemEvent e)
754 if (e.getSource() instanceof JCheckBox)
760 if (e.getStateChange() == ItemEvent.SELECTED)
769 * Handles action event for btn_ok
772 public void ok_ActionPerformed()
774 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
775 final int preferredHeight = pnl_filter.getHeight();
776 ssm.setMappingForPhyre2Model(false);
777 new Thread(new Runnable()
782 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
784 String currentView = selectedFilterOpt.getView();
785 if (currentView == VIEWS_FILTER)
787 int pdbIdColIndex = getResultTable().getColumn("PDB Id")
789 int refSeqColIndex = getResultTable().getColumn("Ref Sequence")
791 int[] selectedRows = getResultTable().getSelectedRows();
792 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
794 List<SequenceI> selectedSeqsToView = new ArrayList<SequenceI>();
795 for (int row : selectedRows)
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)
805 pdbEntry = getFindEntry(pdbIdStr,
806 selectedSeq.getAllPDBEntries());
808 if (pdbEntry == null)
810 pdbEntry = new PDBEntry();
811 pdbEntry.setId(pdbIdStr);
812 pdbEntry.setType(PDBEntry.Type.PDB);
813 selectedSeq.getDatasetSequence().addPDBId(pdbEntry);
815 pdbEntriesToView[count++] = pdbEntry;
817 SequenceI[] selectedSeqs = selectedSeqsToView
818 .toArray(new SequenceI[selectedSeqsToView.size()]);
819 launchStructureViewer(ssm, pdbEntriesToView, ap, selectedSeqs);
821 else if (currentView == VIEWS_LOCAL_PDB)
823 int[] selectedRows = tbl_local_pdb.getSelectedRows();
824 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
826 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
828 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
830 List<SequenceI> selectedSeqsToView = new ArrayList<SequenceI>();
831 for (int row : selectedRows)
833 PDBEntry pdbEntry = (PDBEntry) tbl_local_pdb.getValueAt(row,
835 pdbEntriesToView[count++] = pdbEntry;
836 SequenceI selectedSeq = (SequenceI) tbl_local_pdb.getValueAt(
837 row, refSeqColIndex);
838 selectedSeqsToView.add(selectedSeq);
840 SequenceI[] selectedSeqs = selectedSeqsToView
841 .toArray(new SequenceI[selectedSeqsToView.size()]);
842 launchStructureViewer(ssm, pdbEntriesToView, ap, selectedSeqs);
844 else if (currentView == VIEWS_ENTER_ID)
846 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
847 .getCmb_assSeq().getSelectedItem()).getSequence();
848 if (userSelectedSeq != null)
850 selectedSequence = userSelectedSeq;
854 String pdbIdStr = txt_search.getText();
855 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
856 if (pdbEntry == null)
858 pdbEntry = new PDBEntry();
859 if (pdbIdStr.split(":").length > 1)
861 pdbEntry.setId(pdbIdStr.split(":")[0]);
862 pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase());
866 pdbEntry.setId(pdbIdStr);
868 pdbEntry.setType(PDBEntry.Type.PDB);
869 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
872 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
873 launchStructureViewer(ssm, pdbEntriesToView, ap,
874 new SequenceI[] { selectedSequence });
876 else if (currentView == VIEWS_FROM_FILE)
878 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
879 .getCmb_assSeq().getSelectedItem()).getSequence();
880 if (userSelectedSeq != null)
882 selectedSequence = userSelectedSeq;
884 PDBEntry fileEntry = new AssociateStructureFileWithSeq()
885 .associateStructureWithSeq(selectedStructureFileName,
887 selectedSequence, true, Desktop.instance);
889 launchStructureViewer(ssm,
890 new PDBEntry[] { fileEntry }, ap,
891 new SequenceI[] { selectedSequence });
893 else if (currentView == VIEWS_PHYRE2_PREDICTION)
895 SequenceI userSelectedSeq = ((AssociateSeqOptions) phyre2InputAssSeqPanel
896 .getCmb_assSeq().getSelectedItem()).getSequence();
897 if (userSelectedSeq != null)
899 selectedSequence = userSelectedSeq;
901 int templateColIndex = getPhyreResultTable()
902 .getColumn("Template")
904 int[] selectedRows = getPhyreResultTable().getSelectedRows();
905 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
907 for (int row : selectedRows)
909 String templateId = getPhyreResultTable().getValueAt(row,
910 templateColIndex).toString();
911 String structureFile = phyre2ResultDirectory + templateId;
912 pdbEntriesToView[count++] = new AssociateStructureFileWithSeq()
913 .associateStructureWithSeq(structureFile,
914 DataSourceType.FILE, selectedSequence, true,
918 final StructureSelectionManager ssm = ap
919 .getStructureSelectionManager();
920 ssm.setMappingForPhyre2Model(true);
921 final long progressSessionId = System.currentTimeMillis();
922 ssm.setProgressSessionId(progressSessionId);
924 SequenceI[] sequences = new SequenceI[] { selectedSequence };
926 ssm.setProgressBar(MessageManager
927 .getString("status.launching_3d_structure_viewer"));
928 final StructureViewer sViewer = new StructureViewer(ssm);
929 if (pdbEntriesToView.length > 1)
931 ArrayList<SequenceI[]> seqsMap = new ArrayList<SequenceI[]>();
932 for (SequenceI seq : sequences)
934 seqsMap.add(new SequenceI[] { seq });
936 SequenceI[][] collatedSeqs = seqsMap
937 .toArray(new SequenceI[0][0]);
938 ssm.setProgressBar(null);
939 ssm.setProgressBar(MessageManager
940 .getString("status.fetching_3d_structures_for_selected_entries"));
941 sViewer.viewStructures(pdbEntriesToView, collatedSeqs, ap);
945 ssm.setProgressBar(null);
946 ssm.setProgressBar(MessageManager.formatMessage(
947 "status.fetching_3d_structures_for",
948 pdbEntriesToView[0].getId()));
949 sViewer.viewStructures(pdbEntriesToView[0], sequences, ap);
952 closeAction(preferredHeight);
957 private String phyre2ResultDirectory;
960 public void predict3DModelWithPhyre2()
962 // TODO implement code for submitting sequence to Phyre2 service, and code
963 // for getting the result directory when the job completes, this is
964 // currently hard-wired to the directory of result for FER_CAPAN/1-144
965 phyre2ResultDirectory = "examples/testdata/phyre2results/56da5616b4559c93/";
966 // String summaryhtml = phyre2ResultDirectory + "summary.html";
967 // // TODO ditch HTML parsing once appropriated data file (i.e. JSON) for
968 // // Phyre2 result summary is made available
969 // List<Phyre2SummaryPojo> phyreResults = Phyre2Client
970 // .parsePhyre2ResultSummaryTable(summaryhtml);
972 String crudeListFile = phyre2ResultDirectory + "crudelist";
973 List<Phyre2SummaryPojo> phyreResults = Phyre2Client
974 .parsePhyreCrudeList(crudeListFile);
976 getPhyreResultTable()
977 .setModel(Phyre2Client.getTableModel(phyreResults));
978 Phyre2Client.configurePhyreResultTable(getPhyreResultTable());
981 private PDBEntry getFindEntry(String id, Vector<PDBEntry> pdbEntries)
983 Objects.requireNonNull(id);
984 Objects.requireNonNull(pdbEntries);
985 PDBEntry foundEntry = null;
986 for (PDBEntry entry : pdbEntries)
988 if (entry.getId().equalsIgnoreCase(id))
996 private void launchStructureViewer(StructureSelectionManager ssm,
997 final PDBEntry[] pdbEntriesToView,
998 final AlignmentPanel alignPanel, SequenceI[] sequences)
1000 long progressId = sequences.hashCode();
1001 setProgressBar(MessageManager
1002 .getString("status.launching_3d_structure_viewer"), progressId);
1003 final StructureViewer sViewer = new StructureViewer(ssm);
1004 setProgressBar(null, progressId);
1006 if (SiftsSettings.isMapWithSifts())
1008 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<SequenceI>();
1010 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1011 // real PDB ID. For moment, we can also safely do this if there is already
1012 // a known mapping between the PDBEntry and the sequence.
1014 for (SequenceI seq : sequences)
1016 PDBEntry pdbe = pdbEntriesToView[p++];
1017 if (pdbe != null && pdbe.getFile() != null)
1019 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1020 if (smm != null && smm.length > 0)
1022 for (StructureMapping sm : smm)
1024 if (sm.getSequence() == seq)
1031 if (seq.getPrimaryDBRefs().size() == 0)
1033 seqsWithoutSourceDBRef.add(seq);
1037 if (!seqsWithoutSourceDBRef.isEmpty())
1039 int y = seqsWithoutSourceDBRef.size();
1040 setProgressBar(MessageManager.formatMessage(
1041 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1043 SequenceI[] seqWithoutSrcDBRef = new SequenceI[y];
1045 for (SequenceI fSeq : seqsWithoutSourceDBRef)
1047 seqWithoutSrcDBRef[x++] = fSeq;
1049 new DBRefFetcher(seqWithoutSrcDBRef).fetchDBRefs(true);
1050 setProgressBar("Fetch complete.", progressId); // todo i18n
1053 if (pdbEntriesToView.length > 1)
1055 ArrayList<SequenceI[]> seqsMap = new ArrayList<SequenceI[]>();
1056 for (SequenceI seq : sequences)
1058 seqsMap.add(new SequenceI[] { seq });
1060 SequenceI[][] collatedSeqs = seqsMap.toArray(new SequenceI[0][0]);
1061 setProgressBar(MessageManager
1062 .getString("status.fetching_3d_structures_for_selected_entries"), progressId);
1063 sViewer.viewStructures(pdbEntriesToView, collatedSeqs, alignPanel);
1067 setProgressBar(MessageManager.formatMessage(
1068 "status.fetching_3d_structures_for",
1069 pdbEntriesToView[0].getId()),progressId);
1070 sViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1072 setProgressBar(null, progressId);
1076 * Populates the combo-box used in associating manually fetched structures to
1077 * a unique sequence when more than one sequence selection is made.
1080 public void populateCmbAssociateSeqOptions(
1081 JComboBox<AssociateSeqOptions> cmb_assSeq, JLabel lbl_associateSeq)
1083 cmb_assSeq.removeAllItems();
1084 cmb_assSeq.addItem(new AssociateSeqOptions("-Select Associated Seq-",
1086 lbl_associateSeq.setVisible(false);
1087 if (selectedSequences.length > 1)
1089 for (SequenceI seq : selectedSequences)
1091 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1096 String seqName = selectedSequence.getDisplayId(false);
1097 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1098 lbl_associateSeq.setText(seqName);
1099 lbl_associateSeq.setVisible(true);
1100 cmb_assSeq.setVisible(false);
1104 public boolean isStructuresDiscovered()
1106 return discoveredStructuresSet != null
1107 && !discoveredStructuresSet.isEmpty();
1110 public Collection<FTSData> getDiscoveredStructuresSet()
1112 return discoveredStructuresSet;
1116 protected void txt_search_ActionPerformed()
1123 errorWarning.setLength(0);
1124 isValidPBDEntry = false;
1125 if (txt_search.getText().length() > 0)
1127 String searchTerm = txt_search.getText().toLowerCase();
1128 searchTerm = searchTerm.split(":")[0];
1129 // System.out.println(">>>>> search term : " + searchTerm);
1130 List<FTSDataColumnI> wantedFields = new ArrayList<FTSDataColumnI>();
1131 FTSRestRequest pdbRequest = new FTSRestRequest();
1132 pdbRequest.setAllowEmptySeq(false);
1133 pdbRequest.setResponseSize(1);
1134 pdbRequest.setFieldToSearchBy("(pdb_id:");
1135 pdbRequest.setWantedFields(wantedFields);
1136 pdbRequest.setSearchTerm(searchTerm + ")");
1137 pdbRequest.setAssociatedSequence(selectedSequence);
1138 pdbRestCleint = PDBFTSRestClient.getInstance();
1139 wantedFields.add(pdbRestCleint.getPrimaryKeyColumn());
1140 FTSRestResponse resultList;
1143 resultList = pdbRestCleint.executeRequest(pdbRequest);
1144 } catch (Exception e)
1146 errorWarning.append(e.getMessage());
1150 validateSelections();
1152 if (resultList.getSearchSummary() != null
1153 && resultList.getSearchSummary().size() > 0)
1155 isValidPBDEntry = true;
1158 validateSelections();
1164 public void tabRefresh()
1166 if (selectedSequences != null)
1168 Thread refreshThread = new Thread(new Runnable()
1173 fetchStructuresMetaData();
1174 filterResultSet(((FilterOption) cmb_filterOption
1175 .getSelectedItem()).getValue());
1178 refreshThread.start();
1182 public class PDBEntryTableModel extends AbstractTableModel
1184 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type", "File" };
1186 private List<CachedPDB> pdbEntries;
1188 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1190 this.pdbEntries = new ArrayList<CachedPDB>(pdbEntries);
1194 public String getColumnName(int columnIndex)
1196 return columns[columnIndex];
1200 public int getRowCount()
1202 return pdbEntries.size();
1206 public int getColumnCount()
1208 return columns.length;
1212 public boolean isCellEditable(int row, int column)
1218 public Object getValueAt(int rowIndex, int columnIndex)
1220 Object value = "??";
1221 CachedPDB entry = pdbEntries.get(rowIndex);
1222 switch (columnIndex)
1225 value = entry.getSequence();
1228 value = entry.getPdbEntry();
1231 value = entry.getPdbEntry().getChainCode() == null ? "_" : entry
1232 .getPdbEntry().getChainCode();
1235 value = entry.getPdbEntry().getType();
1238 value = entry.getPdbEntry().getFile();
1245 public Class<?> getColumnClass(int columnIndex)
1247 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1250 public CachedPDB getPDBEntryAt(int row)
1252 return pdbEntries.get(row);
1257 private class CachedPDB
1259 private SequenceI sequence;
1261 private PDBEntry pdbEntry;
1263 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1265 this.sequence = sequence;
1266 this.pdbEntry = pdbEntry;
1269 public SequenceI getSequence()
1274 public PDBEntry getPdbEntry()
1281 private IProgressIndicator progressBar;
1284 public void setProgressBar(String message, long id)
1286 progressBar.setProgressBar(message, id);
1290 public void registerHandler(long id, IProgressIndicatorHandler handler)
1292 progressBar.registerHandler(id, handler);
1296 public boolean operationInProgress()
1298 return progressBar.operationInProgress();