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 long progressSessionId = System.currentTimeMillis();
775 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
776 final int preferredHeight = pnl_filter.getHeight();
777 ssm.setProgressIndicator(this);
778 ssm.setProgressSessionId(progressSessionId);
779 ssm.setMappingForPhyre2Model(false);
780 new Thread(new Runnable()
785 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
787 String currentView = selectedFilterOpt.getView();
788 if (currentView == VIEWS_FILTER)
790 int pdbIdColIndex = getResultTable().getColumn("PDB Id")
792 int refSeqColIndex = getResultTable().getColumn("Ref Sequence")
794 int[] selectedRows = getResultTable().getSelectedRows();
795 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
797 List<SequenceI> selectedSeqsToView = new ArrayList<SequenceI>();
798 for (int row : selectedRows)
800 String pdbIdStr = getResultTable().getValueAt(row,
801 pdbIdColIndex).toString();
802 SequenceI selectedSeq = (SequenceI) getResultTable()
803 .getValueAt(row, refSeqColIndex);
804 selectedSeqsToView.add(selectedSeq);
805 PDBEntry pdbEntry = selectedSeq.getPDBEntry(pdbIdStr);
806 if (pdbEntry == null)
808 pdbEntry = getFindEntry(pdbIdStr,
809 selectedSeq.getAllPDBEntries());
811 if (pdbEntry == null)
813 pdbEntry = new PDBEntry();
814 pdbEntry.setId(pdbIdStr);
815 pdbEntry.setType(PDBEntry.Type.PDB);
816 selectedSeq.getDatasetSequence().addPDBId(pdbEntry);
818 pdbEntriesToView[count++] = pdbEntry;
820 SequenceI[] selectedSeqs = selectedSeqsToView
821 .toArray(new SequenceI[selectedSeqsToView.size()]);
822 launchStructureViewer(ssm, pdbEntriesToView, ap, selectedSeqs);
824 else if (currentView == VIEWS_LOCAL_PDB)
826 int[] selectedRows = tbl_local_pdb.getSelectedRows();
827 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
829 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
831 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
833 List<SequenceI> selectedSeqsToView = new ArrayList<SequenceI>();
834 for (int row : selectedRows)
836 PDBEntry pdbEntry = (PDBEntry) tbl_local_pdb.getValueAt(row,
838 pdbEntriesToView[count++] = pdbEntry;
839 SequenceI selectedSeq = (SequenceI) tbl_local_pdb.getValueAt(
840 row, refSeqColIndex);
841 selectedSeqsToView.add(selectedSeq);
843 SequenceI[] selectedSeqs = selectedSeqsToView
844 .toArray(new SequenceI[selectedSeqsToView.size()]);
845 launchStructureViewer(ssm, pdbEntriesToView, ap, selectedSeqs);
847 else if (currentView == VIEWS_ENTER_ID)
849 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
850 .getCmb_assSeq().getSelectedItem()).getSequence();
851 if (userSelectedSeq != null)
853 selectedSequence = userSelectedSeq;
856 String pdbIdStr = txt_search.getText();
857 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
858 if (pdbEntry == null)
860 pdbEntry = new PDBEntry();
861 if (pdbIdStr.split(":").length > 1)
863 pdbEntry.setId(pdbIdStr.split(":")[0]);
864 pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase());
868 pdbEntry.setId(pdbIdStr);
870 pdbEntry.setType(PDBEntry.Type.PDB);
871 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
874 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
875 launchStructureViewer(ssm, pdbEntriesToView, ap,
876 new SequenceI[] { selectedSequence });
878 else if (currentView == VIEWS_FROM_FILE)
880 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
881 .getCmb_assSeq().getSelectedItem()).getSequence();
882 if (userSelectedSeq != null)
884 selectedSequence = userSelectedSeq;
886 PDBEntry fileEntry = new AssociateStructureFileWithSeq()
887 .associateStructureWithSeq(selectedStructureFileName,
889 selectedSequence, true, Desktop.instance);
891 launchStructureViewer(ssm, new PDBEntry[] { fileEntry }, ap,
892 new SequenceI[] { selectedSequence });
894 else if (currentView == VIEWS_PHYRE2_PREDICTION)
896 SequenceI userSelectedSeq = ((AssociateSeqOptions) phyre2InputAssSeqPanel
897 .getCmb_assSeq().getSelectedItem()).getSequence();
898 if (userSelectedSeq != null)
900 selectedSequence = userSelectedSeq;
902 int templateColIndex = getPhyreResultTable()
903 .getColumn("Template")
905 int[] selectedRows = getPhyreResultTable().getSelectedRows();
906 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
908 for (int row : selectedRows)
910 String templateId = getPhyreResultTable().getValueAt(row,
911 templateColIndex).toString();
912 String structureFile = phyre2ResultDirectory + templateId
914 pdbEntriesToView[count++] = new AssociateStructureFileWithSeq()
915 .associateStructureWithSeq(structureFile,
916 DataSourceType.FILE, selectedSequence, true,
920 final StructureSelectionManager ssm = ap
921 .getStructureSelectionManager();
922 ssm.setMappingForPhyre2Model(true);
923 final long progressSessionId = System.currentTimeMillis();
924 ssm.setProgressSessionId(progressSessionId);
926 SequenceI[] sequences = new SequenceI[] { selectedSequence };
928 ssm.setProgressBar(MessageManager
929 .getString("status.launching_3d_structure_viewer"));
930 final StructureViewer sViewer = new StructureViewer(ssm);
931 if (pdbEntriesToView.length > 1)
933 ArrayList<SequenceI[]> seqsMap = new ArrayList<SequenceI[]>();
934 for (SequenceI seq : sequences)
936 seqsMap.add(new SequenceI[] { seq });
938 SequenceI[][] collatedSeqs = seqsMap
939 .toArray(new SequenceI[0][0]);
940 ssm.setProgressBar(null);
941 ssm.setProgressBar(MessageManager
942 .getString("status.fetching_3d_structures_for_selected_entries"));
943 sViewer.viewStructures(pdbEntriesToView, collatedSeqs, ap);
947 ssm.setProgressBar(null);
948 ssm.setProgressBar(MessageManager.formatMessage(
949 "status.fetching_3d_structures_for",
950 pdbEntriesToView[0].getId()));
951 sViewer.viewStructures(pdbEntriesToView[0], sequences, ap);
954 closeAction(preferredHeight);
959 private String phyre2ResultDirectory;
962 public void predict3DModelWithPhyre2()
964 // TODO implement code for submitting sequence to Phyre2 service, and code
965 // for getting the result directory when the job completes, this is
966 // currently hard-wired to the directory of result for FER_CAPAN/1-144
967 phyre2ResultDirectory = "examples/testdata/phyre2results/56da5616b4559c93/";
968 String summaryhtml = phyre2ResultDirectory + "summary.html";
969 // TODO ditch HTML parsing once appropriated data file (i.e. JSON) for
970 // Phyre2 result summary is made available
971 List<Phyre2SummaryPojo> phyreResults = Phyre2Client
972 .parsePhyre2ResultSummaryTable(summaryhtml);
973 getPhyreResultTable()
974 .setModel(Phyre2Client.getTableModel(phyreResults));
975 Phyre2Client.configurePhyreResultTable(getPhyreResultTable());
978 private PDBEntry getFindEntry(String id, Vector<PDBEntry> pdbEntries)
980 Objects.requireNonNull(id);
981 Objects.requireNonNull(pdbEntries);
982 PDBEntry foundEntry = null;
983 for (PDBEntry entry : pdbEntries)
985 if (entry.getId().equalsIgnoreCase(id))
993 private void launchStructureViewer(StructureSelectionManager ssm,
994 final PDBEntry[] pdbEntriesToView,
995 final AlignmentPanel alignPanel, SequenceI[] sequences)
997 ssm.setProgressBar(MessageManager
998 .getString("status.launching_3d_structure_viewer"));
999 final StructureViewer sViewer = new StructureViewer(ssm);
1001 if (SiftsSettings.isMapWithSifts())
1003 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<SequenceI>();
1005 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1006 // real PDB ID. For moment, we can also safely do this if there is already
1007 // a known mapping between the PDBEntry and the sequence.
1008 for (SequenceI seq : sequences)
1010 PDBEntry pdbe = pdbEntriesToView[p++];
1011 if (pdbe != null && pdbe.getFile() != null)
1013 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1014 if (smm != null && smm.length > 0)
1016 for (StructureMapping sm : smm)
1018 if (sm.getSequence() == seq)
1025 if (seq.getPrimaryDBRefs().size() == 0)
1027 seqsWithoutSourceDBRef.add(seq);
1031 if (!seqsWithoutSourceDBRef.isEmpty())
1033 int y = seqsWithoutSourceDBRef.size();
1034 ssm.setProgressBar(null);
1035 ssm.setProgressBar(MessageManager.formatMessage(
1036 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1038 SequenceI[] seqWithoutSrcDBRef = new SequenceI[y];
1040 for (SequenceI fSeq : seqsWithoutSourceDBRef)
1042 seqWithoutSrcDBRef[x++] = fSeq;
1044 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
1045 dbRefFetcher.fetchDBRefs(true);
1048 if (pdbEntriesToView.length > 1)
1050 ArrayList<SequenceI[]> seqsMap = new ArrayList<SequenceI[]>();
1051 for (SequenceI seq : sequences)
1053 seqsMap.add(new SequenceI[] { seq });
1055 SequenceI[][] collatedSeqs = seqsMap.toArray(new SequenceI[0][0]);
1056 ssm.setProgressBar(null);
1057 ssm.setProgressBar(MessageManager
1058 .getString("status.fetching_3d_structures_for_selected_entries"));
1059 sViewer.viewStructures(pdbEntriesToView, collatedSeqs, alignPanel);
1063 ssm.setProgressBar(null);
1064 ssm.setProgressBar(MessageManager.formatMessage(
1065 "status.fetching_3d_structures_for",
1066 pdbEntriesToView[0].getId()));
1067 sViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1072 * Populates the combo-box used in associating manually fetched structures to
1073 * a unique sequence when more than one sequence selection is made.
1076 public void populateCmbAssociateSeqOptions(
1077 JComboBox<AssociateSeqOptions> cmb_assSeq, JLabel lbl_associateSeq)
1079 cmb_assSeq.removeAllItems();
1080 cmb_assSeq.addItem(new AssociateSeqOptions("-Select Associated Seq-",
1082 lbl_associateSeq.setVisible(false);
1083 if (selectedSequences.length > 1)
1085 for (SequenceI seq : selectedSequences)
1087 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1092 String seqName = selectedSequence.getDisplayId(false);
1093 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1094 lbl_associateSeq.setText(seqName);
1095 lbl_associateSeq.setVisible(true);
1096 cmb_assSeq.setVisible(false);
1100 public boolean isStructuresDiscovered()
1102 return discoveredStructuresSet != null
1103 && !discoveredStructuresSet.isEmpty();
1106 public Collection<FTSData> getDiscoveredStructuresSet()
1108 return discoveredStructuresSet;
1112 protected void txt_search_ActionPerformed()
1119 errorWarning.setLength(0);
1120 isValidPBDEntry = false;
1121 if (txt_search.getText().length() > 0)
1123 String searchTerm = txt_search.getText().toLowerCase();
1124 searchTerm = searchTerm.split(":")[0];
1125 // System.out.println(">>>>> search term : " + searchTerm);
1126 List<FTSDataColumnI> wantedFields = new ArrayList<FTSDataColumnI>();
1127 FTSRestRequest pdbRequest = new FTSRestRequest();
1128 pdbRequest.setAllowEmptySeq(false);
1129 pdbRequest.setResponseSize(1);
1130 pdbRequest.setFieldToSearchBy("(pdb_id:");
1131 pdbRequest.setWantedFields(wantedFields);
1132 pdbRequest.setSearchTerm(searchTerm + ")");
1133 pdbRequest.setAssociatedSequence(selectedSequence);
1134 pdbRestCleint = PDBFTSRestClient.getInstance();
1135 wantedFields.add(pdbRestCleint.getPrimaryKeyColumn());
1136 FTSRestResponse resultList;
1139 resultList = pdbRestCleint.executeRequest(pdbRequest);
1140 } catch (Exception e)
1142 errorWarning.append(e.getMessage());
1146 validateSelections();
1148 if (resultList.getSearchSummary() != null
1149 && resultList.getSearchSummary().size() > 0)
1151 isValidPBDEntry = true;
1154 validateSelections();
1160 public void tabRefresh()
1162 if (selectedSequences != null)
1164 Thread refreshThread = new Thread(new Runnable()
1169 fetchStructuresMetaData();
1170 filterResultSet(((FilterOption) cmb_filterOption
1171 .getSelectedItem()).getValue());
1174 refreshThread.start();
1178 public class PDBEntryTableModel extends AbstractTableModel
1180 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type", "File" };
1182 private List<CachedPDB> pdbEntries;
1184 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1186 this.pdbEntries = new ArrayList<CachedPDB>(pdbEntries);
1190 public String getColumnName(int columnIndex)
1192 return columns[columnIndex];
1196 public int getRowCount()
1198 return pdbEntries.size();
1202 public int getColumnCount()
1204 return columns.length;
1208 public boolean isCellEditable(int row, int column)
1214 public Object getValueAt(int rowIndex, int columnIndex)
1216 Object value = "??";
1217 CachedPDB entry = pdbEntries.get(rowIndex);
1218 switch (columnIndex)
1221 value = entry.getSequence();
1224 value = entry.getPdbEntry();
1227 value = entry.getPdbEntry().getChainCode() == null ? "_" : entry
1228 .getPdbEntry().getChainCode();
1231 value = entry.getPdbEntry().getType();
1234 value = entry.getPdbEntry().getFile();
1241 public Class<?> getColumnClass(int columnIndex)
1243 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1246 public CachedPDB getPDBEntryAt(int row)
1248 return pdbEntries.get(row);
1253 private class CachedPDB
1255 private SequenceI sequence;
1257 private PDBEntry pdbEntry;
1259 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1261 this.sequence = sequence;
1262 this.pdbEntry = pdbEntry;
1265 public SequenceI getSequence()
1270 public PDBEntry getPdbEntry()
1277 private IProgressIndicator progressBar;
1280 public void setProgressBar(String message, long id)
1282 progressBar.setProgressBar(message, id);
1286 public void registerHandler(long id, IProgressIndicatorHandler handler)
1288 progressBar.registerHandler(id, handler);
1292 public boolean operationInProgress()
1294 return progressBar.operationInProgress();