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",
526 selectedStructureFileName);
527 validateSelections();
532 * Populates the filter combo-box options dynamically depending on discovered
535 protected void populateFilterComboBox(boolean haveData,
536 boolean cachedPDBExists)
539 * temporarily suspend the change listener behaviour
541 cmb_filterOption.removeItemListener(this);
543 cmb_filterOption.removeAllItems();
546 cmb_filterOption.addItem(new FilterOption("Best Quality",
547 "overall_quality", VIEWS_FILTER, false));
548 cmb_filterOption.addItem(new FilterOption("Best Resolution",
549 "resolution", VIEWS_FILTER, false));
550 cmb_filterOption.addItem(new FilterOption("Most Protein Chain",
551 "number_of_protein_chains", VIEWS_FILTER, false));
552 cmb_filterOption.addItem(new FilterOption("Most Bound Molecules",
553 "number_of_bound_molecules", VIEWS_FILTER, false));
554 cmb_filterOption.addItem(new FilterOption("Most Polymer Residues",
555 "number_of_polymer_residues", VIEWS_FILTER, true));
557 cmb_filterOption.addItem(new FilterOption("Enter PDB Id", "-",
558 VIEWS_ENTER_ID, false));
559 cmb_filterOption.addItem(new FilterOption("From File", "-",
560 VIEWS_FROM_FILE, false));
564 FilterOption cachedOption = new FilterOption("Cached PDB Entries",
565 "-", VIEWS_LOCAL_PDB, false);
566 cmb_filterOption.addItem(cachedOption);
567 cmb_filterOption.setSelectedItem(cachedOption);
570 cmb_filterOption.addItem(new FilterOption(
571 "Predict 3D Model with Phyre2", "-", VIEWS_PHYRE2_PREDICTION,
573 cmb_filterOption.addItemListener(this);
577 * Updates the displayed view based on the selected filter option
579 protected void updateCurrentView()
581 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
583 layout_switchableViews.show(pnl_switchableViews,
584 selectedFilterOpt.getView());
585 String filterTitle = mainFrame.getTitle();
586 mainFrame.setTitle(frameTitle);
587 chk_invertFilter.setVisible(false);
588 if (selectedFilterOpt.getView() == VIEWS_FILTER)
590 mainFrame.setTitle(filterTitle);
591 chk_invertFilter.setVisible(true);
592 filterResultSet(selectedFilterOpt.getValue());
594 else if (selectedFilterOpt.getView() == VIEWS_PHYRE2_PREDICTION)
596 mainFrame.setTitle(MessageManager
597 .getString("label.phyre2_model_prediction"));
598 phyre2InputAssSeqPanel.loadCmbAssSeq();
600 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
601 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
603 mainFrame.setTitle(MessageManager
604 .getString("label.structure_chooser_manual_association"));
605 idInputAssSeqPanel.loadCmbAssSeq();
606 fileChooserAssSeqPanel.loadCmbAssSeq();
608 validateSelections();
612 * Validates user selection and activates the view button if all parameters
616 public void validateSelections()
618 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
620 btn_view.setEnabled(false);
621 String currentView = selectedFilterOpt.getView();
622 if (currentView == VIEWS_FILTER)
624 if (getResultTable().getSelectedRows().length > 0)
626 btn_view.setEnabled(true);
629 else if (currentView == VIEWS_LOCAL_PDB)
631 if (tbl_local_pdb.getSelectedRows().length > 0)
633 btn_view.setEnabled(true);
636 else if (currentView == VIEWS_ENTER_ID)
638 validateAssociationEnterPdb();
640 else if (currentView == VIEWS_FROM_FILE)
642 validateAssociationFromFile();
644 else if (currentView == VIEWS_PHYRE2_PREDICTION)
646 validateAssociationFromPhyre2();
647 if (getPhyreResultTable().getSelectedRows().length > 0)
649 btn_view.setEnabled(true);
655 * Validates inputs from the Manual PDB entry panel
657 public void validateAssociationEnterPdb()
659 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
660 .getCmb_assSeq().getSelectedItem();
661 lbl_pdbManualFetchStatus.setIcon(errorImage);
662 lbl_pdbManualFetchStatus.setToolTipText("");
663 if (txt_search.getText().length() > 0)
665 lbl_pdbManualFetchStatus
666 .setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager
667 .formatMessage("info.no_pdb_entry_found_for",
668 txt_search.getText())));
671 if (errorWarning.length() > 0)
673 lbl_pdbManualFetchStatus.setIcon(warningImage);
674 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(
675 true, errorWarning.toString()));
678 if (selectedSequences.length == 1
679 || !assSeqOpt.getName().equalsIgnoreCase(
680 "-Select Associated Seq-"))
682 txt_search.setEnabled(true);
685 btn_view.setEnabled(true);
686 lbl_pdbManualFetchStatus.setToolTipText("");
687 lbl_pdbManualFetchStatus.setIcon(goodImage);
692 txt_search.setEnabled(false);
693 lbl_pdbManualFetchStatus.setIcon(errorImage);
698 * Validates inputs for the manual PDB file selection options
700 public void validateAssociationFromFile()
702 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
703 .getCmb_assSeq().getSelectedItem();
704 lbl_fromFileStatus.setIcon(errorImage);
705 if (selectedSequences.length == 1
706 || (assSeqOpt != null && !assSeqOpt.getName().equalsIgnoreCase(
707 "-Select Associated Seq-")))
709 btn_pdbFromFile.setEnabled(true);
710 if (selectedStructureFileName != null
711 && selectedStructureFileName.length() > 0)
713 btn_view.setEnabled(true);
714 lbl_fromFileStatus.setIcon(goodImage);
719 btn_pdbFromFile.setEnabled(false);
720 lbl_fromFileStatus.setIcon(errorImage);
725 * Validates inputs for Phyre2 3D Model prediction
727 public void validateAssociationFromPhyre2()
729 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) phyre2InputAssSeqPanel
730 .getCmb_assSeq().getSelectedItem();
731 if (selectedSequences.length == 1
732 || (assSeqOpt != null && !assSeqOpt.getName().equalsIgnoreCase(
733 "-Select Associated Seq-")))
735 btn_runPhyre2Prediction.setEnabled(true);
739 btn_runPhyre2Prediction.setEnabled(false);
744 public void cmbAssSeqStateChanged()
746 validateSelections();
750 * Handles the state change event for the 'filter' combo-box and 'invert'
754 protected void stateChanged(ItemEvent e)
756 if (e.getSource() instanceof JCheckBox)
762 if (e.getStateChange() == ItemEvent.SELECTED)
771 * Handles action event for btn_ok
774 public void ok_ActionPerformed()
776 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
777 final int preferredHeight = pnl_filter.getHeight();
778 new Thread(new Runnable()
783 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
785 String currentView = selectedFilterOpt.getView();
786 if (currentView == VIEWS_FILTER)
788 int pdbIdColIndex = getResultTable().getColumn("PDB Id")
790 int refSeqColIndex = getResultTable().getColumn("Ref Sequence")
792 int[] selectedRows = getResultTable().getSelectedRows();
793 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
795 List<SequenceI> selectedSeqsToView = new ArrayList<SequenceI>();
796 for (int row : selectedRows)
798 String pdbIdStr = getResultTable().getValueAt(row,
799 pdbIdColIndex).toString();
800 SequenceI selectedSeq = (SequenceI) getResultTable()
801 .getValueAt(row, refSeqColIndex);
802 selectedSeqsToView.add(selectedSeq);
803 PDBEntry pdbEntry = selectedSeq.getPDBEntry(pdbIdStr);
804 if (pdbEntry == null)
806 pdbEntry = getFindEntry(pdbIdStr,
807 selectedSeq.getAllPDBEntries());
809 if (pdbEntry == null)
811 pdbEntry = new PDBEntry();
812 pdbEntry.setId(pdbIdStr);
813 pdbEntry.setType(PDBEntry.Type.PDB);
814 selectedSeq.getDatasetSequence().addPDBId(pdbEntry);
816 pdbEntriesToView[count++] = pdbEntry;
818 SequenceI[] selectedSeqs = selectedSeqsToView
819 .toArray(new SequenceI[selectedSeqsToView.size()]);
820 launchStructureViewer(ssm, pdbEntriesToView, ap, selectedSeqs);
822 else if (currentView == VIEWS_LOCAL_PDB)
824 int[] selectedRows = tbl_local_pdb.getSelectedRows();
825 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
827 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
829 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
831 List<SequenceI> selectedSeqsToView = new ArrayList<SequenceI>();
832 for (int row : selectedRows)
834 PDBEntry pdbEntry = (PDBEntry) tbl_local_pdb.getValueAt(row,
836 pdbEntriesToView[count++] = pdbEntry;
837 SequenceI selectedSeq = (SequenceI) tbl_local_pdb.getValueAt(
838 row, refSeqColIndex);
839 selectedSeqsToView.add(selectedSeq);
841 SequenceI[] selectedSeqs = selectedSeqsToView
842 .toArray(new SequenceI[selectedSeqsToView.size()]);
843 launchStructureViewer(ssm, pdbEntriesToView, ap, selectedSeqs);
845 else if (currentView == VIEWS_ENTER_ID)
847 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
848 .getCmb_assSeq().getSelectedItem()).getSequence();
849 if (userSelectedSeq != null)
851 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,
886 DataSourceType.FILE, selectedSequence, true,
889 launchStructureViewer(ssm, new PDBEntry[] { fileEntry }, ap,
890 new SequenceI[] { selectedSequence });
892 else if (currentView == VIEWS_PHYRE2_PREDICTION)
894 SequenceI userSelectedSeq = ((AssociateSeqOptions) phyre2InputAssSeqPanel
895 .getCmb_assSeq().getSelectedItem()).getSequence();
896 if (userSelectedSeq != null)
898 selectedSequence = userSelectedSeq;
900 int templateColIndex = getPhyreResultTable()
901 .getColumn("Template").getModelIndex();
902 int[] selectedRows = getPhyreResultTable().getSelectedRows();
903 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
905 for (int row : selectedRows)
907 String templateId = getPhyreResultTable().getValueAt(row,
908 templateColIndex).toString();
909 String structureFile = phyre2ResultDirectory + templateId;
910 String fastaMapping = phyre2ResultDirectory
911 + templateId.replaceAll(".pdb", ".fasta");
912 // System.out.println("structure file >>>>> " + structureFile);
913 // System.out.println("fasta mapping >>>>> " + fastaMapping);
914 pdbEntriesToView[count++] = new AssociateStructureFileWithSeq()
915 .associateStructureWithSeq(structureFile,
916 DataSourceType.FILE, selectedSequence, true,
918 ssm.registerPhyre2Template(structureFile, fastaMapping);
921 final StructureSelectionManager ssm = ap
922 .getStructureSelectionManager();
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);
974 String crudeListFile = phyre2ResultDirectory + "crudelist";
975 List<Phyre2SummaryPojo> phyreResults = Phyre2Client
976 .parsePhyreCrudeList(crudeListFile);
978 getPhyreResultTable()
979 .setModel(Phyre2Client.getTableModel(phyreResults));
980 Phyre2Client.configurePhyreResultTable(getPhyreResultTable());
983 private PDBEntry getFindEntry(String id, Vector<PDBEntry> pdbEntries)
985 Objects.requireNonNull(id);
986 Objects.requireNonNull(pdbEntries);
987 PDBEntry foundEntry = null;
988 for (PDBEntry entry : pdbEntries)
990 if (entry.getId().equalsIgnoreCase(id))
998 private void launchStructureViewer(StructureSelectionManager ssm,
999 final PDBEntry[] pdbEntriesToView,
1000 final AlignmentPanel alignPanel, SequenceI[] sequences)
1002 long progressId = sequences.hashCode();
1005 .getString("status.launching_3d_structure_viewer"),
1007 final StructureViewer sViewer = new StructureViewer(ssm);
1008 setProgressBar(null, progressId);
1010 if (SiftsSettings.isMapWithSifts())
1012 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<SequenceI>();
1014 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1015 // real PDB ID. For moment, we can also safely do this if there is already
1016 // a known mapping between the PDBEntry and the sequence.
1018 for (SequenceI seq : sequences)
1020 PDBEntry pdbe = pdbEntriesToView[p++];
1021 if (pdbe != null && pdbe.getFile() != null)
1023 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1024 if (smm != null && smm.length > 0)
1026 for (StructureMapping sm : smm)
1028 if (sm.getSequence() == seq)
1035 if (seq.getPrimaryDBRefs().size() == 0
1036 && !ssm.isPhyre2Template(pdbe.getFile()))
1038 seqsWithoutSourceDBRef.add(seq);
1042 if (!seqsWithoutSourceDBRef.isEmpty())
1044 int y = seqsWithoutSourceDBRef.size();
1045 setProgressBar(MessageManager.formatMessage(
1046 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1048 SequenceI[] seqWithoutSrcDBRef = new SequenceI[y];
1050 for (SequenceI fSeq : seqsWithoutSourceDBRef)
1052 seqWithoutSrcDBRef[x++] = fSeq;
1054 new DBRefFetcher(seqWithoutSrcDBRef).fetchDBRefs(true);
1055 setProgressBar("Fetch complete.", progressId); // todo i18n
1058 if (pdbEntriesToView.length > 1)
1060 ArrayList<SequenceI[]> seqsMap = new ArrayList<SequenceI[]>();
1061 for (SequenceI seq : sequences)
1063 seqsMap.add(new SequenceI[] { seq });
1065 SequenceI[][] collatedSeqs = seqsMap.toArray(new SequenceI[0][0]);
1068 .getString("status.fetching_3d_structures_for_selected_entries"),
1070 sViewer.viewStructures(pdbEntriesToView, collatedSeqs, alignPanel);
1074 setProgressBar(MessageManager.formatMessage(
1075 "status.fetching_3d_structures_for",
1076 pdbEntriesToView[0].getId()), progressId);
1077 sViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1079 setProgressBar(null, progressId);
1083 * Populates the combo-box used in associating manually fetched structures to
1084 * a unique sequence when more than one sequence selection is made.
1087 public void populateCmbAssociateSeqOptions(
1088 JComboBox<AssociateSeqOptions> cmb_assSeq, JLabel lbl_associateSeq)
1090 cmb_assSeq.removeAllItems();
1091 cmb_assSeq.addItem(new AssociateSeqOptions("-Select Associated Seq-",
1093 lbl_associateSeq.setVisible(false);
1094 if (selectedSequences.length > 1)
1096 for (SequenceI seq : selectedSequences)
1098 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1103 String seqName = selectedSequence.getDisplayId(false);
1104 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1105 lbl_associateSeq.setText(seqName);
1106 lbl_associateSeq.setVisible(true);
1107 cmb_assSeq.setVisible(false);
1111 public boolean isStructuresDiscovered()
1113 return discoveredStructuresSet != null
1114 && !discoveredStructuresSet.isEmpty();
1117 public Collection<FTSData> getDiscoveredStructuresSet()
1119 return discoveredStructuresSet;
1123 protected void txt_search_ActionPerformed()
1130 errorWarning.setLength(0);
1131 isValidPBDEntry = false;
1132 if (txt_search.getText().length() > 0)
1134 String searchTerm = txt_search.getText().toLowerCase();
1135 searchTerm = searchTerm.split(":")[0];
1136 // System.out.println(">>>>> search term : " + searchTerm);
1137 List<FTSDataColumnI> wantedFields = new ArrayList<FTSDataColumnI>();
1138 FTSRestRequest pdbRequest = new FTSRestRequest();
1139 pdbRequest.setAllowEmptySeq(false);
1140 pdbRequest.setResponseSize(1);
1141 pdbRequest.setFieldToSearchBy("(pdb_id:");
1142 pdbRequest.setWantedFields(wantedFields);
1143 pdbRequest.setSearchTerm(searchTerm + ")");
1144 pdbRequest.setAssociatedSequence(selectedSequence);
1145 pdbRestCleint = PDBFTSRestClient.getInstance();
1146 wantedFields.add(pdbRestCleint.getPrimaryKeyColumn());
1147 FTSRestResponse resultList;
1150 resultList = pdbRestCleint.executeRequest(pdbRequest);
1151 } catch (Exception e)
1153 errorWarning.append(e.getMessage());
1157 validateSelections();
1159 if (resultList.getSearchSummary() != null
1160 && resultList.getSearchSummary().size() > 0)
1162 isValidPBDEntry = true;
1165 validateSelections();
1171 public void tabRefresh()
1173 if (selectedSequences != null)
1175 Thread refreshThread = new Thread(new Runnable()
1180 fetchStructuresMetaData();
1181 filterResultSet(((FilterOption) cmb_filterOption
1182 .getSelectedItem()).getValue());
1185 refreshThread.start();
1189 public class PDBEntryTableModel extends AbstractTableModel
1191 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type", "File" };
1193 private List<CachedPDB> pdbEntries;
1195 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1197 this.pdbEntries = new ArrayList<CachedPDB>(pdbEntries);
1201 public String getColumnName(int columnIndex)
1203 return columns[columnIndex];
1207 public int getRowCount()
1209 return pdbEntries.size();
1213 public int getColumnCount()
1215 return columns.length;
1219 public boolean isCellEditable(int row, int column)
1225 public Object getValueAt(int rowIndex, int columnIndex)
1227 Object value = "??";
1228 CachedPDB entry = pdbEntries.get(rowIndex);
1229 switch (columnIndex)
1232 value = entry.getSequence();
1235 value = entry.getPdbEntry();
1238 value = entry.getPdbEntry().getChainCode() == null ? "_" : entry
1239 .getPdbEntry().getChainCode();
1242 value = entry.getPdbEntry().getType();
1245 value = entry.getPdbEntry().getFile();
1252 public Class<?> getColumnClass(int columnIndex)
1254 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1257 public CachedPDB getPDBEntryAt(int row)
1259 return pdbEntries.get(row);
1264 private class CachedPDB
1266 private SequenceI sequence;
1268 private PDBEntry pdbEntry;
1270 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1272 this.sequence = sequence;
1273 this.pdbEntry = pdbEntry;
1276 public SequenceI getSequence()
1281 public PDBEntry getPdbEntry()
1288 private IProgressIndicator progressBar;
1291 public void setProgressBar(String message, long id)
1293 progressBar.setProgressBar(message, id);
1297 public void registerHandler(long id, IProgressIndicatorHandler handler)
1299 progressBar.registerHandler(id, handler);
1303 public boolean operationInProgress()
1305 return progressBar.operationInProgress();