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.Cache;
26 import jalview.bin.Jalview;
27 import jalview.datamodel.DBRefEntry;
28 import jalview.datamodel.DBRefSource;
29 import jalview.datamodel.PDBEntry;
30 import jalview.datamodel.SequenceI;
31 import jalview.fts.api.FTSData;
32 import jalview.fts.api.FTSDataColumnI;
33 import jalview.fts.api.FTSRestClientI;
34 import jalview.fts.core.FTSRestRequest;
35 import jalview.fts.core.FTSRestResponse;
36 import jalview.fts.service.pdb.PDBFTSRestClient;
37 import jalview.io.DataSourceType;
38 import jalview.jbgui.GStructureChooser;
39 import jalview.structure.StructureMapping;
40 import jalview.structure.StructureSelectionManager;
41 import jalview.util.MessageManager;
42 import jalview.ws.DBRefFetcher;
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.JTable;
59 import javax.swing.SwingUtilities;
60 import javax.swing.table.AbstractTableModel;
63 * Provides the behaviors for the Structure chooser Panel
68 @SuppressWarnings("serial")
69 public class StructureChooser extends GStructureChooser
70 implements IProgressIndicator
72 private static int MAX_QLENGTH = 7820;
74 private SequenceI selectedSequence;
76 private SequenceI[] selectedSequences;
78 private IProgressIndicator progressIndicator;
80 private Collection<FTSData> discoveredStructuresSet;
82 private FTSRestRequest lastPdbRequest;
84 private FTSRestClientI pdbRestCleint;
86 private String selectedPdbFileName;
88 private boolean isValidPBDEntry;
90 private boolean cachedPDBExists;
92 public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
96 this.selectedSequence = selectedSeq;
97 this.selectedSequences = selectedSeqs;
98 this.progressIndicator = (ap == null) ? null : ap.alignFrame;
103 * Initializes parameters used by the Structure Chooser Panel
107 if (!Jalview.isHeadlessMode())
109 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
112 chk_superpose.setSelected(Cache.getDefault("AUTOSUPERIMPOSE", true));
114 // ensure a filter option is in force for search
115 populateFilterComboBox(true, cachedPDBExists);
116 Thread discoverPDBStructuresThread = new Thread(new Runnable()
121 long startTime = System.currentTimeMillis();
122 updateProgressIndicator(MessageManager
123 .getString("status.loading_cached_pdb_entries"), startTime);
124 loadLocalCachedPDBEntries();
125 updateProgressIndicator(null, startTime);
126 updateProgressIndicator(MessageManager.getString(
127 "status.searching_for_pdb_structures"), startTime);
128 fetchStructuresMetaData();
129 // revise filter options if no results were found
130 populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
131 discoverStructureViews();
132 updateProgressIndicator(null, startTime);
133 mainFrame.setVisible(true);
137 discoverPDBStructuresThread.start();
140 private void discoverStructureViews()
142 if (Desktop.instance != null)
144 targetView.removeAllItems();
145 if (lastTargetedView != null && !lastTargetedView.isVisible())
147 lastTargetedView = null;
149 int linkedViewsAt = 0;
150 for (StructureViewerBase view : Desktop.instance
151 .getStructureViewers(null, null))
153 StructureViewer viewHandler = (lastTargetedView != null
154 && lastTargetedView.sview == view) ? lastTargetedView
155 : StructureViewer.reconfigure(view);
157 if (view.isLinkedWith(ap))
159 targetView.insertItemAt(viewHandler,
164 targetView.addItem(viewHandler);
167 targetView.setVisible(targetView.getItemCount() > 0);
168 btn_view.setVisible(targetView.isVisible());
169 if (targetView.isVisible()) {
170 // finally, restore last targeted view by default.
171 if (lastTargetedView != null)
173 targetView.setSelectedItem(lastTargetedView);
175 targetView.setSelectedIndex(0);
181 private static StructureViewer lastTargetedView = null;
184 * Updates the progress indicator with the specified message
187 * displayed message for the operation
189 * unique handle for this indicator
191 public void updateProgressIndicator(String message, long id)
193 if (progressIndicator != null)
195 progressIndicator.setProgressBar(message, id);
200 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
203 public void fetchStructuresMetaData()
205 long startTime = System.currentTimeMillis();
206 pdbRestCleint = PDBFTSRestClient.getInstance();
207 Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
208 .getStructureSummaryFields();
210 discoveredStructuresSet = new LinkedHashSet<>();
211 HashSet<String> errors = new HashSet<>();
212 for (SequenceI seq : selectedSequences)
214 FTSRestRequest pdbRequest = new FTSRestRequest();
215 pdbRequest.setAllowEmptySeq(false);
216 pdbRequest.setResponseSize(500);
217 pdbRequest.setFieldToSearchBy("(");
218 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
220 pdbRequest.setFieldToSortBy(selectedFilterOpt.getValue(),
221 !chk_invertFilter.isSelected());
222 pdbRequest.setWantedFields(wantedFields);
223 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
224 pdbRequest.setAssociatedSequence(seq);
225 FTSRestResponse resultList;
228 resultList = pdbRestCleint.executeRequest(pdbRequest);
229 } catch (Exception e)
232 errors.add(e.getMessage());
235 lastPdbRequest = pdbRequest;
236 if (resultList.getSearchSummary() != null
237 && !resultList.getSearchSummary().isEmpty())
239 discoveredStructuresSet.addAll(resultList.getSearchSummary());
243 int noOfStructuresFound = 0;
244 String totalTime = (System.currentTimeMillis() - startTime)
246 if (discoveredStructuresSet != null
247 && !discoveredStructuresSet.isEmpty())
249 getResultTable().setModel(FTSRestResponse
250 .getTableModel(lastPdbRequest, discoveredStructuresSet));
251 noOfStructuresFound = discoveredStructuresSet.size();
252 mainFrame.setTitle(MessageManager.formatMessage(
253 "label.structure_chooser_no_of_structures",
254 noOfStructuresFound, totalTime));
258 mainFrame.setTitle(MessageManager
259 .getString("label.structure_chooser_manual_association"));
260 if (errors.size() > 0)
262 StringBuilder errorMsg = new StringBuilder();
263 for (String error : errors)
265 errorMsg.append(error).append("\n");
267 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
268 MessageManager.getString("label.pdb_web-service_error"),
269 JvOptionPane.ERROR_MESSAGE);
274 public void loadLocalCachedPDBEntries()
276 ArrayList<CachedPDB> entries = new ArrayList<>();
277 for (SequenceI seq : selectedSequences)
279 if (seq.getDatasetSequence() != null
280 && seq.getDatasetSequence().getAllPDBEntries() != null)
282 for (PDBEntry pdbEntry : seq.getDatasetSequence()
285 if (pdbEntry.getFile() != null)
287 entries.add(new CachedPDB(seq, pdbEntry));
292 cachedPDBExists = !entries.isEmpty();
293 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
294 tbl_local_pdb.setModel(tableModelx);
298 * Builds a query string for a given sequences using its DBRef entries
301 * the sequences to build a query for
302 * @return the built query string
305 public static String buildQuery(SequenceI seq)
307 boolean isPDBRefsFound = false;
308 boolean isUniProtRefsFound = false;
309 StringBuilder queryBuilder = new StringBuilder();
310 Set<String> seqRefs = new LinkedHashSet<>();
312 if (seq.getAllPDBEntries() != null
313 && queryBuilder.length() < MAX_QLENGTH)
315 for (PDBEntry entry : seq.getAllPDBEntries())
317 if (isValidSeqName(entry.getId()))
319 queryBuilder.append("pdb_id:").append(entry.getId().toLowerCase())
321 isPDBRefsFound = true;
326 if (seq.getDBRefs() != null && seq.getDBRefs().length != 0)
328 for (DBRefEntry dbRef : seq.getDBRefs())
330 if (isValidSeqName(getDBRefId(dbRef))
331 && queryBuilder.length() < MAX_QLENGTH)
333 if (dbRef.getSource().equalsIgnoreCase(DBRefSource.UNIPROT))
335 queryBuilder.append("uniprot_accession:")
336 .append(getDBRefId(dbRef)).append(" OR ");
337 queryBuilder.append("uniprot_id:").append(getDBRefId(dbRef))
339 isUniProtRefsFound = true;
341 else if (dbRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
344 queryBuilder.append("pdb_id:")
345 .append(getDBRefId(dbRef).toLowerCase()).append(" OR ");
346 isPDBRefsFound = true;
350 seqRefs.add(getDBRefId(dbRef));
356 if (!isPDBRefsFound && !isUniProtRefsFound)
358 String seqName = seq.getName();
359 seqName = sanitizeSeqName(seqName);
360 String[] names = seqName.toLowerCase().split("\\|");
361 for (String name : names)
363 // System.out.println("Found name : " + name);
365 if (isValidSeqName(name))
371 for (String seqRef : seqRefs)
373 queryBuilder.append("text:").append(seqRef).append(" OR ");
377 int endIndex = queryBuilder.lastIndexOf(" OR ");
378 if (queryBuilder.toString().length() < 6)
382 String query = queryBuilder.toString().substring(0, endIndex);
387 * Remove the following special characters from input string +, -, &, !, (, ),
388 * {, }, [, ], ^, ", ~, *, ?, :, \
393 static String sanitizeSeqName(String seqName)
395 Objects.requireNonNull(seqName);
396 return seqName.replaceAll("\\[\\d*\\]", "")
397 .replaceAll("[^\\dA-Za-z|_]", "").replaceAll("\\s+", "+");
401 * Ensures sequence ref names are not less than 3 characters and does not
402 * contain a database name
407 public static boolean isValidSeqName(String seqName)
409 // System.out.println("seqName : " + seqName);
410 String ignoreList = "pdb,uniprot,swiss-prot";
411 if (seqName.length() < 3)
415 if (seqName.contains(":"))
419 seqName = seqName.toLowerCase();
420 for (String ignoredEntry : ignoreList.split(","))
422 if (seqName.contains(ignoredEntry))
430 public static String getDBRefId(DBRefEntry dbRef)
432 String ref = dbRef.getAccessionId().replaceAll("GO:", "");
437 * Filters a given list of discovered structures based on supplied argument
439 * @param fieldToFilterBy
440 * the field to filter by
442 public void filterResultSet(final String fieldToFilterBy)
444 Thread filterThread = new Thread(new Runnable()
449 long startTime = System.currentTimeMillis();
450 pdbRestCleint = PDBFTSRestClient.getInstance();
451 lbl_loading.setVisible(true);
452 Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
453 .getStructureSummaryFields();
454 Collection<FTSData> filteredResponse = new HashSet<>();
455 HashSet<String> errors = new HashSet<>();
457 for (SequenceI seq : selectedSequences)
459 FTSRestRequest pdbRequest = new FTSRestRequest();
460 if (fieldToFilterBy.equalsIgnoreCase("uniprot_coverage"))
462 pdbRequest.setAllowEmptySeq(false);
463 pdbRequest.setResponseSize(1);
464 pdbRequest.setFieldToSearchBy("(");
465 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
466 pdbRequest.setWantedFields(wantedFields);
467 pdbRequest.setAssociatedSequence(seq);
468 pdbRequest.setFacet(true);
469 pdbRequest.setFacetPivot(fieldToFilterBy + ",entry_entity");
470 pdbRequest.setFacetPivotMinCount(1);
474 pdbRequest.setAllowEmptySeq(false);
475 pdbRequest.setResponseSize(1);
476 pdbRequest.setFieldToSearchBy("(");
477 pdbRequest.setFieldToSortBy(fieldToFilterBy,
478 !chk_invertFilter.isSelected());
479 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
480 pdbRequest.setWantedFields(wantedFields);
481 pdbRequest.setAssociatedSequence(seq);
483 FTSRestResponse resultList;
486 resultList = pdbRestCleint.executeRequest(pdbRequest);
487 } catch (Exception e)
490 errors.add(e.getMessage());
493 lastPdbRequest = pdbRequest;
494 if (resultList.getSearchSummary() != null
495 && !resultList.getSearchSummary().isEmpty())
497 filteredResponse.addAll(resultList.getSearchSummary());
501 String totalTime = (System.currentTimeMillis() - startTime)
503 if (!filteredResponse.isEmpty())
505 final int filterResponseCount = filteredResponse.size();
506 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
507 reorderedStructuresSet.addAll(filteredResponse);
508 reorderedStructuresSet.addAll(discoveredStructuresSet);
509 getResultTable().setModel(FTSRestResponse
510 .getTableModel(lastPdbRequest, reorderedStructuresSet));
512 FTSRestResponse.configureTableColumn(getResultTable(),
513 wantedFields, tempUserPrefs);
514 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
515 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
516 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
517 // Update table selection model here
518 getResultTable().addRowSelectionInterval(0,
519 filterResponseCount - 1);
520 mainFrame.setTitle(MessageManager.formatMessage(
521 "label.structure_chooser_filter_time", totalTime));
525 mainFrame.setTitle(MessageManager.formatMessage(
526 "label.structure_chooser_filter_time", totalTime));
527 if (errors.size() > 0)
529 StringBuilder errorMsg = new StringBuilder();
530 for (String error : errors)
532 errorMsg.append(error).append("\n");
534 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
535 MessageManager.getString("label.pdb_web-service_error"),
536 JvOptionPane.ERROR_MESSAGE);
540 lbl_loading.setVisible(false);
542 validateSelections();
545 filterThread.start();
549 * Handles action event for btn_pdbFromFile
552 public void pdbFromFile_actionPerformed()
554 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
555 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
556 chooser.setFileView(new jalview.io.JalviewFileView());
557 chooser.setDialogTitle(
558 MessageManager.formatMessage("label.select_pdb_file_for",
559 selectedSequence.getDisplayId(false)));
560 chooser.setToolTipText(MessageManager.formatMessage(
561 "label.load_pdb_file_associate_with_sequence",
562 selectedSequence.getDisplayId(false)));
564 int value = chooser.showOpenDialog(null);
565 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
567 selectedPdbFileName = chooser.getSelectedFile().getPath();
568 jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
569 validateSelections();
574 * Populates the filter combo-box options dynamically depending on discovered
577 protected void populateFilterComboBox(boolean haveData,
578 boolean cachedPDBExist)
581 * temporarily suspend the change listener behaviour
583 cmb_filterOption.removeItemListener(this);
585 cmb_filterOption.removeAllItems();
588 cmb_filterOption.addItem(new FilterOption(
589 MessageManager.getString("label.best_quality"),
590 "overall_quality", VIEWS_FILTER, false));
591 cmb_filterOption.addItem(new FilterOption(
592 MessageManager.getString("label.best_resolution"),
593 "resolution", VIEWS_FILTER, false));
594 cmb_filterOption.addItem(new FilterOption(
595 MessageManager.getString("label.most_protein_chain"),
596 "number_of_protein_chains", VIEWS_FILTER, false));
597 cmb_filterOption.addItem(new FilterOption(
598 MessageManager.getString("label.most_bound_molecules"),
599 "number_of_bound_molecules", VIEWS_FILTER, false));
600 cmb_filterOption.addItem(new FilterOption(
601 MessageManager.getString("label.most_polymer_residues"),
602 "number_of_polymer_residues", VIEWS_FILTER, true));
604 cmb_filterOption.addItem(
605 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
606 "-", VIEWS_ENTER_ID, false));
607 cmb_filterOption.addItem(
608 new FilterOption(MessageManager.getString("label.from_file"),
609 "-", VIEWS_FROM_FILE, false));
613 FilterOption cachedOption = new FilterOption(
614 MessageManager.getString("label.cached_structures"),
615 "-", VIEWS_LOCAL_PDB, false);
616 cmb_filterOption.addItem(cachedOption);
617 cmb_filterOption.setSelectedItem(cachedOption);
620 cmb_filterOption.addItemListener(this);
624 * Updates the displayed view based on the selected filter option
626 protected void updateCurrentView()
628 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
630 layout_switchableViews.show(pnl_switchableViews,
631 selectedFilterOpt.getView());
632 String filterTitle = mainFrame.getTitle();
633 mainFrame.setTitle(frameTitle);
634 chk_invertFilter.setVisible(false);
635 if (selectedFilterOpt.getView() == VIEWS_FILTER)
637 mainFrame.setTitle(filterTitle);
638 chk_invertFilter.setVisible(true);
639 filterResultSet(selectedFilterOpt.getValue());
641 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
642 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
644 mainFrame.setTitle(MessageManager
645 .getString("label.structure_chooser_manual_association"));
646 idInputAssSeqPanel.loadCmbAssSeq();
647 fileChooserAssSeqPanel.loadCmbAssSeq();
649 validateSelections();
653 * Validates user selection and activates the view button if all parameters
657 public void validateSelections()
659 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
661 btn_view.setEnabled(false);
662 String currentView = selectedFilterOpt.getView();
663 if (currentView == VIEWS_FILTER)
665 if (getResultTable().getSelectedRows().length > 0)
667 btn_view.setEnabled(true);
670 else if (currentView == VIEWS_LOCAL_PDB)
672 if (tbl_local_pdb.getSelectedRows().length > 0)
674 btn_view.setEnabled(true);
677 else if (currentView == VIEWS_ENTER_ID)
679 validateAssociationEnterPdb();
681 else if (currentView == VIEWS_FROM_FILE)
683 validateAssociationFromFile();
688 * Validates inputs from the Manual PDB entry panel
690 public void validateAssociationEnterPdb()
692 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
693 .getCmb_assSeq().getSelectedItem();
694 lbl_pdbManualFetchStatus.setIcon(errorImage);
695 lbl_pdbManualFetchStatus.setToolTipText("");
696 if (txt_search.getText().length() > 0)
698 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
699 MessageManager.formatMessage("info.no_pdb_entry_found_for",
700 txt_search.getText())));
703 if (errorWarning.length() > 0)
705 lbl_pdbManualFetchStatus.setIcon(warningImage);
706 lbl_pdbManualFetchStatus.setToolTipText(
707 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
710 if (selectedSequences.length == 1 || !assSeqOpt.getName()
711 .equalsIgnoreCase("-Select Associated Seq-"))
713 txt_search.setEnabled(true);
716 btn_view.setEnabled(true);
717 lbl_pdbManualFetchStatus.setToolTipText("");
718 lbl_pdbManualFetchStatus.setIcon(goodImage);
723 txt_search.setEnabled(false);
724 lbl_pdbManualFetchStatus.setIcon(errorImage);
729 * Validates inputs for the manual PDB file selection options
731 public void validateAssociationFromFile()
733 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
734 .getCmb_assSeq().getSelectedItem();
735 lbl_fromFileStatus.setIcon(errorImage);
736 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
737 .getName().equalsIgnoreCase("-Select Associated Seq-")))
739 btn_pdbFromFile.setEnabled(true);
740 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
742 btn_view.setEnabled(true);
743 lbl_fromFileStatus.setIcon(goodImage);
748 btn_pdbFromFile.setEnabled(false);
749 lbl_fromFileStatus.setIcon(errorImage);
754 public void cmbAssSeqStateChanged()
756 validateSelections();
760 * Handles the state change event for the 'filter' combo-box and 'invert'
764 protected void stateChanged(ItemEvent e)
766 if (e.getSource() instanceof JCheckBox)
772 if (e.getStateChange() == ItemEvent.SELECTED)
781 * select structures for viewing by their PDB IDs
784 * @return true if structures were found and marked as selected
786 public boolean selectStructure(String... pdbids)
788 boolean found = false;
790 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
792 String currentView = selectedFilterOpt.getView();
793 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
794 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
796 if (restable == null)
798 // can't select (enter PDB ID, or load file - need to also select which
799 // sequence to associate with)
803 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
804 for (int r = 0; r < restable.getRowCount(); r++)
806 for (int p = 0; p < pdbids.length; p++)
808 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
809 .equalsIgnoreCase(pdbids[p]))
811 restable.setRowSelectionInterval(r, r);
819 * Handles action event for btn_ok
822 public void newview_ActionPerformed()
824 targetView.setSelectedItem(null);
825 showStructures(false);
829 * Handles action event for btn_ok
832 public void view_ActionPerformed()
834 showStructures(false);
838 * structure viewer opened by this dialog, or null
840 private StructureViewer sViewer = null;
842 public void showStructures(boolean waitUntilFinished)
845 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
847 final int preferredHeight = pnl_filter.getHeight();
849 Runnable viewStruc = new Runnable()
854 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
856 String currentView = selectedFilterOpt.getView();
857 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
860 if (currentView == VIEWS_FILTER)
862 int pdbIdColIndex = restable.getColumn("PDB Id")
864 int refSeqColIndex = restable.getColumn("Ref Sequence")
866 int[] selectedRows = restable.getSelectedRows();
867 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
869 List<SequenceI> selectedSeqsToView = new ArrayList<>();
870 for (int row : selectedRows)
872 String pdbIdStr = restable
873 .getValueAt(row, pdbIdColIndex).toString();
874 SequenceI selectedSeq = (SequenceI) restable
875 .getValueAt(row, refSeqColIndex);
876 selectedSeqsToView.add(selectedSeq);
877 PDBEntry pdbEntry = selectedSeq.getPDBEntry(pdbIdStr);
878 if (pdbEntry == null)
880 pdbEntry = getFindEntry(pdbIdStr,
881 selectedSeq.getAllPDBEntries());
884 if (pdbEntry == null)
886 pdbEntry = new PDBEntry();
887 pdbEntry.setId(pdbIdStr);
888 pdbEntry.setType(PDBEntry.Type.PDB);
889 selectedSeq.getDatasetSequence().addPDBId(pdbEntry);
891 pdbEntriesToView[count++] = pdbEntry;
893 SequenceI[] selectedSeqs = selectedSeqsToView
894 .toArray(new SequenceI[selectedSeqsToView.size()]);
895 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
898 else if (currentView == VIEWS_LOCAL_PDB)
900 int[] selectedRows = tbl_local_pdb.getSelectedRows();
901 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
903 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
905 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
907 List<SequenceI> selectedSeqsToView = new ArrayList<>();
908 for (int row : selectedRows)
910 PDBEntry pdbEntry = (PDBEntry) tbl_local_pdb.getValueAt(row,
912 pdbEntriesToView[count++] = pdbEntry;
913 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
914 .getValueAt(row, refSeqColIndex);
915 selectedSeqsToView.add(selectedSeq);
917 SequenceI[] selectedSeqs = selectedSeqsToView
918 .toArray(new SequenceI[selectedSeqsToView.size()]);
919 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
922 else if (currentView == VIEWS_ENTER_ID)
924 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
925 .getCmb_assSeq().getSelectedItem()).getSequence();
926 if (userSelectedSeq != null)
928 selectedSequence = userSelectedSeq;
930 String pdbIdStr = txt_search.getText();
931 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
932 if (pdbEntry == null)
934 pdbEntry = new PDBEntry();
935 if (pdbIdStr.split(":").length > 1)
937 pdbEntry.setId(pdbIdStr.split(":")[0]);
938 pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase());
942 pdbEntry.setId(pdbIdStr);
944 pdbEntry.setType(PDBEntry.Type.PDB);
945 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
948 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
949 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
951 { selectedSequence });
953 else if (currentView == VIEWS_FROM_FILE)
955 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
956 .getCmb_assSeq().getSelectedItem()).getSequence();
957 if (userSelectedSeq != null)
959 selectedSequence = userSelectedSeq;
961 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
962 .associatePdbWithSeq(selectedPdbFileName,
963 DataSourceType.FILE, selectedSequence, true,
966 sViewer = launchStructureViewer(
970 { selectedSequence });
972 SwingUtilities.invokeLater(new Runnable()
977 closeAction(preferredHeight);
983 Thread runner = new Thread(viewStruc);
985 if (waitUntilFinished)
987 while (sViewer == null ? runner.isAlive()
988 : (sViewer.sview == null ? true
989 : !sViewer.sview.hasMapping()))
994 } catch (InterruptedException ie)
1002 private PDBEntry getFindEntry(String id, Vector<PDBEntry> pdbEntries)
1004 Objects.requireNonNull(id);
1005 Objects.requireNonNull(pdbEntries);
1006 PDBEntry foundEntry = null;
1007 for (PDBEntry entry : pdbEntries)
1009 if (entry.getId().equalsIgnoreCase(id))
1019 * @return targetted structure view (new or existing) configured according to
1020 * superpose checkbox
1022 public StructureViewer getTargetedStructureViewer(
1023 StructureSelectionManager ssm)
1025 Object _sv = targetView.getSelectedItem();
1029 sv = new StructureViewer(ssm);
1031 sv = (StructureViewer) _sv;
1033 sv.setSuperpose(chk_superpose.isSelected());
1036 private StructureViewer launchStructureViewer(
1037 StructureSelectionManager ssm,
1038 final PDBEntry[] pdbEntriesToView,
1039 final AlignmentPanel alignPanel, SequenceI[] sequences)
1041 long progressId = sequences.hashCode();
1042 setProgressBar(MessageManager
1043 .getString("status.launching_3d_structure_viewer"), progressId);
1044 final StructureViewer sViewer = getTargetedStructureViewer(ssm);
1045 sViewer.setSuperpose(chk_superpose.isSelected());
1047 setProgressBar(null, progressId);
1048 if (SiftsSettings.isMapWithSifts())
1050 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
1052 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1053 // real PDB ID. For moment, we can also safely do this if there is already
1054 // a known mapping between the PDBEntry and the sequence.
1055 for (SequenceI seq : sequences)
1057 PDBEntry pdbe = pdbEntriesToView[p++];
1058 if (pdbe != null && pdbe.getFile() != null)
1060 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1061 if (smm != null && smm.length > 0)
1063 for (StructureMapping sm : smm)
1065 if (sm.getSequence() == seq)
1072 if (seq.getPrimaryDBRefs().size() == 0)
1074 seqsWithoutSourceDBRef.add(seq);
1078 if (!seqsWithoutSourceDBRef.isEmpty())
1080 int y = seqsWithoutSourceDBRef.size();
1081 setProgressBar(MessageManager.formatMessage(
1082 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1084 SequenceI[] seqWithoutSrcDBRef = new SequenceI[y];
1086 for (SequenceI fSeq : seqsWithoutSourceDBRef)
1088 seqWithoutSrcDBRef[x++] = fSeq;
1091 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
1092 dbRefFetcher.fetchDBRefs(true);
1094 setProgressBar("Fetch complete.", progressId); // todo i18n
1097 if (pdbEntriesToView.length > 1)
1099 setProgressBar(MessageManager.getString(
1100 "status.fetching_3d_structures_for_selected_entries"),
1102 sViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
1106 setProgressBar(MessageManager.formatMessage(
1107 "status.fetching_3d_structures_for",
1108 pdbEntriesToView[0].getId()),progressId);
1109 sViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1111 setProgressBar(null, progressId);
1112 // remember the last viewer we used...
1113 lastTargetedView = sViewer;
1118 * Populates the combo-box used in associating manually fetched structures to
1119 * a unique sequence when more than one sequence selection is made.
1122 public void populateCmbAssociateSeqOptions(
1123 JComboBox<AssociateSeqOptions> cmb_assSeq,
1124 JLabel lbl_associateSeq)
1126 cmb_assSeq.removeAllItems();
1128 new AssociateSeqOptions("-Select Associated Seq-", null));
1129 lbl_associateSeq.setVisible(false);
1130 if (selectedSequences.length > 1)
1132 for (SequenceI seq : selectedSequences)
1134 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1139 String seqName = selectedSequence.getDisplayId(false);
1140 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1141 lbl_associateSeq.setText(seqName);
1142 lbl_associateSeq.setVisible(true);
1143 cmb_assSeq.setVisible(false);
1147 public boolean isStructuresDiscovered()
1149 return discoveredStructuresSet != null
1150 && !discoveredStructuresSet.isEmpty();
1153 public Collection<FTSData> getDiscoveredStructuresSet()
1155 return discoveredStructuresSet;
1159 protected void txt_search_ActionPerformed()
1166 errorWarning.setLength(0);
1167 isValidPBDEntry = false;
1168 if (txt_search.getText().length() > 0)
1170 String searchTerm = txt_search.getText().toLowerCase();
1171 searchTerm = searchTerm.split(":")[0];
1172 // System.out.println(">>>>> search term : " + searchTerm);
1173 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1174 FTSRestRequest pdbRequest = new FTSRestRequest();
1175 pdbRequest.setAllowEmptySeq(false);
1176 pdbRequest.setResponseSize(1);
1177 pdbRequest.setFieldToSearchBy("(pdb_id:");
1178 pdbRequest.setWantedFields(wantedFields);
1179 pdbRequest.setSearchTerm(searchTerm + ")");
1180 pdbRequest.setAssociatedSequence(selectedSequence);
1181 pdbRestCleint = PDBFTSRestClient.getInstance();
1182 wantedFields.add(pdbRestCleint.getPrimaryKeyColumn());
1183 FTSRestResponse resultList;
1186 resultList = pdbRestCleint.executeRequest(pdbRequest);
1187 } catch (Exception e)
1189 errorWarning.append(e.getMessage());
1193 validateSelections();
1195 if (resultList.getSearchSummary() != null
1196 && resultList.getSearchSummary().size() > 0)
1198 isValidPBDEntry = true;
1201 validateSelections();
1207 public void tabRefresh()
1209 if (selectedSequences != null)
1211 Thread refreshThread = new Thread(new Runnable()
1216 fetchStructuresMetaData();
1218 ((FilterOption) cmb_filterOption.getSelectedItem())
1222 refreshThread.start();
1226 public class PDBEntryTableModel extends AbstractTableModel
1228 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1231 private List<CachedPDB> pdbEntries;
1233 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1235 this.pdbEntries = new ArrayList<>(pdbEntries);
1239 public String getColumnName(int columnIndex)
1241 return columns[columnIndex];
1245 public int getRowCount()
1247 return pdbEntries.size();
1251 public int getColumnCount()
1253 return columns.length;
1257 public boolean isCellEditable(int row, int column)
1263 public Object getValueAt(int rowIndex, int columnIndex)
1265 Object value = "??";
1266 CachedPDB entry = pdbEntries.get(rowIndex);
1267 switch (columnIndex)
1270 value = entry.getSequence();
1273 value = entry.getPdbEntry();
1276 value = entry.getPdbEntry().getChainCode() == null ? "_"
1277 : entry.getPdbEntry().getChainCode();
1280 value = entry.getPdbEntry().getType();
1283 value = entry.getPdbEntry().getFile();
1290 public Class<?> getColumnClass(int columnIndex)
1292 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1295 public CachedPDB getPDBEntryAt(int row)
1297 return pdbEntries.get(row);
1302 private class CachedPDB
1304 private SequenceI sequence;
1306 private PDBEntry pdbEntry;
1308 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1310 this.sequence = sequence;
1311 this.pdbEntry = pdbEntry;
1314 public SequenceI getSequence()
1319 public PDBEntry getPdbEntry()
1326 private IProgressIndicator progressBar;
1329 public void setProgressBar(String message, long id)
1331 progressBar.setProgressBar(message, id);
1335 public void registerHandler(long id, IProgressIndicatorHandler handler)
1337 progressBar.registerHandler(id, handler);
1341 public boolean operationInProgress()
1343 return progressBar.operationInProgress();
1346 public JalviewStructureDisplayI getOpenedStructureViewer()
1348 return sViewer == null ? null : sViewer.sview;