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.SwingUtilities;
59 import javax.swing.table.AbstractTableModel;
62 * Provides the behaviors for the Structure chooser Panel
67 @SuppressWarnings("serial")
68 public class StructureChooser extends GStructureChooser
69 implements IProgressIndicator
71 private static int MAX_QLENGTH = 7820;
73 private SequenceI selectedSequence;
75 private SequenceI[] selectedSequences;
77 private IProgressIndicator progressIndicator;
79 private Collection<FTSData> discoveredStructuresSet;
81 private FTSRestRequest lastPdbRequest;
83 private FTSRestClientI pdbRestCleint;
85 private String selectedPdbFileName;
87 private boolean isValidPBDEntry;
89 private boolean cachedPDBExists;
91 public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
95 this.selectedSequence = selectedSeq;
96 this.selectedSequences = selectedSeqs;
97 this.progressIndicator = (ap == null) ? null : ap.alignFrame;
102 * Initializes parameters used by the Structure Chooser Panel
106 if (!Jalview.isHeadlessMode())
108 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
111 // ensure a filter option is in force for search
112 populateFilterComboBox(true, cachedPDBExists);
113 Thread discoverPDBStructuresThread = new Thread(new Runnable()
118 long startTime = System.currentTimeMillis();
119 updateProgressIndicator(MessageManager
120 .getString("status.loading_cached_pdb_entries"), startTime);
121 loadLocalCachedPDBEntries();
122 updateProgressIndicator(null, startTime);
123 updateProgressIndicator(MessageManager.getString(
124 "status.searching_for_pdb_structures"), startTime);
125 fetchStructuresMetaData();
126 // revise filter options if no results were found
127 populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
128 discoverStructureViews();
129 updateProgressIndicator(null, startTime);
130 mainFrame.setVisible(true);
134 discoverPDBStructuresThread.start();
137 private void discoverStructureViews()
139 if (Desktop.instance != null)
141 targetView.removeAllItems();
143 new StructureViewer(ap.getStructureSelectionManager()));
144 if (lastTargetedView != null && !lastTargetedView.isVisible())
146 lastTargetedView = null;
148 int linkedViewsAt = 1;
149 for (StructureViewerBase view : Desktop.instance
150 .getStructureViewers(null, null))
152 StructureViewer viewHandler = (lastTargetedView != null
153 && lastTargetedView.sview == view) ? lastTargetedView
154 : StructureViewer.reconfigure(view);
156 if (view.isLinkedWith(ap))
158 targetView.insertItemAt(viewHandler,
163 targetView.addItem(viewHandler);
166 targetView.setVisible(targetView.getItemCount() > 1);
168 // finally, restore last targeted view by default.
169 if (lastTargetedView != null)
171 targetView.setSelectedItem(lastTargetedView);
176 private static StructureViewer lastTargetedView = null;
179 * Updates the progress indicator with the specified message
182 * displayed message for the operation
184 * unique handle for this indicator
186 public void updateProgressIndicator(String message, long id)
188 if (progressIndicator != null)
190 progressIndicator.setProgressBar(message, id);
195 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
198 public void fetchStructuresMetaData()
200 long startTime = System.currentTimeMillis();
201 pdbRestCleint = PDBFTSRestClient.getInstance();
202 Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
203 .getStructureSummaryFields();
205 discoveredStructuresSet = new LinkedHashSet<>();
206 HashSet<String> errors = new HashSet<>();
207 for (SequenceI seq : selectedSequences)
209 FTSRestRequest pdbRequest = new FTSRestRequest();
210 pdbRequest.setAllowEmptySeq(false);
211 pdbRequest.setResponseSize(500);
212 pdbRequest.setFieldToSearchBy("(");
213 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
215 pdbRequest.setFieldToSortBy(selectedFilterOpt.getValue(),
216 !chk_invertFilter.isSelected());
217 pdbRequest.setWantedFields(wantedFields);
218 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
219 pdbRequest.setAssociatedSequence(seq);
220 FTSRestResponse resultList;
223 resultList = pdbRestCleint.executeRequest(pdbRequest);
224 } catch (Exception e)
227 errors.add(e.getMessage());
230 lastPdbRequest = pdbRequest;
231 if (resultList.getSearchSummary() != null
232 && !resultList.getSearchSummary().isEmpty())
234 discoveredStructuresSet.addAll(resultList.getSearchSummary());
238 int noOfStructuresFound = 0;
239 String totalTime = (System.currentTimeMillis() - startTime)
241 if (discoveredStructuresSet != null
242 && !discoveredStructuresSet.isEmpty())
244 getResultTable().setModel(FTSRestResponse
245 .getTableModel(lastPdbRequest, discoveredStructuresSet));
246 noOfStructuresFound = discoveredStructuresSet.size();
247 mainFrame.setTitle(MessageManager.formatMessage(
248 "label.structure_chooser_no_of_structures",
249 noOfStructuresFound, totalTime));
253 mainFrame.setTitle(MessageManager
254 .getString("label.structure_chooser_manual_association"));
255 if (errors.size() > 0)
257 StringBuilder errorMsg = new StringBuilder();
258 for (String error : errors)
260 errorMsg.append(error).append("\n");
262 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
263 MessageManager.getString("label.pdb_web-service_error"),
264 JvOptionPane.ERROR_MESSAGE);
269 public void loadLocalCachedPDBEntries()
271 ArrayList<CachedPDB> entries = new ArrayList<>();
272 for (SequenceI seq : selectedSequences)
274 if (seq.getDatasetSequence() != null
275 && seq.getDatasetSequence().getAllPDBEntries() != null)
277 for (PDBEntry pdbEntry : seq.getDatasetSequence()
280 if (pdbEntry.getFile() != null)
282 entries.add(new CachedPDB(seq, pdbEntry));
287 cachedPDBExists = !entries.isEmpty();
288 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
289 tbl_local_pdb.setModel(tableModelx);
293 * Builds a query string for a given sequences using its DBRef entries
296 * the sequences to build a query for
297 * @return the built query string
300 public static String buildQuery(SequenceI seq)
302 boolean isPDBRefsFound = false;
303 boolean isUniProtRefsFound = false;
304 StringBuilder queryBuilder = new StringBuilder();
305 Set<String> seqRefs = new LinkedHashSet<>();
307 if (seq.getAllPDBEntries() != null
308 && queryBuilder.length() < MAX_QLENGTH)
310 for (PDBEntry entry : seq.getAllPDBEntries())
312 if (isValidSeqName(entry.getId()))
314 queryBuilder.append("pdb_id:").append(entry.getId().toLowerCase())
316 isPDBRefsFound = true;
321 if (seq.getDBRefs() != null && seq.getDBRefs().length != 0)
323 for (DBRefEntry dbRef : seq.getDBRefs())
325 if (isValidSeqName(getDBRefId(dbRef))
326 && queryBuilder.length() < MAX_QLENGTH)
328 if (dbRef.getSource().equalsIgnoreCase(DBRefSource.UNIPROT))
330 queryBuilder.append("uniprot_accession:")
331 .append(getDBRefId(dbRef)).append(" OR ");
332 queryBuilder.append("uniprot_id:").append(getDBRefId(dbRef))
334 isUniProtRefsFound = true;
336 else if (dbRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
339 queryBuilder.append("pdb_id:")
340 .append(getDBRefId(dbRef).toLowerCase()).append(" OR ");
341 isPDBRefsFound = true;
345 seqRefs.add(getDBRefId(dbRef));
351 if (!isPDBRefsFound && !isUniProtRefsFound)
353 String seqName = seq.getName();
354 seqName = sanitizeSeqName(seqName);
355 String[] names = seqName.toLowerCase().split("\\|");
356 for (String name : names)
358 // System.out.println("Found name : " + name);
360 if (isValidSeqName(name))
366 for (String seqRef : seqRefs)
368 queryBuilder.append("text:").append(seqRef).append(" OR ");
372 int endIndex = queryBuilder.lastIndexOf(" OR ");
373 if (queryBuilder.toString().length() < 6)
377 String query = queryBuilder.toString().substring(0, endIndex);
382 * Remove the following special characters from input string +, -, &, !, (, ),
383 * {, }, [, ], ^, ", ~, *, ?, :, \
388 static String sanitizeSeqName(String seqName)
390 Objects.requireNonNull(seqName);
391 return seqName.replaceAll("\\[\\d*\\]", "")
392 .replaceAll("[^\\dA-Za-z|_]", "").replaceAll("\\s+", "+");
396 * Ensures sequence ref names are not less than 3 characters and does not
397 * contain a database name
402 public static boolean isValidSeqName(String seqName)
404 // System.out.println("seqName : " + seqName);
405 String ignoreList = "pdb,uniprot,swiss-prot";
406 if (seqName.length() < 3)
410 if (seqName.contains(":"))
414 seqName = seqName.toLowerCase();
415 for (String ignoredEntry : ignoreList.split(","))
417 if (seqName.contains(ignoredEntry))
425 public static String getDBRefId(DBRefEntry dbRef)
427 String ref = dbRef.getAccessionId().replaceAll("GO:", "");
432 * Filters a given list of discovered structures based on supplied argument
434 * @param fieldToFilterBy
435 * the field to filter by
437 public void filterResultSet(final String fieldToFilterBy)
439 Thread filterThread = new Thread(new Runnable()
444 long startTime = System.currentTimeMillis();
445 pdbRestCleint = PDBFTSRestClient.getInstance();
446 lbl_loading.setVisible(true);
447 Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
448 .getStructureSummaryFields();
449 Collection<FTSData> filteredResponse = new HashSet<>();
450 HashSet<String> errors = new HashSet<>();
452 for (SequenceI seq : selectedSequences)
454 FTSRestRequest pdbRequest = new FTSRestRequest();
455 if (fieldToFilterBy.equalsIgnoreCase("uniprot_coverage"))
457 pdbRequest.setAllowEmptySeq(false);
458 pdbRequest.setResponseSize(1);
459 pdbRequest.setFieldToSearchBy("(");
460 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
461 pdbRequest.setWantedFields(wantedFields);
462 pdbRequest.setAssociatedSequence(seq);
463 pdbRequest.setFacet(true);
464 pdbRequest.setFacetPivot(fieldToFilterBy + ",entry_entity");
465 pdbRequest.setFacetPivotMinCount(1);
469 pdbRequest.setAllowEmptySeq(false);
470 pdbRequest.setResponseSize(1);
471 pdbRequest.setFieldToSearchBy("(");
472 pdbRequest.setFieldToSortBy(fieldToFilterBy,
473 !chk_invertFilter.isSelected());
474 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
475 pdbRequest.setWantedFields(wantedFields);
476 pdbRequest.setAssociatedSequence(seq);
478 FTSRestResponse resultList;
481 resultList = pdbRestCleint.executeRequest(pdbRequest);
482 } catch (Exception e)
485 errors.add(e.getMessage());
488 lastPdbRequest = pdbRequest;
489 if (resultList.getSearchSummary() != null
490 && !resultList.getSearchSummary().isEmpty())
492 filteredResponse.addAll(resultList.getSearchSummary());
496 String totalTime = (System.currentTimeMillis() - startTime)
498 if (!filteredResponse.isEmpty())
500 final int filterResponseCount = filteredResponse.size();
501 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
502 reorderedStructuresSet.addAll(filteredResponse);
503 reorderedStructuresSet.addAll(discoveredStructuresSet);
504 getResultTable().setModel(FTSRestResponse
505 .getTableModel(lastPdbRequest, reorderedStructuresSet));
507 FTSRestResponse.configureTableColumn(getResultTable(),
508 wantedFields, tempUserPrefs);
509 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
510 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
511 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
512 // Update table selection model here
513 getResultTable().addRowSelectionInterval(0,
514 filterResponseCount - 1);
515 mainFrame.setTitle(MessageManager.formatMessage(
516 "label.structure_chooser_filter_time", totalTime));
520 mainFrame.setTitle(MessageManager.formatMessage(
521 "label.structure_chooser_filter_time", totalTime));
522 if (errors.size() > 0)
524 StringBuilder errorMsg = new StringBuilder();
525 for (String error : errors)
527 errorMsg.append(error).append("\n");
529 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
530 MessageManager.getString("label.pdb_web-service_error"),
531 JvOptionPane.ERROR_MESSAGE);
535 lbl_loading.setVisible(false);
537 validateSelections();
540 filterThread.start();
544 * Handles action event for btn_pdbFromFile
547 public void pdbFromFile_actionPerformed()
549 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
550 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
551 chooser.setFileView(new jalview.io.JalviewFileView());
552 chooser.setDialogTitle(
553 MessageManager.formatMessage("label.select_pdb_file_for",
554 selectedSequence.getDisplayId(false)));
555 chooser.setToolTipText(MessageManager.formatMessage(
556 "label.load_pdb_file_associate_with_sequence",
557 selectedSequence.getDisplayId(false)));
559 int value = chooser.showOpenDialog(null);
560 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
562 selectedPdbFileName = chooser.getSelectedFile().getPath();
563 jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
564 validateSelections();
569 * Populates the filter combo-box options dynamically depending on discovered
572 protected void populateFilterComboBox(boolean haveData,
573 boolean cachedPDBExist)
576 * temporarily suspend the change listener behaviour
578 cmb_filterOption.removeItemListener(this);
580 cmb_filterOption.removeAllItems();
583 cmb_filterOption.addItem(new FilterOption(
584 MessageManager.getString("label.best_quality"),
585 "overall_quality", VIEWS_FILTER, false));
586 cmb_filterOption.addItem(new FilterOption(
587 MessageManager.getString("label.best_resolution"),
588 "resolution", VIEWS_FILTER, false));
589 cmb_filterOption.addItem(new FilterOption(
590 MessageManager.getString("label.most_protein_chain"),
591 "number_of_protein_chains", VIEWS_FILTER, false));
592 cmb_filterOption.addItem(new FilterOption(
593 MessageManager.getString("label.most_bound_molecules"),
594 "number_of_bound_molecules", VIEWS_FILTER, false));
595 cmb_filterOption.addItem(new FilterOption(
596 MessageManager.getString("label.most_polymer_residues"),
597 "number_of_polymer_residues", VIEWS_FILTER, true));
599 cmb_filterOption.addItem(
600 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
601 "-", VIEWS_ENTER_ID, false));
602 cmb_filterOption.addItem(
603 new FilterOption(MessageManager.getString("label.from_file"),
604 "-", VIEWS_FROM_FILE, false));
608 FilterOption cachedOption = new FilterOption(
609 MessageManager.getString("label.cached_structures"),
610 "-", VIEWS_LOCAL_PDB, false);
611 cmb_filterOption.addItem(cachedOption);
612 cmb_filterOption.setSelectedItem(cachedOption);
615 cmb_filterOption.addItemListener(this);
619 * Updates the displayed view based on the selected filter option
621 protected void updateCurrentView()
623 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
625 layout_switchableViews.show(pnl_switchableViews,
626 selectedFilterOpt.getView());
627 String filterTitle = mainFrame.getTitle();
628 mainFrame.setTitle(frameTitle);
629 chk_invertFilter.setVisible(false);
630 if (selectedFilterOpt.getView() == VIEWS_FILTER)
632 mainFrame.setTitle(filterTitle);
633 chk_invertFilter.setVisible(true);
634 filterResultSet(selectedFilterOpt.getValue());
636 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
637 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
639 mainFrame.setTitle(MessageManager
640 .getString("label.structure_chooser_manual_association"));
641 idInputAssSeqPanel.loadCmbAssSeq();
642 fileChooserAssSeqPanel.loadCmbAssSeq();
644 validateSelections();
648 * Validates user selection and activates the view button if all parameters
652 public void validateSelections()
654 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
656 btn_view.setEnabled(false);
657 String currentView = selectedFilterOpt.getView();
658 if (currentView == VIEWS_FILTER)
660 if (getResultTable().getSelectedRows().length > 0)
662 btn_view.setEnabled(true);
665 else if (currentView == VIEWS_LOCAL_PDB)
667 if (tbl_local_pdb.getSelectedRows().length > 0)
669 btn_view.setEnabled(true);
672 else if (currentView == VIEWS_ENTER_ID)
674 validateAssociationEnterPdb();
676 else if (currentView == VIEWS_FROM_FILE)
678 validateAssociationFromFile();
683 * Validates inputs from the Manual PDB entry panel
685 public void validateAssociationEnterPdb()
687 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
688 .getCmb_assSeq().getSelectedItem();
689 lbl_pdbManualFetchStatus.setIcon(errorImage);
690 lbl_pdbManualFetchStatus.setToolTipText("");
691 if (txt_search.getText().length() > 0)
693 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
694 MessageManager.formatMessage("info.no_pdb_entry_found_for",
695 txt_search.getText())));
698 if (errorWarning.length() > 0)
700 lbl_pdbManualFetchStatus.setIcon(warningImage);
701 lbl_pdbManualFetchStatus.setToolTipText(
702 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
705 if (selectedSequences.length == 1 || !assSeqOpt.getName()
706 .equalsIgnoreCase("-Select Associated Seq-"))
708 txt_search.setEnabled(true);
711 btn_view.setEnabled(true);
712 lbl_pdbManualFetchStatus.setToolTipText("");
713 lbl_pdbManualFetchStatus.setIcon(goodImage);
718 txt_search.setEnabled(false);
719 lbl_pdbManualFetchStatus.setIcon(errorImage);
724 * Validates inputs for the manual PDB file selection options
726 public void validateAssociationFromFile()
728 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
729 .getCmb_assSeq().getSelectedItem();
730 lbl_fromFileStatus.setIcon(errorImage);
731 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
732 .getName().equalsIgnoreCase("-Select Associated Seq-")))
734 btn_pdbFromFile.setEnabled(true);
735 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
737 btn_view.setEnabled(true);
738 lbl_fromFileStatus.setIcon(goodImage);
743 btn_pdbFromFile.setEnabled(false);
744 lbl_fromFileStatus.setIcon(errorImage);
749 public void cmbAssSeqStateChanged()
751 validateSelections();
755 * Handles the state change event for the 'filter' combo-box and 'invert'
759 protected void stateChanged(ItemEvent e)
761 if (e.getSource() instanceof JCheckBox)
767 if (e.getStateChange() == ItemEvent.SELECTED)
776 * select structures for viewing by their PDB IDs
779 * @return true if structures were found and marked as selected
781 public boolean selectStructure(String... pdbids)
783 boolean found = false;
785 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
787 String currentView = selectedFilterOpt.getView();
788 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
789 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
791 if (restable == null)
793 // can't select (enter PDB ID, or load file - need to also select which
794 // sequence to associate with)
798 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
799 for (int r = 0; r < restable.getRowCount(); r++)
801 for (int p = 0; p < pdbids.length; p++)
803 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
804 .equalsIgnoreCase(pdbids[p]))
806 restable.setRowSelectionInterval(r, r);
814 * Handles action event for btn_ok
817 public void ok_ActionPerformed()
819 showStructures(false);
823 * structure viewer opened by this dialog, or null
825 private StructureViewer sViewer = null;
827 public void showStructures(boolean waitUntilFinished)
830 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
832 final int preferredHeight = pnl_filter.getHeight();
834 Runnable viewStruc = new Runnable()
839 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
841 String currentView = selectedFilterOpt.getView();
842 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
845 if (currentView == VIEWS_FILTER)
847 int pdbIdColIndex = restable.getColumn("PDB Id")
849 int refSeqColIndex = restable.getColumn("Ref Sequence")
851 int[] selectedRows = restable.getSelectedRows();
852 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
854 List<SequenceI> selectedSeqsToView = new ArrayList<>();
855 for (int row : selectedRows)
857 String pdbIdStr = restable
858 .getValueAt(row, pdbIdColIndex).toString();
859 SequenceI selectedSeq = (SequenceI) restable
860 .getValueAt(row, refSeqColIndex);
861 selectedSeqsToView.add(selectedSeq);
862 PDBEntry pdbEntry = selectedSeq.getPDBEntry(pdbIdStr);
863 if (pdbEntry == null)
865 pdbEntry = getFindEntry(pdbIdStr,
866 selectedSeq.getAllPDBEntries());
869 if (pdbEntry == null)
871 pdbEntry = new PDBEntry();
872 pdbEntry.setId(pdbIdStr);
873 pdbEntry.setType(PDBEntry.Type.PDB);
874 selectedSeq.getDatasetSequence().addPDBId(pdbEntry);
876 pdbEntriesToView[count++] = pdbEntry;
878 SequenceI[] selectedSeqs = selectedSeqsToView
879 .toArray(new SequenceI[selectedSeqsToView.size()]);
880 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
883 else if (currentView == VIEWS_LOCAL_PDB)
885 int[] selectedRows = tbl_local_pdb.getSelectedRows();
886 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
888 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
890 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
892 List<SequenceI> selectedSeqsToView = new ArrayList<>();
893 for (int row : selectedRows)
895 PDBEntry pdbEntry = (PDBEntry) tbl_local_pdb.getValueAt(row,
897 pdbEntriesToView[count++] = pdbEntry;
898 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
899 .getValueAt(row, refSeqColIndex);
900 selectedSeqsToView.add(selectedSeq);
902 SequenceI[] selectedSeqs = selectedSeqsToView
903 .toArray(new SequenceI[selectedSeqsToView.size()]);
904 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
907 else if (currentView == VIEWS_ENTER_ID)
909 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
910 .getCmb_assSeq().getSelectedItem()).getSequence();
911 if (userSelectedSeq != null)
913 selectedSequence = userSelectedSeq;
915 String pdbIdStr = txt_search.getText();
916 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
917 if (pdbEntry == null)
919 pdbEntry = new PDBEntry();
920 if (pdbIdStr.split(":").length > 1)
922 pdbEntry.setId(pdbIdStr.split(":")[0]);
923 pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase());
927 pdbEntry.setId(pdbIdStr);
929 pdbEntry.setType(PDBEntry.Type.PDB);
930 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
933 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
934 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
936 { selectedSequence });
938 else if (currentView == VIEWS_FROM_FILE)
940 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
941 .getCmb_assSeq().getSelectedItem()).getSequence();
942 if (userSelectedSeq != null)
944 selectedSequence = userSelectedSeq;
946 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
947 .associatePdbWithSeq(selectedPdbFileName,
948 DataSourceType.FILE, selectedSequence, true,
951 sViewer = launchStructureViewer(
955 { selectedSequence });
957 SwingUtilities.invokeLater(new Runnable()
962 closeAction(preferredHeight);
968 Thread runner = new Thread(viewStruc);
970 if (waitUntilFinished)
972 while (sViewer == null ? runner.isAlive()
973 : (sViewer.sview == null ? true
974 : !sViewer.sview.hasMapping()))
979 } catch (InterruptedException ie)
987 private PDBEntry getFindEntry(String id, Vector<PDBEntry> pdbEntries)
989 Objects.requireNonNull(id);
990 Objects.requireNonNull(pdbEntries);
991 PDBEntry foundEntry = null;
992 for (PDBEntry entry : pdbEntries)
994 if (entry.getId().equalsIgnoreCase(id))
1002 public StructureViewer getTargetedStructureViewer(
1003 StructureSelectionManager ssm)
1005 Object _sv = targetView.getSelectedItem();
1009 return new StructureViewer(ssm);
1011 return (StructureViewer) _sv;
1014 private StructureViewer launchStructureViewer(
1015 StructureSelectionManager ssm,
1016 final PDBEntry[] pdbEntriesToView,
1017 final AlignmentPanel alignPanel, SequenceI[] sequences)
1019 long progressId = sequences.hashCode();
1020 setProgressBar(MessageManager
1021 .getString("status.launching_3d_structure_viewer"), progressId);
1022 final StructureViewer sViewer = getTargetedStructureViewer(ssm);
1024 setProgressBar(null, progressId);
1025 if (SiftsSettings.isMapWithSifts())
1027 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
1029 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1030 // real PDB ID. For moment, we can also safely do this if there is already
1031 // a known mapping between the PDBEntry and the sequence.
1032 for (SequenceI seq : sequences)
1034 PDBEntry pdbe = pdbEntriesToView[p++];
1035 if (pdbe != null && pdbe.getFile() != null)
1037 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1038 if (smm != null && smm.length > 0)
1040 for (StructureMapping sm : smm)
1042 if (sm.getSequence() == seq)
1049 if (seq.getPrimaryDBRefs().size() == 0)
1051 seqsWithoutSourceDBRef.add(seq);
1055 if (!seqsWithoutSourceDBRef.isEmpty())
1057 int y = seqsWithoutSourceDBRef.size();
1058 setProgressBar(MessageManager.formatMessage(
1059 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1061 SequenceI[] seqWithoutSrcDBRef = new SequenceI[y];
1063 for (SequenceI fSeq : seqsWithoutSourceDBRef)
1065 seqWithoutSrcDBRef[x++] = fSeq;
1068 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
1069 dbRefFetcher.fetchDBRefs(true);
1071 setProgressBar("Fetch complete.", progressId); // todo i18n
1074 if (pdbEntriesToView.length > 1)
1076 setProgressBar(MessageManager.getString(
1077 "status.fetching_3d_structures_for_selected_entries"),
1079 sViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
1083 setProgressBar(MessageManager.formatMessage(
1084 "status.fetching_3d_structures_for",
1085 pdbEntriesToView[0].getId()),progressId);
1086 sViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1088 setProgressBar(null, progressId);
1089 // remember the last viewer we used...
1090 lastTargetedView = sViewer;
1095 * Populates the combo-box used in associating manually fetched structures to
1096 * a unique sequence when more than one sequence selection is made.
1099 public void populateCmbAssociateSeqOptions(
1100 JComboBox<AssociateSeqOptions> cmb_assSeq,
1101 JLabel lbl_associateSeq)
1103 cmb_assSeq.removeAllItems();
1105 new AssociateSeqOptions("-Select Associated Seq-", null));
1106 lbl_associateSeq.setVisible(false);
1107 if (selectedSequences.length > 1)
1109 for (SequenceI seq : selectedSequences)
1111 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1116 String seqName = selectedSequence.getDisplayId(false);
1117 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1118 lbl_associateSeq.setText(seqName);
1119 lbl_associateSeq.setVisible(true);
1120 cmb_assSeq.setVisible(false);
1124 public boolean isStructuresDiscovered()
1126 return discoveredStructuresSet != null
1127 && !discoveredStructuresSet.isEmpty();
1130 public Collection<FTSData> getDiscoveredStructuresSet()
1132 return discoveredStructuresSet;
1136 protected void txt_search_ActionPerformed()
1143 errorWarning.setLength(0);
1144 isValidPBDEntry = false;
1145 if (txt_search.getText().length() > 0)
1147 String searchTerm = txt_search.getText().toLowerCase();
1148 searchTerm = searchTerm.split(":")[0];
1149 // System.out.println(">>>>> search term : " + searchTerm);
1150 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1151 FTSRestRequest pdbRequest = new FTSRestRequest();
1152 pdbRequest.setAllowEmptySeq(false);
1153 pdbRequest.setResponseSize(1);
1154 pdbRequest.setFieldToSearchBy("(pdb_id:");
1155 pdbRequest.setWantedFields(wantedFields);
1156 pdbRequest.setSearchTerm(searchTerm + ")");
1157 pdbRequest.setAssociatedSequence(selectedSequence);
1158 pdbRestCleint = PDBFTSRestClient.getInstance();
1159 wantedFields.add(pdbRestCleint.getPrimaryKeyColumn());
1160 FTSRestResponse resultList;
1163 resultList = pdbRestCleint.executeRequest(pdbRequest);
1164 } catch (Exception e)
1166 errorWarning.append(e.getMessage());
1170 validateSelections();
1172 if (resultList.getSearchSummary() != null
1173 && resultList.getSearchSummary().size() > 0)
1175 isValidPBDEntry = true;
1178 validateSelections();
1184 public void tabRefresh()
1186 if (selectedSequences != null)
1188 Thread refreshThread = new Thread(new Runnable()
1193 fetchStructuresMetaData();
1195 ((FilterOption) cmb_filterOption.getSelectedItem())
1199 refreshThread.start();
1203 public class PDBEntryTableModel extends AbstractTableModel
1205 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1208 private List<CachedPDB> pdbEntries;
1210 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1212 this.pdbEntries = new ArrayList<>(pdbEntries);
1216 public String getColumnName(int columnIndex)
1218 return columns[columnIndex];
1222 public int getRowCount()
1224 return pdbEntries.size();
1228 public int getColumnCount()
1230 return columns.length;
1234 public boolean isCellEditable(int row, int column)
1240 public Object getValueAt(int rowIndex, int columnIndex)
1242 Object value = "??";
1243 CachedPDB entry = pdbEntries.get(rowIndex);
1244 switch (columnIndex)
1247 value = entry.getSequence();
1250 value = entry.getPdbEntry();
1253 value = entry.getPdbEntry().getChainCode() == null ? "_"
1254 : entry.getPdbEntry().getChainCode();
1257 value = entry.getPdbEntry().getType();
1260 value = entry.getPdbEntry().getFile();
1267 public Class<?> getColumnClass(int columnIndex)
1269 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1272 public CachedPDB getPDBEntryAt(int row)
1274 return pdbEntries.get(row);
1279 private class CachedPDB
1281 private SequenceI sequence;
1283 private PDBEntry pdbEntry;
1285 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1287 this.sequence = sequence;
1288 this.pdbEntry = pdbEntry;
1291 public SequenceI getSequence()
1296 public PDBEntry getPdbEntry()
1303 private IProgressIndicator progressBar;
1306 public void setProgressBar(String message, long id)
1308 progressBar.setProgressBar(message, id);
1312 public void registerHandler(long id, IProgressIndicatorHandler handler)
1314 progressBar.registerHandler(id, handler);
1318 public boolean operationInProgress()
1320 return progressBar.operationInProgress();
1323 public JalviewStructureDisplayI getOpenedStructureViewer()
1325 return sViewer == null ? null : sViewer.sview;