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();
146 new StructureViewer(ap.getStructureSelectionManager()));
147 if (lastTargetedView != null && !lastTargetedView.isVisible())
149 lastTargetedView = null;
151 int linkedViewsAt = 1;
152 for (StructureViewerBase view : Desktop.instance
153 .getStructureViewers(null, null))
155 StructureViewer viewHandler = (lastTargetedView != null
156 && lastTargetedView.sview == view) ? lastTargetedView
157 : StructureViewer.reconfigure(view);
159 if (view.isLinkedWith(ap))
161 targetView.insertItemAt(viewHandler,
166 targetView.addItem(viewHandler);
169 targetView.setVisible(targetView.getItemCount() > 1);
171 // finally, restore last targeted view by default.
172 if (lastTargetedView != null)
174 targetView.setSelectedItem(lastTargetedView);
179 private static StructureViewer lastTargetedView = null;
182 * Updates the progress indicator with the specified message
185 * displayed message for the operation
187 * unique handle for this indicator
189 public void updateProgressIndicator(String message, long id)
191 if (progressIndicator != null)
193 progressIndicator.setProgressBar(message, id);
198 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
201 public void fetchStructuresMetaData()
203 long startTime = System.currentTimeMillis();
204 pdbRestCleint = PDBFTSRestClient.getInstance();
205 Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
206 .getStructureSummaryFields();
208 discoveredStructuresSet = new LinkedHashSet<>();
209 HashSet<String> errors = new HashSet<>();
210 for (SequenceI seq : selectedSequences)
212 FTSRestRequest pdbRequest = new FTSRestRequest();
213 pdbRequest.setAllowEmptySeq(false);
214 pdbRequest.setResponseSize(500);
215 pdbRequest.setFieldToSearchBy("(");
216 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
218 pdbRequest.setFieldToSortBy(selectedFilterOpt.getValue(),
219 !chk_invertFilter.isSelected());
220 pdbRequest.setWantedFields(wantedFields);
221 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
222 pdbRequest.setAssociatedSequence(seq);
223 FTSRestResponse resultList;
226 resultList = pdbRestCleint.executeRequest(pdbRequest);
227 } catch (Exception e)
230 errors.add(e.getMessage());
233 lastPdbRequest = pdbRequest;
234 if (resultList.getSearchSummary() != null
235 && !resultList.getSearchSummary().isEmpty())
237 discoveredStructuresSet.addAll(resultList.getSearchSummary());
241 int noOfStructuresFound = 0;
242 String totalTime = (System.currentTimeMillis() - startTime)
244 if (discoveredStructuresSet != null
245 && !discoveredStructuresSet.isEmpty())
247 getResultTable().setModel(FTSRestResponse
248 .getTableModel(lastPdbRequest, discoveredStructuresSet));
249 noOfStructuresFound = discoveredStructuresSet.size();
250 mainFrame.setTitle(MessageManager.formatMessage(
251 "label.structure_chooser_no_of_structures",
252 noOfStructuresFound, totalTime));
256 mainFrame.setTitle(MessageManager
257 .getString("label.structure_chooser_manual_association"));
258 if (errors.size() > 0)
260 StringBuilder errorMsg = new StringBuilder();
261 for (String error : errors)
263 errorMsg.append(error).append("\n");
265 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
266 MessageManager.getString("label.pdb_web-service_error"),
267 JvOptionPane.ERROR_MESSAGE);
272 public void loadLocalCachedPDBEntries()
274 ArrayList<CachedPDB> entries = new ArrayList<>();
275 for (SequenceI seq : selectedSequences)
277 if (seq.getDatasetSequence() != null
278 && seq.getDatasetSequence().getAllPDBEntries() != null)
280 for (PDBEntry pdbEntry : seq.getDatasetSequence()
283 if (pdbEntry.getFile() != null)
285 entries.add(new CachedPDB(seq, pdbEntry));
290 cachedPDBExists = !entries.isEmpty();
291 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
292 tbl_local_pdb.setModel(tableModelx);
296 * Builds a query string for a given sequences using its DBRef entries
299 * the sequences to build a query for
300 * @return the built query string
303 public static String buildQuery(SequenceI seq)
305 boolean isPDBRefsFound = false;
306 boolean isUniProtRefsFound = false;
307 StringBuilder queryBuilder = new StringBuilder();
308 Set<String> seqRefs = new LinkedHashSet<>();
310 if (seq.getAllPDBEntries() != null
311 && queryBuilder.length() < MAX_QLENGTH)
313 for (PDBEntry entry : seq.getAllPDBEntries())
315 if (isValidSeqName(entry.getId()))
317 queryBuilder.append("pdb_id:").append(entry.getId().toLowerCase())
319 isPDBRefsFound = true;
324 if (seq.getDBRefs() != null && seq.getDBRefs().length != 0)
326 for (DBRefEntry dbRef : seq.getDBRefs())
328 if (isValidSeqName(getDBRefId(dbRef))
329 && queryBuilder.length() < MAX_QLENGTH)
331 if (dbRef.getSource().equalsIgnoreCase(DBRefSource.UNIPROT))
333 queryBuilder.append("uniprot_accession:")
334 .append(getDBRefId(dbRef)).append(" OR ");
335 queryBuilder.append("uniprot_id:").append(getDBRefId(dbRef))
337 isUniProtRefsFound = true;
339 else if (dbRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
342 queryBuilder.append("pdb_id:")
343 .append(getDBRefId(dbRef).toLowerCase()).append(" OR ");
344 isPDBRefsFound = true;
348 seqRefs.add(getDBRefId(dbRef));
354 if (!isPDBRefsFound && !isUniProtRefsFound)
356 String seqName = seq.getName();
357 seqName = sanitizeSeqName(seqName);
358 String[] names = seqName.toLowerCase().split("\\|");
359 for (String name : names)
361 // System.out.println("Found name : " + name);
363 if (isValidSeqName(name))
369 for (String seqRef : seqRefs)
371 queryBuilder.append("text:").append(seqRef).append(" OR ");
375 int endIndex = queryBuilder.lastIndexOf(" OR ");
376 if (queryBuilder.toString().length() < 6)
380 String query = queryBuilder.toString().substring(0, endIndex);
385 * Remove the following special characters from input string +, -, &, !, (, ),
386 * {, }, [, ], ^, ", ~, *, ?, :, \
391 static String sanitizeSeqName(String seqName)
393 Objects.requireNonNull(seqName);
394 return seqName.replaceAll("\\[\\d*\\]", "")
395 .replaceAll("[^\\dA-Za-z|_]", "").replaceAll("\\s+", "+");
399 * Ensures sequence ref names are not less than 3 characters and does not
400 * contain a database name
405 public static boolean isValidSeqName(String seqName)
407 // System.out.println("seqName : " + seqName);
408 String ignoreList = "pdb,uniprot,swiss-prot";
409 if (seqName.length() < 3)
413 if (seqName.contains(":"))
417 seqName = seqName.toLowerCase();
418 for (String ignoredEntry : ignoreList.split(","))
420 if (seqName.contains(ignoredEntry))
428 public static String getDBRefId(DBRefEntry dbRef)
430 String ref = dbRef.getAccessionId().replaceAll("GO:", "");
435 * Filters a given list of discovered structures based on supplied argument
437 * @param fieldToFilterBy
438 * the field to filter by
440 public void filterResultSet(final String fieldToFilterBy)
442 Thread filterThread = new Thread(new Runnable()
447 long startTime = System.currentTimeMillis();
448 pdbRestCleint = PDBFTSRestClient.getInstance();
449 lbl_loading.setVisible(true);
450 Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
451 .getStructureSummaryFields();
452 Collection<FTSData> filteredResponse = new HashSet<>();
453 HashSet<String> errors = new HashSet<>();
455 for (SequenceI seq : selectedSequences)
457 FTSRestRequest pdbRequest = new FTSRestRequest();
458 if (fieldToFilterBy.equalsIgnoreCase("uniprot_coverage"))
460 pdbRequest.setAllowEmptySeq(false);
461 pdbRequest.setResponseSize(1);
462 pdbRequest.setFieldToSearchBy("(");
463 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
464 pdbRequest.setWantedFields(wantedFields);
465 pdbRequest.setAssociatedSequence(seq);
466 pdbRequest.setFacet(true);
467 pdbRequest.setFacetPivot(fieldToFilterBy + ",entry_entity");
468 pdbRequest.setFacetPivotMinCount(1);
472 pdbRequest.setAllowEmptySeq(false);
473 pdbRequest.setResponseSize(1);
474 pdbRequest.setFieldToSearchBy("(");
475 pdbRequest.setFieldToSortBy(fieldToFilterBy,
476 !chk_invertFilter.isSelected());
477 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
478 pdbRequest.setWantedFields(wantedFields);
479 pdbRequest.setAssociatedSequence(seq);
481 FTSRestResponse resultList;
484 resultList = pdbRestCleint.executeRequest(pdbRequest);
485 } catch (Exception e)
488 errors.add(e.getMessage());
491 lastPdbRequest = pdbRequest;
492 if (resultList.getSearchSummary() != null
493 && !resultList.getSearchSummary().isEmpty())
495 filteredResponse.addAll(resultList.getSearchSummary());
499 String totalTime = (System.currentTimeMillis() - startTime)
501 if (!filteredResponse.isEmpty())
503 final int filterResponseCount = filteredResponse.size();
504 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
505 reorderedStructuresSet.addAll(filteredResponse);
506 reorderedStructuresSet.addAll(discoveredStructuresSet);
507 getResultTable().setModel(FTSRestResponse
508 .getTableModel(lastPdbRequest, reorderedStructuresSet));
510 FTSRestResponse.configureTableColumn(getResultTable(),
511 wantedFields, tempUserPrefs);
512 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
513 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
514 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
515 // Update table selection model here
516 getResultTable().addRowSelectionInterval(0,
517 filterResponseCount - 1);
518 mainFrame.setTitle(MessageManager.formatMessage(
519 "label.structure_chooser_filter_time", totalTime));
523 mainFrame.setTitle(MessageManager.formatMessage(
524 "label.structure_chooser_filter_time", totalTime));
525 if (errors.size() > 0)
527 StringBuilder errorMsg = new StringBuilder();
528 for (String error : errors)
530 errorMsg.append(error).append("\n");
532 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
533 MessageManager.getString("label.pdb_web-service_error"),
534 JvOptionPane.ERROR_MESSAGE);
538 lbl_loading.setVisible(false);
540 validateSelections();
543 filterThread.start();
547 * Handles action event for btn_pdbFromFile
550 public void pdbFromFile_actionPerformed()
552 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
553 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
554 chooser.setFileView(new jalview.io.JalviewFileView());
555 chooser.setDialogTitle(
556 MessageManager.formatMessage("label.select_pdb_file_for",
557 selectedSequence.getDisplayId(false)));
558 chooser.setToolTipText(MessageManager.formatMessage(
559 "label.load_pdb_file_associate_with_sequence",
560 selectedSequence.getDisplayId(false)));
562 int value = chooser.showOpenDialog(null);
563 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
565 selectedPdbFileName = chooser.getSelectedFile().getPath();
566 jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
567 validateSelections();
572 * Populates the filter combo-box options dynamically depending on discovered
575 protected void populateFilterComboBox(boolean haveData,
576 boolean cachedPDBExist)
579 * temporarily suspend the change listener behaviour
581 cmb_filterOption.removeItemListener(this);
583 cmb_filterOption.removeAllItems();
586 cmb_filterOption.addItem(new FilterOption(
587 MessageManager.getString("label.best_quality"),
588 "overall_quality", VIEWS_FILTER, false));
589 cmb_filterOption.addItem(new FilterOption(
590 MessageManager.getString("label.best_resolution"),
591 "resolution", VIEWS_FILTER, false));
592 cmb_filterOption.addItem(new FilterOption(
593 MessageManager.getString("label.most_protein_chain"),
594 "number_of_protein_chains", VIEWS_FILTER, false));
595 cmb_filterOption.addItem(new FilterOption(
596 MessageManager.getString("label.most_bound_molecules"),
597 "number_of_bound_molecules", VIEWS_FILTER, false));
598 cmb_filterOption.addItem(new FilterOption(
599 MessageManager.getString("label.most_polymer_residues"),
600 "number_of_polymer_residues", VIEWS_FILTER, true));
602 cmb_filterOption.addItem(
603 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
604 "-", VIEWS_ENTER_ID, false));
605 cmb_filterOption.addItem(
606 new FilterOption(MessageManager.getString("label.from_file"),
607 "-", VIEWS_FROM_FILE, false));
611 FilterOption cachedOption = new FilterOption(
612 MessageManager.getString("label.cached_structures"),
613 "-", VIEWS_LOCAL_PDB, false);
614 cmb_filterOption.addItem(cachedOption);
615 cmb_filterOption.setSelectedItem(cachedOption);
618 cmb_filterOption.addItemListener(this);
622 * Updates the displayed view based on the selected filter option
624 protected void updateCurrentView()
626 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
628 layout_switchableViews.show(pnl_switchableViews,
629 selectedFilterOpt.getView());
630 String filterTitle = mainFrame.getTitle();
631 mainFrame.setTitle(frameTitle);
632 chk_invertFilter.setVisible(false);
633 if (selectedFilterOpt.getView() == VIEWS_FILTER)
635 mainFrame.setTitle(filterTitle);
636 chk_invertFilter.setVisible(true);
637 filterResultSet(selectedFilterOpt.getValue());
639 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
640 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
642 mainFrame.setTitle(MessageManager
643 .getString("label.structure_chooser_manual_association"));
644 idInputAssSeqPanel.loadCmbAssSeq();
645 fileChooserAssSeqPanel.loadCmbAssSeq();
647 validateSelections();
651 * Validates user selection and activates the view button if all parameters
655 public void validateSelections()
657 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
659 btn_view.setEnabled(false);
660 String currentView = selectedFilterOpt.getView();
661 if (currentView == VIEWS_FILTER)
663 if (getResultTable().getSelectedRows().length > 0)
665 btn_view.setEnabled(true);
668 else if (currentView == VIEWS_LOCAL_PDB)
670 if (tbl_local_pdb.getSelectedRows().length > 0)
672 btn_view.setEnabled(true);
675 else if (currentView == VIEWS_ENTER_ID)
677 validateAssociationEnterPdb();
679 else if (currentView == VIEWS_FROM_FILE)
681 validateAssociationFromFile();
686 * Validates inputs from the Manual PDB entry panel
688 public void validateAssociationEnterPdb()
690 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
691 .getCmb_assSeq().getSelectedItem();
692 lbl_pdbManualFetchStatus.setIcon(errorImage);
693 lbl_pdbManualFetchStatus.setToolTipText("");
694 if (txt_search.getText().length() > 0)
696 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
697 MessageManager.formatMessage("info.no_pdb_entry_found_for",
698 txt_search.getText())));
701 if (errorWarning.length() > 0)
703 lbl_pdbManualFetchStatus.setIcon(warningImage);
704 lbl_pdbManualFetchStatus.setToolTipText(
705 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
708 if (selectedSequences.length == 1 || !assSeqOpt.getName()
709 .equalsIgnoreCase("-Select Associated Seq-"))
711 txt_search.setEnabled(true);
714 btn_view.setEnabled(true);
715 lbl_pdbManualFetchStatus.setToolTipText("");
716 lbl_pdbManualFetchStatus.setIcon(goodImage);
721 txt_search.setEnabled(false);
722 lbl_pdbManualFetchStatus.setIcon(errorImage);
727 * Validates inputs for the manual PDB file selection options
729 public void validateAssociationFromFile()
731 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
732 .getCmb_assSeq().getSelectedItem();
733 lbl_fromFileStatus.setIcon(errorImage);
734 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
735 .getName().equalsIgnoreCase("-Select Associated Seq-")))
737 btn_pdbFromFile.setEnabled(true);
738 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
740 btn_view.setEnabled(true);
741 lbl_fromFileStatus.setIcon(goodImage);
746 btn_pdbFromFile.setEnabled(false);
747 lbl_fromFileStatus.setIcon(errorImage);
752 public void cmbAssSeqStateChanged()
754 validateSelections();
758 * Handles the state change event for the 'filter' combo-box and 'invert'
762 protected void stateChanged(ItemEvent e)
764 if (e.getSource() instanceof JCheckBox)
770 if (e.getStateChange() == ItemEvent.SELECTED)
779 * select structures for viewing by their PDB IDs
782 * @return true if structures were found and marked as selected
784 public boolean selectStructure(String... pdbids)
786 boolean found = false;
788 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
790 String currentView = selectedFilterOpt.getView();
791 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
792 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
794 if (restable == null)
796 // can't select (enter PDB ID, or load file - need to also select which
797 // sequence to associate with)
801 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
802 for (int r = 0; r < restable.getRowCount(); r++)
804 for (int p = 0; p < pdbids.length; p++)
806 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
807 .equalsIgnoreCase(pdbids[p]))
809 restable.setRowSelectionInterval(r, r);
817 * Handles action event for btn_ok
820 public void ok_ActionPerformed()
822 showStructures(false);
826 * structure viewer opened by this dialog, or null
828 private StructureViewer sViewer = null;
830 public void showStructures(boolean waitUntilFinished)
833 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
835 final int preferredHeight = pnl_filter.getHeight();
837 Runnable viewStruc = new Runnable()
842 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
844 String currentView = selectedFilterOpt.getView();
845 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
848 if (currentView == VIEWS_FILTER)
850 int pdbIdColIndex = restable.getColumn("PDB Id")
852 int refSeqColIndex = restable.getColumn("Ref Sequence")
854 int[] selectedRows = restable.getSelectedRows();
855 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
857 List<SequenceI> selectedSeqsToView = new ArrayList<>();
858 for (int row : selectedRows)
860 String pdbIdStr = restable
861 .getValueAt(row, pdbIdColIndex).toString();
862 SequenceI selectedSeq = (SequenceI) restable
863 .getValueAt(row, refSeqColIndex);
864 selectedSeqsToView.add(selectedSeq);
865 PDBEntry pdbEntry = selectedSeq.getPDBEntry(pdbIdStr);
866 if (pdbEntry == null)
868 pdbEntry = getFindEntry(pdbIdStr,
869 selectedSeq.getAllPDBEntries());
872 if (pdbEntry == null)
874 pdbEntry = new PDBEntry();
875 pdbEntry.setId(pdbIdStr);
876 pdbEntry.setType(PDBEntry.Type.PDB);
877 selectedSeq.getDatasetSequence().addPDBId(pdbEntry);
879 pdbEntriesToView[count++] = pdbEntry;
881 SequenceI[] selectedSeqs = selectedSeqsToView
882 .toArray(new SequenceI[selectedSeqsToView.size()]);
883 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
886 else if (currentView == VIEWS_LOCAL_PDB)
888 int[] selectedRows = tbl_local_pdb.getSelectedRows();
889 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
891 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
893 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
895 List<SequenceI> selectedSeqsToView = new ArrayList<>();
896 for (int row : selectedRows)
898 PDBEntry pdbEntry = (PDBEntry) tbl_local_pdb.getValueAt(row,
900 pdbEntriesToView[count++] = pdbEntry;
901 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
902 .getValueAt(row, refSeqColIndex);
903 selectedSeqsToView.add(selectedSeq);
905 SequenceI[] selectedSeqs = selectedSeqsToView
906 .toArray(new SequenceI[selectedSeqsToView.size()]);
907 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
910 else if (currentView == VIEWS_ENTER_ID)
912 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
913 .getCmb_assSeq().getSelectedItem()).getSequence();
914 if (userSelectedSeq != null)
916 selectedSequence = userSelectedSeq;
918 String pdbIdStr = txt_search.getText();
919 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
920 if (pdbEntry == null)
922 pdbEntry = new PDBEntry();
923 if (pdbIdStr.split(":").length > 1)
925 pdbEntry.setId(pdbIdStr.split(":")[0]);
926 pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase());
930 pdbEntry.setId(pdbIdStr);
932 pdbEntry.setType(PDBEntry.Type.PDB);
933 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
936 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
937 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
939 { selectedSequence });
941 else if (currentView == VIEWS_FROM_FILE)
943 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
944 .getCmb_assSeq().getSelectedItem()).getSequence();
945 if (userSelectedSeq != null)
947 selectedSequence = userSelectedSeq;
949 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
950 .associatePdbWithSeq(selectedPdbFileName,
951 DataSourceType.FILE, selectedSequence, true,
954 sViewer = launchStructureViewer(
958 { selectedSequence });
960 SwingUtilities.invokeLater(new Runnable()
965 closeAction(preferredHeight);
971 Thread runner = new Thread(viewStruc);
973 if (waitUntilFinished)
975 while (sViewer == null ? runner.isAlive()
976 : (sViewer.sview == null ? true
977 : !sViewer.sview.hasMapping()))
982 } catch (InterruptedException ie)
990 private PDBEntry getFindEntry(String id, Vector<PDBEntry> pdbEntries)
992 Objects.requireNonNull(id);
993 Objects.requireNonNull(pdbEntries);
994 PDBEntry foundEntry = null;
995 for (PDBEntry entry : pdbEntries)
997 if (entry.getId().equalsIgnoreCase(id))
1007 * @return targetted structure view (new or existing) configured according to
1008 * superpose checkbox
1010 public StructureViewer getTargetedStructureViewer(
1011 StructureSelectionManager ssm)
1013 Object _sv = targetView.getSelectedItem();
1017 sv = new StructureViewer(ssm);
1019 sv = (StructureViewer) _sv;
1021 sv.setSuperpose(chk_superpose.isSelected());
1024 private StructureViewer launchStructureViewer(
1025 StructureSelectionManager ssm,
1026 final PDBEntry[] pdbEntriesToView,
1027 final AlignmentPanel alignPanel, SequenceI[] sequences)
1029 long progressId = sequences.hashCode();
1030 setProgressBar(MessageManager
1031 .getString("status.launching_3d_structure_viewer"), progressId);
1032 final StructureViewer sViewer = getTargetedStructureViewer(ssm);
1033 sViewer.setSuperpose(chk_superpose.isSelected());
1035 setProgressBar(null, progressId);
1036 if (SiftsSettings.isMapWithSifts())
1038 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
1040 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1041 // real PDB ID. For moment, we can also safely do this if there is already
1042 // a known mapping between the PDBEntry and the sequence.
1043 for (SequenceI seq : sequences)
1045 PDBEntry pdbe = pdbEntriesToView[p++];
1046 if (pdbe != null && pdbe.getFile() != null)
1048 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1049 if (smm != null && smm.length > 0)
1051 for (StructureMapping sm : smm)
1053 if (sm.getSequence() == seq)
1060 if (seq.getPrimaryDBRefs().size() == 0)
1062 seqsWithoutSourceDBRef.add(seq);
1066 if (!seqsWithoutSourceDBRef.isEmpty())
1068 int y = seqsWithoutSourceDBRef.size();
1069 setProgressBar(MessageManager.formatMessage(
1070 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1072 SequenceI[] seqWithoutSrcDBRef = new SequenceI[y];
1074 for (SequenceI fSeq : seqsWithoutSourceDBRef)
1076 seqWithoutSrcDBRef[x++] = fSeq;
1079 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
1080 dbRefFetcher.fetchDBRefs(true);
1082 setProgressBar("Fetch complete.", progressId); // todo i18n
1085 if (pdbEntriesToView.length > 1)
1087 setProgressBar(MessageManager.getString(
1088 "status.fetching_3d_structures_for_selected_entries"),
1090 sViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
1094 setProgressBar(MessageManager.formatMessage(
1095 "status.fetching_3d_structures_for",
1096 pdbEntriesToView[0].getId()),progressId);
1097 sViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1099 setProgressBar(null, progressId);
1100 // remember the last viewer we used...
1101 lastTargetedView = sViewer;
1106 * Populates the combo-box used in associating manually fetched structures to
1107 * a unique sequence when more than one sequence selection is made.
1110 public void populateCmbAssociateSeqOptions(
1111 JComboBox<AssociateSeqOptions> cmb_assSeq,
1112 JLabel lbl_associateSeq)
1114 cmb_assSeq.removeAllItems();
1116 new AssociateSeqOptions("-Select Associated Seq-", null));
1117 lbl_associateSeq.setVisible(false);
1118 if (selectedSequences.length > 1)
1120 for (SequenceI seq : selectedSequences)
1122 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1127 String seqName = selectedSequence.getDisplayId(false);
1128 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1129 lbl_associateSeq.setText(seqName);
1130 lbl_associateSeq.setVisible(true);
1131 cmb_assSeq.setVisible(false);
1135 public boolean isStructuresDiscovered()
1137 return discoveredStructuresSet != null
1138 && !discoveredStructuresSet.isEmpty();
1141 public Collection<FTSData> getDiscoveredStructuresSet()
1143 return discoveredStructuresSet;
1147 protected void txt_search_ActionPerformed()
1154 errorWarning.setLength(0);
1155 isValidPBDEntry = false;
1156 if (txt_search.getText().length() > 0)
1158 String searchTerm = txt_search.getText().toLowerCase();
1159 searchTerm = searchTerm.split(":")[0];
1160 // System.out.println(">>>>> search term : " + searchTerm);
1161 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1162 FTSRestRequest pdbRequest = new FTSRestRequest();
1163 pdbRequest.setAllowEmptySeq(false);
1164 pdbRequest.setResponseSize(1);
1165 pdbRequest.setFieldToSearchBy("(pdb_id:");
1166 pdbRequest.setWantedFields(wantedFields);
1167 pdbRequest.setSearchTerm(searchTerm + ")");
1168 pdbRequest.setAssociatedSequence(selectedSequence);
1169 pdbRestCleint = PDBFTSRestClient.getInstance();
1170 wantedFields.add(pdbRestCleint.getPrimaryKeyColumn());
1171 FTSRestResponse resultList;
1174 resultList = pdbRestCleint.executeRequest(pdbRequest);
1175 } catch (Exception e)
1177 errorWarning.append(e.getMessage());
1181 validateSelections();
1183 if (resultList.getSearchSummary() != null
1184 && resultList.getSearchSummary().size() > 0)
1186 isValidPBDEntry = true;
1189 validateSelections();
1195 public void tabRefresh()
1197 if (selectedSequences != null)
1199 Thread refreshThread = new Thread(new Runnable()
1204 fetchStructuresMetaData();
1206 ((FilterOption) cmb_filterOption.getSelectedItem())
1210 refreshThread.start();
1214 public class PDBEntryTableModel extends AbstractTableModel
1216 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1219 private List<CachedPDB> pdbEntries;
1221 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1223 this.pdbEntries = new ArrayList<>(pdbEntries);
1227 public String getColumnName(int columnIndex)
1229 return columns[columnIndex];
1233 public int getRowCount()
1235 return pdbEntries.size();
1239 public int getColumnCount()
1241 return columns.length;
1245 public boolean isCellEditable(int row, int column)
1251 public Object getValueAt(int rowIndex, int columnIndex)
1253 Object value = "??";
1254 CachedPDB entry = pdbEntries.get(rowIndex);
1255 switch (columnIndex)
1258 value = entry.getSequence();
1261 value = entry.getPdbEntry();
1264 value = entry.getPdbEntry().getChainCode() == null ? "_"
1265 : entry.getPdbEntry().getChainCode();
1268 value = entry.getPdbEntry().getType();
1271 value = entry.getPdbEntry().getFile();
1278 public Class<?> getColumnClass(int columnIndex)
1280 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1283 public CachedPDB getPDBEntryAt(int row)
1285 return pdbEntries.get(row);
1290 private class CachedPDB
1292 private SequenceI sequence;
1294 private PDBEntry pdbEntry;
1296 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1298 this.sequence = sequence;
1299 this.pdbEntry = pdbEntry;
1302 public SequenceI getSequence()
1307 public PDBEntry getPdbEntry()
1314 private IProgressIndicator progressBar;
1317 public void setProgressBar(String message, long id)
1319 progressBar.setProgressBar(message, id);
1323 public void registerHandler(long id, IProgressIndicatorHandler handler)
1325 progressBar.registerHandler(id, handler);
1329 public boolean operationInProgress()
1331 return progressBar.operationInProgress();
1334 public JalviewStructureDisplayI getOpenedStructureViewer()
1336 return sViewer == null ? null : sViewer.sview;