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.api.structures.JalviewStructureDisplayI;
25 import jalview.bin.Jalview;
26 import jalview.datamodel.DBRefEntry;
27 import jalview.datamodel.DBRefSource;
28 import jalview.datamodel.PDBEntry;
29 import jalview.datamodel.SequenceI;
30 import jalview.fts.api.FTSData;
31 import jalview.fts.api.FTSDataColumnI;
32 import jalview.fts.api.FTSRestClientI;
33 import jalview.fts.core.FTSRestRequest;
34 import jalview.fts.core.FTSRestResponse;
35 import jalview.fts.service.pdb.PDBFTSRestClient;
36 import jalview.io.DataSourceType;
37 import jalview.jbgui.GStructureChooser;
38 import jalview.structure.StructureMapping;
39 import jalview.structure.StructureSelectionManager;
40 import jalview.util.MessageManager;
41 import jalview.ws.DBRefFetcher;
42 import jalview.ws.sifts.SiftsSettings;
44 import java.awt.event.ItemEvent;
45 import java.util.ArrayList;
46 import java.util.Collection;
47 import java.util.HashSet;
48 import java.util.LinkedHashSet;
49 import java.util.List;
50 import java.util.Objects;
52 import java.util.Vector;
54 import javax.swing.JCheckBox;
55 import javax.swing.JComboBox;
56 import javax.swing.JLabel;
57 import javax.swing.JTable;
58 import javax.swing.table.AbstractTableModel;
61 * Provides the behaviors for the Structure chooser Panel
66 @SuppressWarnings("serial")
67 public class StructureChooser extends GStructureChooser
68 implements IProgressIndicator
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 selectedPdbFileName;
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.getString(
123 "status.searching_for_pdb_structures"), startTime);
124 fetchStructuresMetaData();
125 // revise filter options if no results were found
126 populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
127 updateProgressIndicator(null, startTime);
128 mainFrame.setVisible(true);
132 discoverPDBStructuresThread.start();
136 * Updates the progress indicator with the specified message
139 * displayed message for the operation
141 * unique handle for this indicator
143 public void updateProgressIndicator(String message, long id)
145 if (progressIndicator != null)
147 progressIndicator.setProgressBar(message, id);
152 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
155 public void fetchStructuresMetaData()
157 long startTime = System.currentTimeMillis();
158 pdbRestCleint = PDBFTSRestClient.getInstance();
159 Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
160 .getStructureSummaryFields();
162 discoveredStructuresSet = new LinkedHashSet<>();
163 HashSet<String> errors = new HashSet<>();
164 for (SequenceI seq : selectedSequences)
166 FTSRestRequest pdbRequest = new FTSRestRequest();
167 pdbRequest.setAllowEmptySeq(false);
168 pdbRequest.setResponseSize(500);
169 pdbRequest.setFieldToSearchBy("(");
170 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
172 pdbRequest.setFieldToSortBy(selectedFilterOpt.getValue(),
173 !chk_invertFilter.isSelected());
174 pdbRequest.setWantedFields(wantedFields);
175 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
176 pdbRequest.setAssociatedSequence(seq);
177 FTSRestResponse resultList;
180 resultList = pdbRestCleint.executeRequest(pdbRequest);
181 } catch (Exception e)
184 errors.add(e.getMessage());
187 lastPdbRequest = pdbRequest;
188 if (resultList.getSearchSummary() != null
189 && !resultList.getSearchSummary().isEmpty())
191 discoveredStructuresSet.addAll(resultList.getSearchSummary());
195 int noOfStructuresFound = 0;
196 String totalTime = (System.currentTimeMillis() - startTime)
198 if (discoveredStructuresSet != null
199 && !discoveredStructuresSet.isEmpty())
201 getResultTable().setModel(FTSRestResponse
202 .getTableModel(lastPdbRequest, discoveredStructuresSet));
203 noOfStructuresFound = discoveredStructuresSet.size();
204 mainFrame.setTitle(MessageManager.formatMessage(
205 "label.structure_chooser_no_of_structures",
206 noOfStructuresFound, totalTime));
210 mainFrame.setTitle(MessageManager
211 .getString("label.structure_chooser_manual_association"));
212 if (errors.size() > 0)
214 StringBuilder errorMsg = new StringBuilder();
215 for (String error : errors)
217 errorMsg.append(error).append("\n");
219 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
220 MessageManager.getString("label.pdb_web-service_error"),
221 JvOptionPane.ERROR_MESSAGE);
226 public void loadLocalCachedPDBEntries()
228 ArrayList<CachedPDB> entries = new ArrayList<>();
229 for (SequenceI seq : selectedSequences)
231 if (seq.getDatasetSequence() != null
232 && seq.getDatasetSequence().getAllPDBEntries() != null)
234 for (PDBEntry pdbEntry : seq.getDatasetSequence()
237 if (pdbEntry.getFile() != null)
239 entries.add(new CachedPDB(seq, pdbEntry));
244 cachedPDBExists = !entries.isEmpty();
245 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
246 tbl_local_pdb.setModel(tableModelx);
250 * Builds a query string for a given sequences using its DBRef entries
253 * the sequences to build a query for
254 * @return the built query string
257 public static String buildQuery(SequenceI seq)
259 boolean isPDBRefsFound = false;
260 boolean isUniProtRefsFound = false;
261 StringBuilder queryBuilder = new StringBuilder();
262 Set<String> seqRefs = new LinkedHashSet<>();
264 if (seq.getAllPDBEntries() != null
265 && queryBuilder.length() < MAX_QLENGTH)
267 for (PDBEntry entry : seq.getAllPDBEntries())
269 if (isValidSeqName(entry.getId()))
271 queryBuilder.append("pdb_id:").append(entry.getId().toLowerCase())
273 isPDBRefsFound = true;
278 if (seq.getDBRefs() != null && seq.getDBRefs().length != 0)
280 for (DBRefEntry dbRef : seq.getDBRefs())
282 if (isValidSeqName(getDBRefId(dbRef))
283 && queryBuilder.length() < MAX_QLENGTH)
285 if (dbRef.getSource().equalsIgnoreCase(DBRefSource.UNIPROT))
287 queryBuilder.append("uniprot_accession:")
288 .append(getDBRefId(dbRef)).append(" OR ");
289 queryBuilder.append("uniprot_id:").append(getDBRefId(dbRef))
291 isUniProtRefsFound = true;
293 else if (dbRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
296 queryBuilder.append("pdb_id:")
297 .append(getDBRefId(dbRef).toLowerCase()).append(" OR ");
298 isPDBRefsFound = true;
302 seqRefs.add(getDBRefId(dbRef));
308 if (!isPDBRefsFound && !isUniProtRefsFound)
310 String seqName = seq.getName();
311 seqName = sanitizeSeqName(seqName);
312 String[] names = seqName.toLowerCase().split("\\|");
313 for (String name : names)
315 // System.out.println("Found name : " + name);
317 if (isValidSeqName(name))
323 for (String seqRef : seqRefs)
325 queryBuilder.append("text:").append(seqRef).append(" OR ");
329 int endIndex = queryBuilder.lastIndexOf(" OR ");
330 if (queryBuilder.toString().length() < 6)
334 String query = queryBuilder.toString().substring(0, endIndex);
339 * Remove the following special characters from input string +, -, &, !, (, ),
340 * {, }, [, ], ^, ", ~, *, ?, :, \
345 static String sanitizeSeqName(String seqName)
347 Objects.requireNonNull(seqName);
348 return seqName.replaceAll("\\[\\d*\\]", "")
349 .replaceAll("[^\\dA-Za-z|_]", "").replaceAll("\\s+", "+");
353 * Ensures sequence ref names are not less than 3 characters and does not
354 * contain a database name
359 public static boolean isValidSeqName(String seqName)
361 // System.out.println("seqName : " + seqName);
362 String ignoreList = "pdb,uniprot,swiss-prot";
363 if (seqName.length() < 3)
367 if (seqName.contains(":"))
371 seqName = seqName.toLowerCase();
372 for (String ignoredEntry : ignoreList.split(","))
374 if (seqName.contains(ignoredEntry))
382 public static String getDBRefId(DBRefEntry dbRef)
384 String ref = dbRef.getAccessionId().replaceAll("GO:", "");
389 * Filters a given list of discovered structures based on supplied argument
391 * @param fieldToFilterBy
392 * the field to filter by
394 public void filterResultSet(final String fieldToFilterBy)
396 Thread filterThread = new Thread(new Runnable()
401 long startTime = System.currentTimeMillis();
402 pdbRestCleint = PDBFTSRestClient.getInstance();
403 lbl_loading.setVisible(true);
404 Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
405 .getStructureSummaryFields();
406 Collection<FTSData> filteredResponse = new HashSet<>();
407 HashSet<String> errors = new HashSet<>();
409 for (SequenceI seq : selectedSequences)
411 FTSRestRequest pdbRequest = new FTSRestRequest();
412 if (fieldToFilterBy.equalsIgnoreCase("uniprot_coverage"))
414 pdbRequest.setAllowEmptySeq(false);
415 pdbRequest.setResponseSize(1);
416 pdbRequest.setFieldToSearchBy("(");
417 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
418 pdbRequest.setWantedFields(wantedFields);
419 pdbRequest.setAssociatedSequence(seq);
420 pdbRequest.setFacet(true);
421 pdbRequest.setFacetPivot(fieldToFilterBy + ",entry_entity");
422 pdbRequest.setFacetPivotMinCount(1);
426 pdbRequest.setAllowEmptySeq(false);
427 pdbRequest.setResponseSize(1);
428 pdbRequest.setFieldToSearchBy("(");
429 pdbRequest.setFieldToSortBy(fieldToFilterBy,
430 !chk_invertFilter.isSelected());
431 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
432 pdbRequest.setWantedFields(wantedFields);
433 pdbRequest.setAssociatedSequence(seq);
435 FTSRestResponse resultList;
438 resultList = pdbRestCleint.executeRequest(pdbRequest);
439 } catch (Exception e)
442 errors.add(e.getMessage());
445 lastPdbRequest = pdbRequest;
446 if (resultList.getSearchSummary() != null
447 && !resultList.getSearchSummary().isEmpty())
449 filteredResponse.addAll(resultList.getSearchSummary());
453 String totalTime = (System.currentTimeMillis() - startTime)
455 if (!filteredResponse.isEmpty())
457 final int filterResponseCount = filteredResponse.size();
458 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
459 reorderedStructuresSet.addAll(filteredResponse);
460 reorderedStructuresSet.addAll(discoveredStructuresSet);
461 getResultTable().setModel(FTSRestResponse
462 .getTableModel(lastPdbRequest, reorderedStructuresSet));
464 FTSRestResponse.configureTableColumn(getResultTable(),
465 wantedFields, tempUserPrefs);
466 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
467 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
468 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
469 // Update table selection model here
470 getResultTable().addRowSelectionInterval(0,
471 filterResponseCount - 1);
472 mainFrame.setTitle(MessageManager.formatMessage(
473 "label.structure_chooser_filter_time", totalTime));
477 mainFrame.setTitle(MessageManager.formatMessage(
478 "label.structure_chooser_filter_time", totalTime));
479 if (errors.size() > 0)
481 StringBuilder errorMsg = new StringBuilder();
482 for (String error : errors)
484 errorMsg.append(error).append("\n");
486 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
487 MessageManager.getString("label.pdb_web-service_error"),
488 JvOptionPane.ERROR_MESSAGE);
492 lbl_loading.setVisible(false);
494 validateSelections();
497 filterThread.start();
501 * Handles action event for btn_pdbFromFile
504 public void pdbFromFile_actionPerformed()
506 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
507 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
508 chooser.setFileView(new jalview.io.JalviewFileView());
509 chooser.setDialogTitle(
510 MessageManager.formatMessage("label.select_pdb_file_for",
511 selectedSequence.getDisplayId(false)));
512 chooser.setToolTipText(MessageManager.formatMessage(
513 "label.load_pdb_file_associate_with_sequence",
514 selectedSequence.getDisplayId(false)));
516 int value = chooser.showOpenDialog(null);
517 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
519 selectedPdbFileName = chooser.getSelectedFile().getPath();
520 jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
521 validateSelections();
526 * Populates the filter combo-box options dynamically depending on discovered
529 protected void populateFilterComboBox(boolean haveData,
530 boolean cachedPDBExist)
533 * temporarily suspend the change listener behaviour
535 cmb_filterOption.removeItemListener(this);
537 cmb_filterOption.removeAllItems();
540 cmb_filterOption.addItem(new FilterOption(
541 MessageManager.getString("label.best_quality"),
542 "overall_quality", VIEWS_FILTER, false));
543 cmb_filterOption.addItem(new FilterOption(
544 MessageManager.getString("label.best_resolution"),
545 "resolution", VIEWS_FILTER, false));
546 cmb_filterOption.addItem(new FilterOption(
547 MessageManager.getString("label.most_protein_chain"),
548 "number_of_protein_chains", VIEWS_FILTER, false));
549 cmb_filterOption.addItem(new FilterOption(
550 MessageManager.getString("label.most_bound_molecules"),
551 "number_of_bound_molecules", VIEWS_FILTER, false));
552 cmb_filterOption.addItem(new FilterOption(
553 MessageManager.getString("label.most_polymer_residues"),
554 "number_of_polymer_residues", VIEWS_FILTER, true));
556 cmb_filterOption.addItem(
557 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
558 "-", VIEWS_ENTER_ID, false));
559 cmb_filterOption.addItem(
560 new FilterOption(MessageManager.getString("label.from_file"),
561 "-", VIEWS_FROM_FILE, false));
565 FilterOption cachedOption = new FilterOption(
566 MessageManager.getString("label.cached_structures"),
567 "-", VIEWS_LOCAL_PDB, false);
568 cmb_filterOption.addItem(cachedOption);
569 cmb_filterOption.setSelectedItem(cachedOption);
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_ENTER_ID
594 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
596 mainFrame.setTitle(MessageManager
597 .getString("label.structure_chooser_manual_association"));
598 idInputAssSeqPanel.loadCmbAssSeq();
599 fileChooserAssSeqPanel.loadCmbAssSeq();
601 validateSelections();
605 * Validates user selection and activates the view button if all parameters
609 public void validateSelections()
611 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
613 btn_view.setEnabled(false);
614 String currentView = selectedFilterOpt.getView();
615 if (currentView == VIEWS_FILTER)
617 if (getResultTable().getSelectedRows().length > 0)
619 btn_view.setEnabled(true);
622 else if (currentView == VIEWS_LOCAL_PDB)
624 if (tbl_local_pdb.getSelectedRows().length > 0)
626 btn_view.setEnabled(true);
629 else if (currentView == VIEWS_ENTER_ID)
631 validateAssociationEnterPdb();
633 else if (currentView == VIEWS_FROM_FILE)
635 validateAssociationFromFile();
640 * Validates inputs from the Manual PDB entry panel
642 public void validateAssociationEnterPdb()
644 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
645 .getCmb_assSeq().getSelectedItem();
646 lbl_pdbManualFetchStatus.setIcon(errorImage);
647 lbl_pdbManualFetchStatus.setToolTipText("");
648 if (txt_search.getText().length() > 0)
650 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
651 MessageManager.formatMessage("info.no_pdb_entry_found_for",
652 txt_search.getText())));
655 if (errorWarning.length() > 0)
657 lbl_pdbManualFetchStatus.setIcon(warningImage);
658 lbl_pdbManualFetchStatus.setToolTipText(
659 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
662 if (selectedSequences.length == 1 || !assSeqOpt.getName()
663 .equalsIgnoreCase("-Select Associated Seq-"))
665 txt_search.setEnabled(true);
668 btn_view.setEnabled(true);
669 lbl_pdbManualFetchStatus.setToolTipText("");
670 lbl_pdbManualFetchStatus.setIcon(goodImage);
675 txt_search.setEnabled(false);
676 lbl_pdbManualFetchStatus.setIcon(errorImage);
681 * Validates inputs for the manual PDB file selection options
683 public void validateAssociationFromFile()
685 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
686 .getCmb_assSeq().getSelectedItem();
687 lbl_fromFileStatus.setIcon(errorImage);
688 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
689 .getName().equalsIgnoreCase("-Select Associated Seq-")))
691 btn_pdbFromFile.setEnabled(true);
692 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
694 btn_view.setEnabled(true);
695 lbl_fromFileStatus.setIcon(goodImage);
700 btn_pdbFromFile.setEnabled(false);
701 lbl_fromFileStatus.setIcon(errorImage);
706 public void cmbAssSeqStateChanged()
708 validateSelections();
712 * Handles the state change event for the 'filter' combo-box and 'invert'
716 protected void stateChanged(ItemEvent e)
718 if (e.getSource() instanceof JCheckBox)
724 if (e.getStateChange() == ItemEvent.SELECTED)
733 * select structures for viewing by their PDB IDs
736 * @return true if structures were found and marked as selected
738 public boolean selectStructure(String... pdbids)
740 boolean found = false;
742 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
744 String currentView = selectedFilterOpt.getView();
745 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
746 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
748 if (restable == null)
750 // can't select (enter PDB ID, or load file - need to also select which
751 // sequence to associate with)
755 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
756 for (int r = 0; r < restable.getRowCount(); r++)
758 for (int p = 0; p < pdbids.length; p++)
760 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
761 .equalsIgnoreCase(pdbids[p]))
763 restable.setRowSelectionInterval(r, r);
771 * Handles action event for btn_ok
774 public void ok_ActionPerformed()
776 showStructures(false);
780 * structure viewer opened by this dialog, or null
782 private StructureViewer sViewer = null;
784 public void showStructures(boolean waitUntilFinished)
787 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
789 final int preferredHeight = pnl_filter.getHeight();
791 Runnable viewStruc = new Runnable()
796 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
798 String currentView = selectedFilterOpt.getView();
799 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
802 if (currentView == VIEWS_FILTER)
804 int pdbIdColIndex = restable.getColumn("PDB Id")
806 int refSeqColIndex = restable.getColumn("Ref Sequence")
808 int[] selectedRows = restable.getSelectedRows();
809 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
811 List<SequenceI> selectedSeqsToView = new ArrayList<>();
812 for (int row : selectedRows)
814 String pdbIdStr = restable
815 .getValueAt(row, pdbIdColIndex).toString();
816 SequenceI selectedSeq = (SequenceI) restable
817 .getValueAt(row, refSeqColIndex);
818 selectedSeqsToView.add(selectedSeq);
819 PDBEntry pdbEntry = selectedSeq.getPDBEntry(pdbIdStr);
820 if (pdbEntry == null)
822 pdbEntry = getFindEntry(pdbIdStr,
823 selectedSeq.getAllPDBEntries());
826 if (pdbEntry == null)
828 pdbEntry = new PDBEntry();
829 pdbEntry.setId(pdbIdStr);
830 pdbEntry.setType(PDBEntry.Type.PDB);
831 selectedSeq.getDatasetSequence().addPDBId(pdbEntry);
833 pdbEntriesToView[count++] = pdbEntry;
835 SequenceI[] selectedSeqs = selectedSeqsToView
836 .toArray(new SequenceI[selectedSeqsToView.size()]);
837 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
840 else if (currentView == VIEWS_LOCAL_PDB)
842 int[] selectedRows = tbl_local_pdb.getSelectedRows();
843 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
845 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
847 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
849 List<SequenceI> selectedSeqsToView = new ArrayList<>();
850 for (int row : selectedRows)
852 PDBEntry pdbEntry = (PDBEntry) tbl_local_pdb.getValueAt(row,
854 pdbEntriesToView[count++] = pdbEntry;
855 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
856 .getValueAt(row, refSeqColIndex);
857 selectedSeqsToView.add(selectedSeq);
859 SequenceI[] selectedSeqs = selectedSeqsToView
860 .toArray(new SequenceI[selectedSeqsToView.size()]);
861 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
864 else if (currentView == VIEWS_ENTER_ID)
866 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
867 .getCmb_assSeq().getSelectedItem()).getSequence();
868 if (userSelectedSeq != null)
870 selectedSequence = userSelectedSeq;
872 String pdbIdStr = txt_search.getText();
873 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
874 if (pdbEntry == null)
876 pdbEntry = new PDBEntry();
877 if (pdbIdStr.split(":").length > 1)
879 pdbEntry.setId(pdbIdStr.split(":")[0]);
880 pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase());
884 pdbEntry.setId(pdbIdStr);
886 pdbEntry.setType(PDBEntry.Type.PDB);
887 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
890 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
891 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
893 { selectedSequence });
895 else if (currentView == VIEWS_FROM_FILE)
897 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
898 .getCmb_assSeq().getSelectedItem()).getSequence();
899 if (userSelectedSeq != null)
901 selectedSequence = userSelectedSeq;
903 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
904 .associatePdbWithSeq(selectedPdbFileName,
905 DataSourceType.FILE, selectedSequence, true,
908 sViewer = launchStructureViewer(
912 { selectedSequence });
914 closeAction(preferredHeight);
918 Thread runner = new Thread(viewStruc);
920 if (waitUntilFinished)
922 while (sViewer == null ? runner.isAlive()
923 : (sViewer.sview == null ? true
924 : !sViewer.sview.hasMapping()))
929 } catch (InterruptedException ie)
937 private PDBEntry getFindEntry(String id, Vector<PDBEntry> pdbEntries)
939 Objects.requireNonNull(id);
940 Objects.requireNonNull(pdbEntries);
941 PDBEntry foundEntry = null;
942 for (PDBEntry entry : pdbEntries)
944 if (entry.getId().equalsIgnoreCase(id))
952 private StructureViewer launchStructureViewer(
953 StructureSelectionManager ssm,
954 final PDBEntry[] pdbEntriesToView,
955 final AlignmentPanel alignPanel, SequenceI[] sequences)
957 long progressId = sequences.hashCode();
958 setProgressBar(MessageManager
959 .getString("status.launching_3d_structure_viewer"), progressId);
960 final StructureViewer sViewer = new StructureViewer(ssm);
961 setProgressBar(null, progressId);
963 if (SiftsSettings.isMapWithSifts())
965 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
967 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
968 // real PDB ID. For moment, we can also safely do this if there is already
969 // a known mapping between the PDBEntry and the sequence.
970 for (SequenceI seq : sequences)
972 PDBEntry pdbe = pdbEntriesToView[p++];
973 if (pdbe != null && pdbe.getFile() != null)
975 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
976 if (smm != null && smm.length > 0)
978 for (StructureMapping sm : smm)
980 if (sm.getSequence() == seq)
987 if (seq.getPrimaryDBRefs().size() == 0)
989 seqsWithoutSourceDBRef.add(seq);
993 if (!seqsWithoutSourceDBRef.isEmpty())
995 int y = seqsWithoutSourceDBRef.size();
996 setProgressBar(MessageManager.formatMessage(
997 "status.fetching_dbrefs_for_sequences_without_valid_refs",
999 SequenceI[] seqWithoutSrcDBRef = new SequenceI[y];
1001 for (SequenceI fSeq : seqsWithoutSourceDBRef)
1003 seqWithoutSrcDBRef[x++] = fSeq;
1006 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
1007 dbRefFetcher.fetchDBRefs(true);
1009 setProgressBar("Fetch complete.", progressId); // todo i18n
1012 if (pdbEntriesToView.length > 1)
1014 setProgressBar(MessageManager.getString(
1015 "status.fetching_3d_structures_for_selected_entries"),
1017 sViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
1021 setProgressBar(MessageManager.formatMessage(
1022 "status.fetching_3d_structures_for",
1023 pdbEntriesToView[0].getId()),progressId);
1024 sViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1026 setProgressBar(null, progressId);
1031 * Populates the combo-box used in associating manually fetched structures to
1032 * a unique sequence when more than one sequence selection is made.
1035 public void populateCmbAssociateSeqOptions(
1036 JComboBox<AssociateSeqOptions> cmb_assSeq,
1037 JLabel lbl_associateSeq)
1039 cmb_assSeq.removeAllItems();
1041 new AssociateSeqOptions("-Select Associated Seq-", null));
1042 lbl_associateSeq.setVisible(false);
1043 if (selectedSequences.length > 1)
1045 for (SequenceI seq : selectedSequences)
1047 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1052 String seqName = selectedSequence.getDisplayId(false);
1053 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1054 lbl_associateSeq.setText(seqName);
1055 lbl_associateSeq.setVisible(true);
1056 cmb_assSeq.setVisible(false);
1060 public boolean isStructuresDiscovered()
1062 return discoveredStructuresSet != null
1063 && !discoveredStructuresSet.isEmpty();
1066 public Collection<FTSData> getDiscoveredStructuresSet()
1068 return discoveredStructuresSet;
1072 protected void txt_search_ActionPerformed()
1079 errorWarning.setLength(0);
1080 isValidPBDEntry = false;
1081 if (txt_search.getText().length() > 0)
1083 String searchTerm = txt_search.getText().toLowerCase();
1084 searchTerm = searchTerm.split(":")[0];
1085 // System.out.println(">>>>> search term : " + searchTerm);
1086 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1087 FTSRestRequest pdbRequest = new FTSRestRequest();
1088 pdbRequest.setAllowEmptySeq(false);
1089 pdbRequest.setResponseSize(1);
1090 pdbRequest.setFieldToSearchBy("(pdb_id:");
1091 pdbRequest.setWantedFields(wantedFields);
1092 pdbRequest.setSearchTerm(searchTerm + ")");
1093 pdbRequest.setAssociatedSequence(selectedSequence);
1094 pdbRestCleint = PDBFTSRestClient.getInstance();
1095 wantedFields.add(pdbRestCleint.getPrimaryKeyColumn());
1096 FTSRestResponse resultList;
1099 resultList = pdbRestCleint.executeRequest(pdbRequest);
1100 } catch (Exception e)
1102 errorWarning.append(e.getMessage());
1106 validateSelections();
1108 if (resultList.getSearchSummary() != null
1109 && resultList.getSearchSummary().size() > 0)
1111 isValidPBDEntry = true;
1114 validateSelections();
1120 public void tabRefresh()
1122 if (selectedSequences != null)
1124 Thread refreshThread = new Thread(new Runnable()
1129 fetchStructuresMetaData();
1131 ((FilterOption) cmb_filterOption.getSelectedItem())
1135 refreshThread.start();
1139 public class PDBEntryTableModel extends AbstractTableModel
1141 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1144 private List<CachedPDB> pdbEntries;
1146 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1148 this.pdbEntries = new ArrayList<>(pdbEntries);
1152 public String getColumnName(int columnIndex)
1154 return columns[columnIndex];
1158 public int getRowCount()
1160 return pdbEntries.size();
1164 public int getColumnCount()
1166 return columns.length;
1170 public boolean isCellEditable(int row, int column)
1176 public Object getValueAt(int rowIndex, int columnIndex)
1178 Object value = "??";
1179 CachedPDB entry = pdbEntries.get(rowIndex);
1180 switch (columnIndex)
1183 value = entry.getSequence();
1186 value = entry.getPdbEntry();
1189 value = entry.getPdbEntry().getChainCode() == null ? "_"
1190 : entry.getPdbEntry().getChainCode();
1193 value = entry.getPdbEntry().getType();
1196 value = entry.getPdbEntry().getFile();
1203 public Class<?> getColumnClass(int columnIndex)
1205 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1208 public CachedPDB getPDBEntryAt(int row)
1210 return pdbEntries.get(row);
1215 private class CachedPDB
1217 private SequenceI sequence;
1219 private PDBEntry pdbEntry;
1221 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1223 this.sequence = sequence;
1224 this.pdbEntry = pdbEntry;
1227 public SequenceI getSequence()
1232 public PDBEntry getPdbEntry()
1239 private IProgressIndicator progressBar;
1242 public void setProgressBar(String message, long id)
1244 progressBar.setProgressBar(message, id);
1248 public void registerHandler(long id, IProgressIndicatorHandler handler)
1250 progressBar.registerHandler(id, handler);
1254 public boolean operationInProgress()
1256 return progressBar.operationInProgress();
1259 public JalviewStructureDisplayI getOpenedStructureViewer()
1261 return sViewer == null ? null : sViewer.sview;