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 updateProgressIndicator(null, startTime);
129 mainFrame.setVisible(true);
133 discoverPDBStructuresThread.start();
137 * Updates the progress indicator with the specified message
140 * displayed message for the operation
142 * unique handle for this indicator
144 public void updateProgressIndicator(String message, long id)
146 if (progressIndicator != null)
148 progressIndicator.setProgressBar(message, id);
153 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
156 public void fetchStructuresMetaData()
158 long startTime = System.currentTimeMillis();
159 pdbRestCleint = PDBFTSRestClient.getInstance();
160 Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
161 .getStructureSummaryFields();
163 discoveredStructuresSet = new LinkedHashSet<>();
164 HashSet<String> errors = new HashSet<>();
165 for (SequenceI seq : selectedSequences)
167 FTSRestRequest pdbRequest = new FTSRestRequest();
168 pdbRequest.setAllowEmptySeq(false);
169 pdbRequest.setResponseSize(500);
170 pdbRequest.setFieldToSearchBy("(");
171 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
173 pdbRequest.setFieldToSortBy(selectedFilterOpt.getValue(),
174 !chk_invertFilter.isSelected());
175 pdbRequest.setWantedFields(wantedFields);
176 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
177 pdbRequest.setAssociatedSequence(seq);
178 FTSRestResponse resultList;
181 resultList = pdbRestCleint.executeRequest(pdbRequest);
182 } catch (Exception e)
185 errors.add(e.getMessage());
188 lastPdbRequest = pdbRequest;
189 if (resultList.getSearchSummary() != null
190 && !resultList.getSearchSummary().isEmpty())
192 discoveredStructuresSet.addAll(resultList.getSearchSummary());
196 int noOfStructuresFound = 0;
197 String totalTime = (System.currentTimeMillis() - startTime)
199 if (discoveredStructuresSet != null
200 && !discoveredStructuresSet.isEmpty())
202 getResultTable().setModel(FTSRestResponse
203 .getTableModel(lastPdbRequest, discoveredStructuresSet));
204 noOfStructuresFound = discoveredStructuresSet.size();
205 mainFrame.setTitle(MessageManager.formatMessage(
206 "label.structure_chooser_no_of_structures",
207 noOfStructuresFound, totalTime));
211 mainFrame.setTitle(MessageManager
212 .getString("label.structure_chooser_manual_association"));
213 if (errors.size() > 0)
215 StringBuilder errorMsg = new StringBuilder();
216 for (String error : errors)
218 errorMsg.append(error).append("\n");
220 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
221 MessageManager.getString("label.pdb_web-service_error"),
222 JvOptionPane.ERROR_MESSAGE);
227 public void loadLocalCachedPDBEntries()
229 ArrayList<CachedPDB> entries = new ArrayList<>();
230 for (SequenceI seq : selectedSequences)
232 if (seq.getDatasetSequence() != null
233 && seq.getDatasetSequence().getAllPDBEntries() != null)
235 for (PDBEntry pdbEntry : seq.getDatasetSequence()
238 if (pdbEntry.getFile() != null)
240 entries.add(new CachedPDB(seq, pdbEntry));
245 cachedPDBExists = !entries.isEmpty();
246 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
247 tbl_local_pdb.setModel(tableModelx);
251 * Builds a query string for a given sequences using its DBRef entries
254 * the sequences to build a query for
255 * @return the built query string
258 public static String buildQuery(SequenceI seq)
260 boolean isPDBRefsFound = false;
261 boolean isUniProtRefsFound = false;
262 StringBuilder queryBuilder = new StringBuilder();
263 Set<String> seqRefs = new LinkedHashSet<>();
265 if (seq.getAllPDBEntries() != null
266 && queryBuilder.length() < MAX_QLENGTH)
268 for (PDBEntry entry : seq.getAllPDBEntries())
270 if (isValidSeqName(entry.getId()))
272 queryBuilder.append("pdb_id:").append(entry.getId().toLowerCase())
274 isPDBRefsFound = true;
279 if (seq.getDBRefs() != null && seq.getDBRefs().length != 0)
281 for (DBRefEntry dbRef : seq.getDBRefs())
283 if (isValidSeqName(getDBRefId(dbRef))
284 && queryBuilder.length() < MAX_QLENGTH)
286 if (dbRef.getSource().equalsIgnoreCase(DBRefSource.UNIPROT))
288 queryBuilder.append("uniprot_accession:")
289 .append(getDBRefId(dbRef)).append(" OR ");
290 queryBuilder.append("uniprot_id:").append(getDBRefId(dbRef))
292 isUniProtRefsFound = true;
294 else if (dbRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
297 queryBuilder.append("pdb_id:")
298 .append(getDBRefId(dbRef).toLowerCase()).append(" OR ");
299 isPDBRefsFound = true;
303 seqRefs.add(getDBRefId(dbRef));
309 if (!isPDBRefsFound && !isUniProtRefsFound)
311 String seqName = seq.getName();
312 seqName = sanitizeSeqName(seqName);
313 String[] names = seqName.toLowerCase().split("\\|");
314 for (String name : names)
316 // System.out.println("Found name : " + name);
318 if (isValidSeqName(name))
324 for (String seqRef : seqRefs)
326 queryBuilder.append("text:").append(seqRef).append(" OR ");
330 int endIndex = queryBuilder.lastIndexOf(" OR ");
331 if (queryBuilder.toString().length() < 6)
335 String query = queryBuilder.toString().substring(0, endIndex);
340 * Remove the following special characters from input string +, -, &, !, (, ),
341 * {, }, [, ], ^, ", ~, *, ?, :, \
346 static String sanitizeSeqName(String seqName)
348 Objects.requireNonNull(seqName);
349 return seqName.replaceAll("\\[\\d*\\]", "")
350 .replaceAll("[^\\dA-Za-z|_]", "").replaceAll("\\s+", "+");
354 * Ensures sequence ref names are not less than 3 characters and does not
355 * contain a database name
360 public static boolean isValidSeqName(String seqName)
362 // System.out.println("seqName : " + seqName);
363 String ignoreList = "pdb,uniprot,swiss-prot";
364 if (seqName.length() < 3)
368 if (seqName.contains(":"))
372 seqName = seqName.toLowerCase();
373 for (String ignoredEntry : ignoreList.split(","))
375 if (seqName.contains(ignoredEntry))
383 public static String getDBRefId(DBRefEntry dbRef)
385 String ref = dbRef.getAccessionId().replaceAll("GO:", "");
390 * Filters a given list of discovered structures based on supplied argument
392 * @param fieldToFilterBy
393 * the field to filter by
395 public void filterResultSet(final String fieldToFilterBy)
397 Thread filterThread = new Thread(new Runnable()
402 long startTime = System.currentTimeMillis();
403 pdbRestCleint = PDBFTSRestClient.getInstance();
404 lbl_loading.setVisible(true);
405 Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
406 .getStructureSummaryFields();
407 Collection<FTSData> filteredResponse = new HashSet<>();
408 HashSet<String> errors = new HashSet<>();
410 for (SequenceI seq : selectedSequences)
412 FTSRestRequest pdbRequest = new FTSRestRequest();
413 if (fieldToFilterBy.equalsIgnoreCase("uniprot_coverage"))
415 pdbRequest.setAllowEmptySeq(false);
416 pdbRequest.setResponseSize(1);
417 pdbRequest.setFieldToSearchBy("(");
418 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
419 pdbRequest.setWantedFields(wantedFields);
420 pdbRequest.setAssociatedSequence(seq);
421 pdbRequest.setFacet(true);
422 pdbRequest.setFacetPivot(fieldToFilterBy + ",entry_entity");
423 pdbRequest.setFacetPivotMinCount(1);
427 pdbRequest.setAllowEmptySeq(false);
428 pdbRequest.setResponseSize(1);
429 pdbRequest.setFieldToSearchBy("(");
430 pdbRequest.setFieldToSortBy(fieldToFilterBy,
431 !chk_invertFilter.isSelected());
432 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
433 pdbRequest.setWantedFields(wantedFields);
434 pdbRequest.setAssociatedSequence(seq);
436 FTSRestResponse resultList;
439 resultList = pdbRestCleint.executeRequest(pdbRequest);
440 } catch (Exception e)
443 errors.add(e.getMessage());
446 lastPdbRequest = pdbRequest;
447 if (resultList.getSearchSummary() != null
448 && !resultList.getSearchSummary().isEmpty())
450 filteredResponse.addAll(resultList.getSearchSummary());
454 String totalTime = (System.currentTimeMillis() - startTime)
456 if (!filteredResponse.isEmpty())
458 final int filterResponseCount = filteredResponse.size();
459 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
460 reorderedStructuresSet.addAll(filteredResponse);
461 reorderedStructuresSet.addAll(discoveredStructuresSet);
462 getResultTable().setModel(FTSRestResponse
463 .getTableModel(lastPdbRequest, reorderedStructuresSet));
465 FTSRestResponse.configureTableColumn(getResultTable(),
466 wantedFields, tempUserPrefs);
467 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
468 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
469 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
470 // Update table selection model here
471 getResultTable().addRowSelectionInterval(0,
472 filterResponseCount - 1);
473 mainFrame.setTitle(MessageManager.formatMessage(
474 "label.structure_chooser_filter_time", totalTime));
478 mainFrame.setTitle(MessageManager.formatMessage(
479 "label.structure_chooser_filter_time", totalTime));
480 if (errors.size() > 0)
482 StringBuilder errorMsg = new StringBuilder();
483 for (String error : errors)
485 errorMsg.append(error).append("\n");
487 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
488 MessageManager.getString("label.pdb_web-service_error"),
489 JvOptionPane.ERROR_MESSAGE);
493 lbl_loading.setVisible(false);
495 validateSelections();
498 filterThread.start();
502 * Handles action event for btn_pdbFromFile
505 public void pdbFromFile_actionPerformed()
507 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
508 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
509 chooser.setFileView(new jalview.io.JalviewFileView());
510 chooser.setDialogTitle(
511 MessageManager.formatMessage("label.select_pdb_file_for",
512 selectedSequence.getDisplayId(false)));
513 chooser.setToolTipText(MessageManager.formatMessage(
514 "label.load_pdb_file_associate_with_sequence",
515 selectedSequence.getDisplayId(false)));
517 int value = chooser.showOpenDialog(null);
518 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
520 selectedPdbFileName = chooser.getSelectedFile().getPath();
521 jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
522 validateSelections();
527 * Populates the filter combo-box options dynamically depending on discovered
530 protected void populateFilterComboBox(boolean haveData,
531 boolean cachedPDBExist)
534 * temporarily suspend the change listener behaviour
536 cmb_filterOption.removeItemListener(this);
538 cmb_filterOption.removeAllItems();
541 cmb_filterOption.addItem(new FilterOption(
542 MessageManager.getString("label.best_quality"),
543 "overall_quality", VIEWS_FILTER, false));
544 cmb_filterOption.addItem(new FilterOption(
545 MessageManager.getString("label.best_resolution"),
546 "resolution", VIEWS_FILTER, false));
547 cmb_filterOption.addItem(new FilterOption(
548 MessageManager.getString("label.most_protein_chain"),
549 "number_of_protein_chains", VIEWS_FILTER, false));
550 cmb_filterOption.addItem(new FilterOption(
551 MessageManager.getString("label.most_bound_molecules"),
552 "number_of_bound_molecules", VIEWS_FILTER, false));
553 cmb_filterOption.addItem(new FilterOption(
554 MessageManager.getString("label.most_polymer_residues"),
555 "number_of_polymer_residues", VIEWS_FILTER, true));
557 cmb_filterOption.addItem(
558 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
559 "-", VIEWS_ENTER_ID, false));
560 cmb_filterOption.addItem(
561 new FilterOption(MessageManager.getString("label.from_file"),
562 "-", VIEWS_FROM_FILE, false));
566 FilterOption cachedOption = new FilterOption(
567 MessageManager.getString("label.cached_structures"),
568 "-", VIEWS_LOCAL_PDB, false);
569 cmb_filterOption.addItem(cachedOption);
570 cmb_filterOption.setSelectedItem(cachedOption);
573 cmb_filterOption.addItemListener(this);
577 * Updates the displayed view based on the selected filter option
579 protected void updateCurrentView()
581 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
583 layout_switchableViews.show(pnl_switchableViews,
584 selectedFilterOpt.getView());
585 String filterTitle = mainFrame.getTitle();
586 mainFrame.setTitle(frameTitle);
587 chk_invertFilter.setVisible(false);
588 if (selectedFilterOpt.getView() == VIEWS_FILTER)
590 mainFrame.setTitle(filterTitle);
591 chk_invertFilter.setVisible(true);
592 filterResultSet(selectedFilterOpt.getValue());
594 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
595 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
597 mainFrame.setTitle(MessageManager
598 .getString("label.structure_chooser_manual_association"));
599 idInputAssSeqPanel.loadCmbAssSeq();
600 fileChooserAssSeqPanel.loadCmbAssSeq();
602 validateSelections();
606 * Validates user selection and activates the view button if all parameters
610 public void validateSelections()
612 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
614 btn_view.setEnabled(false);
615 String currentView = selectedFilterOpt.getView();
616 if (currentView == VIEWS_FILTER)
618 if (getResultTable().getSelectedRows().length > 0)
620 btn_view.setEnabled(true);
623 else if (currentView == VIEWS_LOCAL_PDB)
625 if (tbl_local_pdb.getSelectedRows().length > 0)
627 btn_view.setEnabled(true);
630 else if (currentView == VIEWS_ENTER_ID)
632 validateAssociationEnterPdb();
634 else if (currentView == VIEWS_FROM_FILE)
636 validateAssociationFromFile();
641 * Validates inputs from the Manual PDB entry panel
643 public void validateAssociationEnterPdb()
645 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
646 .getCmb_assSeq().getSelectedItem();
647 lbl_pdbManualFetchStatus.setIcon(errorImage);
648 lbl_pdbManualFetchStatus.setToolTipText("");
649 if (txt_search.getText().length() > 0)
651 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
652 MessageManager.formatMessage("info.no_pdb_entry_found_for",
653 txt_search.getText())));
656 if (errorWarning.length() > 0)
658 lbl_pdbManualFetchStatus.setIcon(warningImage);
659 lbl_pdbManualFetchStatus.setToolTipText(
660 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
663 if (selectedSequences.length == 1 || !assSeqOpt.getName()
664 .equalsIgnoreCase("-Select Associated Seq-"))
666 txt_search.setEnabled(true);
669 btn_view.setEnabled(true);
670 lbl_pdbManualFetchStatus.setToolTipText("");
671 lbl_pdbManualFetchStatus.setIcon(goodImage);
676 txt_search.setEnabled(false);
677 lbl_pdbManualFetchStatus.setIcon(errorImage);
682 * Validates inputs for the manual PDB file selection options
684 public void validateAssociationFromFile()
686 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
687 .getCmb_assSeq().getSelectedItem();
688 lbl_fromFileStatus.setIcon(errorImage);
689 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
690 .getName().equalsIgnoreCase("-Select Associated Seq-")))
692 btn_pdbFromFile.setEnabled(true);
693 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
695 btn_view.setEnabled(true);
696 lbl_fromFileStatus.setIcon(goodImage);
701 btn_pdbFromFile.setEnabled(false);
702 lbl_fromFileStatus.setIcon(errorImage);
707 public void cmbAssSeqStateChanged()
709 validateSelections();
713 * Handles the state change event for the 'filter' combo-box and 'invert'
717 protected void stateChanged(ItemEvent e)
719 if (e.getSource() instanceof JCheckBox)
725 if (e.getStateChange() == ItemEvent.SELECTED)
734 * select structures for viewing by their PDB IDs
737 * @return true if structures were found and marked as selected
739 public boolean selectStructure(String... pdbids)
741 boolean found = false;
743 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
745 String currentView = selectedFilterOpt.getView();
746 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
747 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
749 if (restable == null)
751 // can't select (enter PDB ID, or load file - need to also select which
752 // sequence to associate with)
756 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
757 for (int r = 0; r < restable.getRowCount(); r++)
759 for (int p = 0; p < pdbids.length; p++)
761 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
762 .equalsIgnoreCase(pdbids[p]))
764 restable.setRowSelectionInterval(r, r);
772 * Handles action event for btn_ok
775 public void ok_ActionPerformed()
777 showStructures(false);
781 * structure viewer opened by this dialog, or null
783 private StructureViewer sViewer = null;
785 public void showStructures(boolean waitUntilFinished)
788 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
790 final int preferredHeight = pnl_filter.getHeight();
792 Runnable viewStruc = new Runnable()
797 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
799 String currentView = selectedFilterOpt.getView();
800 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
803 if (currentView == VIEWS_FILTER)
805 int pdbIdColIndex = restable.getColumn("PDB Id")
807 int refSeqColIndex = restable.getColumn("Ref Sequence")
809 int[] selectedRows = restable.getSelectedRows();
810 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
812 List<SequenceI> selectedSeqsToView = new ArrayList<>();
813 for (int row : selectedRows)
815 String pdbIdStr = restable
816 .getValueAt(row, pdbIdColIndex).toString();
817 SequenceI selectedSeq = (SequenceI) restable
818 .getValueAt(row, refSeqColIndex);
819 selectedSeqsToView.add(selectedSeq);
820 PDBEntry pdbEntry = selectedSeq.getPDBEntry(pdbIdStr);
821 if (pdbEntry == null)
823 pdbEntry = getFindEntry(pdbIdStr,
824 selectedSeq.getAllPDBEntries());
827 if (pdbEntry == null)
829 pdbEntry = new PDBEntry();
830 pdbEntry.setId(pdbIdStr);
831 pdbEntry.setType(PDBEntry.Type.PDB);
832 selectedSeq.getDatasetSequence().addPDBId(pdbEntry);
834 pdbEntriesToView[count++] = pdbEntry;
836 SequenceI[] selectedSeqs = selectedSeqsToView
837 .toArray(new SequenceI[selectedSeqsToView.size()]);
838 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
841 else if (currentView == VIEWS_LOCAL_PDB)
843 int[] selectedRows = tbl_local_pdb.getSelectedRows();
844 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
846 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
848 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
850 List<SequenceI> selectedSeqsToView = new ArrayList<>();
851 for (int row : selectedRows)
853 PDBEntry pdbEntry = (PDBEntry) tbl_local_pdb.getValueAt(row,
855 pdbEntriesToView[count++] = pdbEntry;
856 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
857 .getValueAt(row, refSeqColIndex);
858 selectedSeqsToView.add(selectedSeq);
860 SequenceI[] selectedSeqs = selectedSeqsToView
861 .toArray(new SequenceI[selectedSeqsToView.size()]);
862 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
865 else if (currentView == VIEWS_ENTER_ID)
867 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
868 .getCmb_assSeq().getSelectedItem()).getSequence();
869 if (userSelectedSeq != null)
871 selectedSequence = userSelectedSeq;
873 String pdbIdStr = txt_search.getText();
874 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
875 if (pdbEntry == null)
877 pdbEntry = new PDBEntry();
878 if (pdbIdStr.split(":").length > 1)
880 pdbEntry.setId(pdbIdStr.split(":")[0]);
881 pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase());
885 pdbEntry.setId(pdbIdStr);
887 pdbEntry.setType(PDBEntry.Type.PDB);
888 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
891 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
892 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
894 { selectedSequence });
896 else if (currentView == VIEWS_FROM_FILE)
898 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
899 .getCmb_assSeq().getSelectedItem()).getSequence();
900 if (userSelectedSeq != null)
902 selectedSequence = userSelectedSeq;
904 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
905 .associatePdbWithSeq(selectedPdbFileName,
906 DataSourceType.FILE, selectedSequence, true,
909 sViewer = launchStructureViewer(
913 { selectedSequence });
915 SwingUtilities.invokeLater(new Runnable()
920 closeAction(preferredHeight);
926 Thread runner = new Thread(viewStruc);
928 if (waitUntilFinished)
930 while (sViewer == null ? runner.isAlive()
931 : (sViewer.sview == null ? true
932 : !sViewer.sview.hasMapping()))
937 } catch (InterruptedException ie)
945 private PDBEntry getFindEntry(String id, Vector<PDBEntry> pdbEntries)
947 Objects.requireNonNull(id);
948 Objects.requireNonNull(pdbEntries);
949 PDBEntry foundEntry = null;
950 for (PDBEntry entry : pdbEntries)
952 if (entry.getId().equalsIgnoreCase(id))
960 private StructureViewer launchStructureViewer(
961 StructureSelectionManager ssm,
962 final PDBEntry[] pdbEntriesToView,
963 final AlignmentPanel alignPanel, SequenceI[] sequences)
965 long progressId = sequences.hashCode();
966 setProgressBar(MessageManager
967 .getString("status.launching_3d_structure_viewer"), progressId);
968 final StructureViewer sViewer = new StructureViewer(ssm);
969 setProgressBar(null, progressId);
971 if (SiftsSettings.isMapWithSifts())
973 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
975 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
976 // real PDB ID. For moment, we can also safely do this if there is already
977 // a known mapping between the PDBEntry and the sequence.
978 for (SequenceI seq : sequences)
980 PDBEntry pdbe = pdbEntriesToView[p++];
981 if (pdbe != null && pdbe.getFile() != null)
983 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
984 if (smm != null && smm.length > 0)
986 for (StructureMapping sm : smm)
988 if (sm.getSequence() == seq)
995 if (seq.getPrimaryDBRefs().size() == 0)
997 seqsWithoutSourceDBRef.add(seq);
1001 if (!seqsWithoutSourceDBRef.isEmpty())
1003 int y = seqsWithoutSourceDBRef.size();
1004 setProgressBar(MessageManager.formatMessage(
1005 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1007 SequenceI[] seqWithoutSrcDBRef = new SequenceI[y];
1009 for (SequenceI fSeq : seqsWithoutSourceDBRef)
1011 seqWithoutSrcDBRef[x++] = fSeq;
1014 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
1015 dbRefFetcher.fetchDBRefs(true);
1017 setProgressBar("Fetch complete.", progressId); // todo i18n
1020 if (pdbEntriesToView.length > 1)
1022 setProgressBar(MessageManager.getString(
1023 "status.fetching_3d_structures_for_selected_entries"),
1025 sViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
1029 setProgressBar(MessageManager.formatMessage(
1030 "status.fetching_3d_structures_for",
1031 pdbEntriesToView[0].getId()),progressId);
1032 sViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1034 setProgressBar(null, progressId);
1039 * Populates the combo-box used in associating manually fetched structures to
1040 * a unique sequence when more than one sequence selection is made.
1043 public void populateCmbAssociateSeqOptions(
1044 JComboBox<AssociateSeqOptions> cmb_assSeq,
1045 JLabel lbl_associateSeq)
1047 cmb_assSeq.removeAllItems();
1049 new AssociateSeqOptions("-Select Associated Seq-", null));
1050 lbl_associateSeq.setVisible(false);
1051 if (selectedSequences.length > 1)
1053 for (SequenceI seq : selectedSequences)
1055 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1060 String seqName = selectedSequence.getDisplayId(false);
1061 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1062 lbl_associateSeq.setText(seqName);
1063 lbl_associateSeq.setVisible(true);
1064 cmb_assSeq.setVisible(false);
1068 public boolean isStructuresDiscovered()
1070 return discoveredStructuresSet != null
1071 && !discoveredStructuresSet.isEmpty();
1074 public Collection<FTSData> getDiscoveredStructuresSet()
1076 return discoveredStructuresSet;
1080 protected void txt_search_ActionPerformed()
1087 errorWarning.setLength(0);
1088 isValidPBDEntry = false;
1089 if (txt_search.getText().length() > 0)
1091 String searchTerm = txt_search.getText().toLowerCase();
1092 searchTerm = searchTerm.split(":")[0];
1093 // System.out.println(">>>>> search term : " + searchTerm);
1094 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1095 FTSRestRequest pdbRequest = new FTSRestRequest();
1096 pdbRequest.setAllowEmptySeq(false);
1097 pdbRequest.setResponseSize(1);
1098 pdbRequest.setFieldToSearchBy("(pdb_id:");
1099 pdbRequest.setWantedFields(wantedFields);
1100 pdbRequest.setSearchTerm(searchTerm + ")");
1101 pdbRequest.setAssociatedSequence(selectedSequence);
1102 pdbRestCleint = PDBFTSRestClient.getInstance();
1103 wantedFields.add(pdbRestCleint.getPrimaryKeyColumn());
1104 FTSRestResponse resultList;
1107 resultList = pdbRestCleint.executeRequest(pdbRequest);
1108 } catch (Exception e)
1110 errorWarning.append(e.getMessage());
1114 validateSelections();
1116 if (resultList.getSearchSummary() != null
1117 && resultList.getSearchSummary().size() > 0)
1119 isValidPBDEntry = true;
1122 validateSelections();
1128 public void tabRefresh()
1130 if (selectedSequences != null)
1132 Thread refreshThread = new Thread(new Runnable()
1137 fetchStructuresMetaData();
1139 ((FilterOption) cmb_filterOption.getSelectedItem())
1143 refreshThread.start();
1147 public class PDBEntryTableModel extends AbstractTableModel
1149 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1152 private List<CachedPDB> pdbEntries;
1154 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1156 this.pdbEntries = new ArrayList<>(pdbEntries);
1160 public String getColumnName(int columnIndex)
1162 return columns[columnIndex];
1166 public int getRowCount()
1168 return pdbEntries.size();
1172 public int getColumnCount()
1174 return columns.length;
1178 public boolean isCellEditable(int row, int column)
1184 public Object getValueAt(int rowIndex, int columnIndex)
1186 Object value = "??";
1187 CachedPDB entry = pdbEntries.get(rowIndex);
1188 switch (columnIndex)
1191 value = entry.getSequence();
1194 value = entry.getPdbEntry();
1197 value = entry.getPdbEntry().getChainCode() == null ? "_"
1198 : entry.getPdbEntry().getChainCode();
1201 value = entry.getPdbEntry().getType();
1204 value = entry.getPdbEntry().getFile();
1211 public Class<?> getColumnClass(int columnIndex)
1213 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1216 public CachedPDB getPDBEntryAt(int row)
1218 return pdbEntries.get(row);
1223 private class CachedPDB
1225 private SequenceI sequence;
1227 private PDBEntry pdbEntry;
1229 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1231 this.sequence = sequence;
1232 this.pdbEntry = pdbEntry;
1235 public SequenceI getSequence()
1240 public PDBEntry getPdbEntry()
1247 private IProgressIndicator progressBar;
1250 public void setProgressBar(String message, long id)
1252 progressBar.setProgressBar(message, id);
1256 public void registerHandler(long id, IProgressIndicatorHandler handler)
1258 progressBar.registerHandler(id, handler);
1262 public boolean operationInProgress()
1264 return progressBar.operationInProgress();
1267 public JalviewStructureDisplayI getOpenedStructureViewer()
1269 return sViewer == null ? null : sViewer.sview;