3 * Copyright (C) 2014 EDIT
4 * European Distributed Institute of Taxonomy
5 * http://www.e-taxonomy.eu
7 * The contents of this file are subject to the Mozilla Public License Version 1.1
8 * See LICENSE.TXT at the top of this package for the full license terms.
10 package eu
.etaxonomy
.taxeditor
.editor
.molecular
;
13 import info
.bioinfweb
.libralign
.alignmentarea
.AlignmentArea
;
14 import info
.bioinfweb
.libralign
.alignmentarea
.selection
.SelectionModel
;
15 import info
.bioinfweb
.libralign
.dataarea
.implementations
.ConsensusSequenceArea
;
16 import info
.bioinfweb
.libralign
.dataarea
.implementations
.SequenceIndexArea
;
17 import info
.bioinfweb
.libralign
.dataarea
.implementations
.pherogram
.PherogramAlignmentModel
;
18 import info
.bioinfweb
.libralign
.dataarea
.implementations
.pherogram
.PherogramArea
;
19 import info
.bioinfweb
.libralign
.dataarea
.implementations
.pherogram
.ShiftChange
;
20 import info
.bioinfweb
.libralign
.editsettings
.EditSettingsChangeEvent
;
21 import info
.bioinfweb
.libralign
.editsettings
.EditSettingsListener
;
22 import info
.bioinfweb
.libralign
.model
.AlignmentModel
;
23 import info
.bioinfweb
.libralign
.model
.AlignmentModelChangeListener
;
24 import info
.bioinfweb
.libralign
.model
.SequenceUtils
;
25 import info
.bioinfweb
.libralign
.model
.adapters
.StringAdapter
;
26 import info
.bioinfweb
.libralign
.model
.events
.SequenceChangeEvent
;
27 import info
.bioinfweb
.libralign
.model
.events
.SequenceRenamedEvent
;
28 import info
.bioinfweb
.libralign
.model
.events
.TokenChangeEvent
;
29 import info
.bioinfweb
.libralign
.model
.implementations
.PackedAlignmentModel
;
30 import info
.bioinfweb
.libralign
.model
.tokenset
.BioJavaTokenSet
;
31 import info
.bioinfweb
.libralign
.model
.tokenset
.TokenSet
;
32 import info
.bioinfweb
.libralign
.multiplealignments
.AlignmentAreaList
;
33 import info
.bioinfweb
.libralign
.multiplealignments
.MultipleAlignmentsContainer
;
34 import info
.bioinfweb
.libralign
.pherogram
.model
.BioJavaPherogramModel
;
35 import info
.bioinfweb
.libralign
.pherogram
.model
.PherogramModel
;
36 import info
.bioinfweb
.libralign
.pherogram
.model
.ReverseComplementPherogramModel
;
39 import java
.io
.IOException
;
40 import java
.io
.InputStream
;
42 import java
.util
.ArrayList
;
43 import java
.util
.Collection
;
44 import java
.util
.Collections
;
45 import java
.util
.Iterator
;
47 import java
.util
.TreeMap
;
49 import org
.biojava
.bio
.chromatogram
.ChromatogramFactory
;
50 import org
.biojava
.bio
.chromatogram
.UnsupportedChromatogramFormatException
;
51 import org
.biojava3
.core
.sequence
.compound
.DNACompoundSet
;
52 import org
.biojava3
.core
.sequence
.compound
.NucleotideCompound
;
53 import org
.eclipse
.core
.runtime
.IProgressMonitor
;
54 import org
.eclipse
.swt
.SWT
;
55 import org
.eclipse
.swt
.widgets
.Composite
;
56 import org
.eclipse
.ui
.IActionBars
;
57 import org
.eclipse
.ui
.IEditorInput
;
58 import org
.eclipse
.ui
.IEditorPart
;
59 import org
.eclipse
.ui
.IEditorSite
;
60 import org
.eclipse
.ui
.PartInitException
;
61 import org
.eclipse
.ui
.PlatformUI
;
62 import org
.eclipse
.ui
.commands
.ICommandService
;
63 import org
.eclipse
.ui
.part
.EditorPart
;
65 import eu
.etaxonomy
.cdm
.api
.conversation
.ConversationHolder
;
66 import eu
.etaxonomy
.cdm
.api
.service
.molecular
.ISequenceService
;
67 import eu
.etaxonomy
.cdm
.model
.media
.MediaUtils
;
68 import eu
.etaxonomy
.cdm
.model
.molecular
.Sequence
;
69 import eu
.etaxonomy
.cdm
.model
.molecular
.SequenceString
;
70 import eu
.etaxonomy
.cdm
.model
.molecular
.SingleRead
;
71 import eu
.etaxonomy
.cdm
.model
.molecular
.SingleReadAlignment
;
72 import eu
.etaxonomy
.taxeditor
.editor
.handler
.alignmenteditor
.ToggleInsertOverwriteHandler
;
73 import eu
.etaxonomy
.taxeditor
.editor
.handler
.alignmenteditor
.ToggleLeftRightInsertionHandler
;
74 import eu
.etaxonomy
.taxeditor
.store
.CdmStore
;
79 * Editor component to edit a contig alignment used to combine different overlapping pherograms from Sanger sequencing to
80 * a consensus sequence.
82 * The contained GUI components used to edit the alignment come from <a href="http://bioinfweb.info/LibrAlign/">LibrAlign</a>.
88 public class AlignmentEditor
extends EditorPart
{
89 public static final String ID
= "eu.etaxonomy.taxeditor.editor.molecular.AlignmentEditor";
91 public static final int READS_AREA_INDEX
= 1;
92 public static final int CONSENSUS_AREA_INDEX
= READS_AREA_INDEX
+ 1;
93 public static final int PHEROGRAM_AREA_INDEX
= 0;
94 public static final String DEFAULT_READ_NAME_PREFIX
= "Read ";
95 public static final String CONSENSUS_NAME
= "Consensus";
98 private final ConversationHolder conversationHolder
;
100 private final AlignmentModelChangeListener DIRTY_LISTENER
= new AlignmentModelChangeListener() {
102 public <T
> void afterTokenChange(TokenChangeEvent
<T
> e
) {
107 public <T
> void afterSequenceRenamed(SequenceRenamedEvent
<T
> e
) {
112 public <T
> void afterSequenceChange(SequenceChangeEvent
<T
> e
) {
117 public <T
, U
> void afterProviderChanged(AlignmentModel
<T
> oldProvider
,
118 AlignmentModel
<U
> newProvider
) { // Not expected.
124 private MultipleAlignmentsContainer alignmentsContainer
= null;
125 private final Map
<Integer
, SingleReadAlignment
> cdmMap
= new TreeMap
<Integer
, SingleReadAlignment
>(); //TODO Move this to ContigSequenceDataProvider
126 private boolean dirty
= false;
129 public AlignmentEditor() {
131 //conversationHolder = CdmStore.createConversation();
132 conversationHolder
= null;
136 private void refreshToolbarElement(String id
) {
137 ICommandService commandService
=
138 (ICommandService
)PlatformUI
.getWorkbench().getActiveWorkbenchWindow().getService(ICommandService
.class);
139 if (commandService
!= null) {
140 commandService
.refreshElements(id
, Collections
.EMPTY_MAP
);
145 private void registerEditSettingListener(MultipleAlignmentsContainer container
) {
146 container
.getEditSettings().addListener(new EditSettingsListener() {
148 public void workingModeChanged(EditSettingsChangeEvent e
) {} // Currently nothing to do
151 public void insertLeftInDataAreaChanged(EditSettingsChangeEvent e
) {
153 refreshToolbarElement(ToggleLeftRightInsertionHandler
.COMMAND_ID
);
157 public void insertChanged(EditSettingsChangeEvent e
) {
159 refreshToolbarElement(ToggleInsertOverwriteHandler
.COMMAND_ID
);
165 private AlignmentArea
createIndexArea(MultipleAlignmentsContainer container
) {
166 AlignmentArea result
= new AlignmentArea(container
);
167 result
.setAllowVerticalScrolling(false);
168 result
.getDataAreas().getTopAreas().add(new SequenceIndexArea(result
.getContentArea()));
173 private AlignmentArea
createEditableAlignmentArea(MultipleAlignmentsContainer container
, boolean allowVerticalScrolling
) {
174 AlignmentArea result
= new AlignmentArea(container
);
175 result
.setAllowVerticalScrolling(allowVerticalScrolling
);
177 TokenSet
<NucleotideCompound
> tokenSet
= new BioJavaTokenSet
<NucleotideCompound
>(new DNACompoundSet(), true);
178 AlignmentModel
<NucleotideCompound
> provider
= new PackedAlignmentModel
<NucleotideCompound
>(tokenSet
);
179 result
.setAlignmentModel(provider
, false);
180 provider
.getChangeListeners().add(DIRTY_LISTENER
);
186 private AlignmentArea
createConsensusHintArea(MultipleAlignmentsContainer container
,
187 AlignmentModel
<?
> sequenceProvider
) {
189 AlignmentArea result
= new AlignmentArea(container
);
190 result
.setAllowVerticalScrolling(false);
191 result
.getDataAreas().getBottomAreas().add(
192 new ConsensusSequenceArea(result
.getContentArea(), sequenceProvider
));
197 private MultipleAlignmentsContainer
getAlignmentsContainer() {
198 if (alignmentsContainer
== null) {
199 alignmentsContainer
= new MultipleAlignmentsContainer();
201 AlignmentAreaList list
= alignmentsContainer
.getAlignmentAreas();
202 list
.add(createIndexArea(alignmentsContainer
));
203 AlignmentArea readsArea
= createEditableAlignmentArea(alignmentsContainer
, true);
204 list
.add(readsArea
); // Make sure READS_AREA_INDEX is correct.
205 list
.add(createEditableAlignmentArea(alignmentsContainer
, false)); // Make sure COMSENSUS_AREA_INDEX is correct.
206 list
.add(createConsensusHintArea(alignmentsContainer
,
207 readsArea
.getAlignmentModel()));
209 registerEditSettingListener(alignmentsContainer
);
211 return alignmentsContainer
;
215 private AlignmentArea
getReadsArea() {
216 return getAlignmentsContainer().getAlignmentAreas().get(READS_AREA_INDEX
);
220 private AlignmentArea
getConsensusArea() {
221 return getAlignmentsContainer().getAlignmentAreas().get(CONSENSUS_AREA_INDEX
);
225 private PherogramArea
getPherogramArea(int sequenceID
) {
226 return (PherogramArea
)getReadsArea().getDataAreas().getSequenceAreas(sequenceID
).get(PHEROGRAM_AREA_INDEX
);
230 private void createTestContents() {
233 addRead(new File("D:/Users/BenStoever/Documents/Studium/Projekte/Promotion/EDITor/Quelltexte/LibrAlign branch/Repository/eu.etaxonomy.taxeditor.editor/src/main/resources/AlignmentTestData/JR430_JR-P01.ab1").toURI(), false);
234 addRead(new File("D:/Users/BenStoever/Documents/Studium/Projekte/Promotion/EDITor/Quelltexte/LibrAlign branch/Repository/eu.etaxonomy.taxeditor.editor/src/main/resources/AlignmentTestData/JR444_JR-P05.ab1").toURI(), false);
236 // Add test consensus sequence:
237 AlignmentModel consensusProvider
= getConsensusArea().getAlignmentModel();
238 int id
= consensusProvider
.addSequence(CONSENSUS_NAME
);
239 Collection
<Object
> tokens
= new ArrayList
<Object
>(); // First save tokens in a collection to avoid GUI updated for each token.
240 tokens
.add(consensusProvider
.getTokenSet().tokenByKeyChar('A'));
241 tokens
.add(consensusProvider
.getTokenSet().tokenByKeyChar('C'));
242 tokens
.add(consensusProvider
.getTokenSet().tokenByKeyChar('G'));
243 tokens
.add(consensusProvider
.getTokenSet().tokenByKeyChar('T'));
244 consensusProvider
.insertTokensAt(id
, 0, tokens
);
246 catch (Exception e
) {
247 throw new RuntimeException(e
);
252 private void readCDMData(Sequence sequenceNode
) {
253 //TODO If called from somewhere else than createPartControl() the editorInput needs to be checked and previous contents need to be cleared (or updated).
256 for (SingleReadAlignment singleReadAlignment
: sequenceNode
.getSingleReadAlignments()) {
258 SingleRead pherogramInfo
= singleReadAlignment
.getSingleRead();
259 int id
= addRead(pherogramInfo
.getPrimer().getLabel(), //TODO Should the sequence name contain other/additional/alternative data? Can the same string as in the derivative tree be used here?
260 MediaUtils
.getFirstMediaRepresentationPart(pherogramInfo
.getPherogram()).getUri(),
261 singleReadAlignment
.isReverseComplement(),
262 singleReadAlignment
.getEditedSequence(),
263 singleReadAlignment
.getShifts());
264 cdmMap
.put(id
, singleReadAlignment
);
266 catch (IOException e
) {
267 e
.printStackTrace(); //TODO Output to user (Possibly collect for all pherograms and display in the end.)
269 catch (UnsupportedChromatogramFormatException e
) {
270 e
.printStackTrace(); //TODO Output to user (Possibly collect for all pherograms and display in the end.)
274 // Set consensus sequence:
275 AlignmentModel consensusProvider
= getConsensusArea().getAlignmentModel();
276 int id
= consensusProvider
.addSequence(CONSENSUS_NAME
);
277 consensusProvider
.insertTokensAt(id
, 0, SequenceUtils
.stringToTokenList(
278 sequenceNode
.getConsensusSequence().getString(), consensusProvider
.getTokenSet()));
279 //TODO Can the consensus sequence also be null? / Should it be created here, if nothing is in the DB?
284 * @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
287 public void createPartControl(Composite parent
) {
288 getAlignmentsContainer().createSWTWidget(parent
, SWT
.NONE
);
291 if (getEditorInput() instanceof AlignmentEditorInput
) {
292 if (((AlignmentEditorInput
)getEditorInput()).getSequenceNode() != null) {
293 Sequence sequenceNode
= ((AlignmentEditorInput
)getEditorInput()).getSequenceNode();
294 //re-load into the current session if it is already persisted in the DB
295 if(sequenceNode
!=null && sequenceNode
.getId()!=0){
296 sequenceNode
= CdmStore
.getService(ISequenceService
.class).load(sequenceNode
.getUuid());
298 readCDMData(sequenceNode
);
301 createTestContents(); // This case will removed after the test phase and an exception should probably be thrown.
305 throw new IllegalArgumentException("The editor input must have the type " +
306 AlignmentEditorInput
.class.getCanonicalName()); //TODO What should be done here?
311 private void updateStatusBar() {
312 IActionBars bars
= getEditorSite().getActionBars();
313 bars
.getStatusLineManager().setMessage("Edit mode: " +
314 (getReadsArea().getEditSettings().isInsert() ?
"Insert" : "Overwrite") + " " +
315 "Insertion in pherogram: " +
316 (getReadsArea().getEditSettings().isInsertLeftInDataArea() ?
"Left" : "Right"));
320 private SingleReadAlignment
.Shift
[] convertToCDMShifts(PherogramAlignmentModel alignmentModel
) {
321 SingleReadAlignment
.Shift
[] result
= new SingleReadAlignment
.Shift
[alignmentModel
.getShiftChangeCount()];
322 Iterator
<ShiftChange
> iterator
= alignmentModel
.shiftChangeIterator();
324 while (iterator
.hasNext()) {
325 ShiftChange shiftChange
= iterator
.next();
326 result
[pos
] = new SingleReadAlignment
.Shift(shiftChange
.getBaseCallIndex(), shiftChange
.getShiftChange());
333 * @see org.eclipse.ui.part.EditorPart#doSave(org.eclipse.core.runtime.IProgressMonitor)
336 public void doSave(IProgressMonitor monitor
) {
337 if (getEditorInput() instanceof AlignmentEditorInput
) {
338 String taskName
= "Saving alignment";
339 monitor
.beginTask(taskName
, 3);
341 Sequence sequenceNode
= ((AlignmentEditorInput
)getEditorInput()).getSequenceNode();
342 StringAdapter stringProvider
= new StringAdapter(getConsensusArea().getAlignmentModel(), false); // Throws an exception if a token has more than one character.
344 // Write consensus sequence:
345 SequenceString consensusSequenceObj
= sequenceNode
.getConsensusSequence();
346 String newConsensusSequence
= stringProvider
.getSequence(
347 getConsensusArea().getAlignmentModel().sequenceIDByName(CONSENSUS_NAME
));
348 if (consensusSequenceObj
== null) {
349 sequenceNode
.setConsensusSequence(SequenceString
.NewInstance(newConsensusSequence
));
352 consensusSequenceObj
.setString(newConsensusSequence
);
355 // Write single reads:
356 stringProvider
.setUnderlyingProvider(getReadsArea().getAlignmentModel());
357 sequenceNode
.getSingleReadAlignments().retainAll(cdmMap
.values()); // Remove all reads that are not in the alignment anymore.
358 Iterator
<Integer
> iterator
= getReadsArea().getAlignmentModel().sequenceIDIterator();
359 while (iterator
.hasNext()) {
360 int id
= iterator
.next();
361 SingleReadAlignment singleRead
= cdmMap
.get(id
);
362 if (singleRead
== null) {
363 //TODO Create new read object. => Shall it be allowed to add reads in the alignment editor which are not represented in the CDM tree before the alignment editor is saved?
364 //singleRead = SingleReadAlignment.NewInstance(consensusSequence, singleRead, shifts, editedSequence);
367 singleRead
.setEditedSequence(stringProvider
.getSequence(id
));
368 singleRead
.setReverseComplement(getPherogramArea(id
).getProvider() instanceof ReverseComplementPherogramModel
); // Works only if ReverseComplementPherogramProvider instances are not nested.
369 singleRead
.setShifts(convertToCDMShifts(getPherogramArea(id
).getAlignmentModel()));
372 if (!conversationHolder
.isBound()) {
373 conversationHolder
.bind();
377 // Commit the conversation and start a new transaction immediately:
378 conversationHolder
.commit(true);
384 firePropertyChange(PROP_DIRTY
);
387 //TODO Throw exception as soon as testing period which allows unlinked AlignmentEditor is over.
393 * @see org.eclipse.ui.part.EditorPart#doSaveAs()
396 public void doSaveAs() {}
400 * @see org.eclipse.ui.part.EditorPart#init(org.eclipse.ui.IEditorSite, org.eclipse.ui.IEditorInput)
403 public void init(IEditorSite site
, IEditorInput input
) throws PartInitException
{
410 * @see org.eclipse.ui.part.EditorPart#isDirty()
413 public boolean isDirty() {
418 private void setDirty() {
420 firePropertyChange(IEditorPart
.PROP_DIRTY
);
425 * @see org.eclipse.ui.part.EditorPart#isSaveAsAllowed()
428 public boolean isSaveAsAllowed() {
429 return false; // "Save as" not allowed.
434 public void setFocus() {
435 if(conversationHolder
!=null){
436 conversationHolder
.bind();
441 public boolean isInsertMode() {
442 return getAlignmentsContainer().getEditSettings().isInsert();
446 public boolean isInsertLeftInPherogram() {
447 return getAlignmentsContainer().getEditSettings().isInsertLeftInDataArea();
451 public void toggleLeftRightInsertionInPherogram() {
452 getAlignmentsContainer().getEditSettings().toggleInsertLeftInDataArea();
456 public void toggleInsertOverwrite() {
457 getAlignmentsContainer().getEditSettings().toggleInsert();
461 public void reverseComplementSelection() {
462 SelectionModel selection
= getReadsArea().getSelection();
463 AlignmentModel
<?
> provider
= getReadsArea().getAlignmentModel();
464 for (int row
= selection
.getStartRow(); row
< selection
.getStartRow() + selection
.getCursorHeight(); row
++) {
465 int sequenceID
= getReadsArea().getSequenceOrder().idByIndex(row
);
466 //TODO rc edited sequence
468 if (getPherogramArea(sequenceID
).getProvider() instanceof ReverseComplementPherogramModel
) {
469 //getPherogramArea(sequenceID).
470 //TODO Allow to set new provider in PherogramArea or create new PherogramArea
471 //TODO Reposition pherogram according to previous position in edited sequence and length
477 public static PherogramModel
readPherogram(URI uri
) throws IOException
, UnsupportedChromatogramFormatException
{
478 PherogramModel result
;
479 InputStream stream
= uri
.toURL().openStream();
481 result
= new BioJavaPherogramModel(ChromatogramFactory
.create(stream
));
490 private String
newReadName() {
492 while (getReadsArea().getAlignmentModel().sequenceIDByName(DEFAULT_READ_NAME_PREFIX
+ index
)
493 != AlignmentModel
.NO_SEQUENCE_FOUND
) {
497 return DEFAULT_READ_NAME_PREFIX
+ index
;
501 public void addRead(URI pherogramURI
, boolean reverseComplemented
) throws IOException
, UnsupportedChromatogramFormatException
{
502 addRead(newReadName(), pherogramURI
, reverseComplemented
, null, null);
507 * Adds a new sequence with attached phergram data area to the reads alignment.
509 * If {@code null} is specified as {@code editedSequence} the base call sequence from the pherogram will
510 * be set as the edited sequence. If {@code null} is specified as {@code shifts} no shifts between the edited
511 * and the base calls sequence are assumed.
513 * @param name the name of the new sequence
514 * @param pherogramURI the URI where the associated pherogram file is located
515 * @param reverseComplemented Specify {@code true} here, if the reverse complement of the pherogram data should
516 * be added, {@code false} otherwise.
517 * @param editedSequence the edited version of the base call sequence (May be {@code null}.)
518 * @param shifts the alignment information that links the edited and the base call sequence (May be {@code null}.)
519 * @return the sequence ID of the added read
520 * @throws IOException if an error occurred when trying to read the pherogram file
521 * @throws UnsupportedChromatogramFormatException if the format of the pherogram file is not supported
523 public int addRead(String name
, URI pherogramURI
, boolean reverseComplemented
, String editedSequence
,
524 SingleReadAlignment
.Shift
[] shifts
) throws IOException
, UnsupportedChromatogramFormatException
{
526 AlignmentModel provider
= getReadsArea().getAlignmentModel();
527 PherogramModel pherogramProvider
= readPherogram(pherogramURI
); // Must happen before a sequence is added, because it might throw an exception.
528 if (reverseComplemented
) {
529 pherogramProvider
= new ReverseComplementPherogramModel(pherogramProvider
);
533 provider
.addSequence(name
);
534 int id
= provider
.sequenceIDByName(name
);
536 // Set edited sequence:
537 Collection
<Object
> tokens
; // First save tokens in a collection to avoid GUI updated for each token.
538 if (editedSequence
!= null) {
539 tokens
= SequenceUtils
.stringToTokenList(editedSequence
, provider
.getTokenSet());
541 else { // Copy base call sequence into alignment:
542 tokens
= new ArrayList
<Object
>();
543 for (int i
= 0; i
< pherogramProvider
.getSequenceLength(); i
++) {
544 tokens
.add(provider
.getTokenSet().tokenByKeyChar(
545 pherogramProvider
.getBaseCall(i
).getUpperedBase().charAt(0)));
549 provider
.insertTokensAt(id
, 0, tokens
);
551 // Create pherogram area:
552 PherogramArea pherogramArea
= new PherogramArea(getReadsArea().getContentArea(), pherogramProvider
);
555 if ((shifts
!= null) && (shifts
.length
> 0)) {
556 PherogramAlignmentModel alignmentModel
= pherogramArea
.getAlignmentModel();
557 for (int i
= 0; i
< shifts
.length
; i
++) {
558 alignmentModel
.addShiftChange(shifts
[i
].position
, shifts
[i
].shift
);
563 // Add pherogram area to GUI:
564 pherogramArea
.addMouseListener(new PherogramMouseListener(pherogramURI
));
565 getReadsArea().getDataAreas().getSequenceAreas(id
).add(pherogramArea
);