/
MamutExporter.java
783 lines (689 loc) · 30.9 KB
/
MamutExporter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
package org.mastodon.revised.model.mamut.trackmate;
import static org.mastodon.feature.Multiplicity.SINGLE;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.ANALYZER_COLLECTION_TAG;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.ANALYZER_KEY_ATTRIBUTE;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.ANALYZER_TAG;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.BOOKMARKS_TAG;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.EDGE_ANALYZERS_TAG;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.EDGE_FEATURE_DECLARATION_TAG;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.EDGE_SOURCE_ATTRIBUTE;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.EDGE_TAG;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.EDGE_TARGET_ANALYZER_VALUE;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.EDGE_TARGET_ATTRIBUTE;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.FEATURE_ATTRIBUTE;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.FEATURE_DECLARATION_TAG;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.FEATURE_DIMENSION_ATTRIBUTE;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.FEATURE_ISINT_ATTRIBUTE;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.FEATURE_NAME_ATTRIBUTE;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.FEATURE_SHORT_NAME_ATTRIBUTE;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.FEATURE_TAG;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.FILENAME_ATTRIBUTE;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.FILTERED_TRACKS_TAG;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.FILTER_FEATURE_ATTRIBUTE;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.FILTER_IS_ABOVE_ATTRIBUTE;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.FILTER_VALUE_ATTRIBUTE;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.FOLDER_ATTRIBUTE;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.FRAME_ATTRIBUTE;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.FRAME_FEATURE_NAME;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.GUI_STATE_TAG;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.HEIGHT_ATTRIBUTE;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.ID_FEATURE_NAME;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.IMAGE_DATA_TAG;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.INITIAL_SPOT_FILTER_TAG;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.LABEL_FEATURE_NAME;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.MODEL_TAG;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.NFRAMES_ATTRIBUTE;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.NSLICES_ATTRIBUTE;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.PIXEL_HEIGHT_ATTRIBUTE;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.PIXEL_WIDTH_ATTRIBUTE;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.POSITION_T_FEATURE_NAME;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.POSITION_X_FEATURE_NAME;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.POSITION_Y_FEATURE_NAME;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.POSITION_Z_FEATURE_NAME;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.QUALITY_FEATURE_NAME;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.RADIUS_FEATURE_NAME;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.SETTINGS_TAG;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.SETUP_ASSIGNMENTS_TAG;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.SPATIAL_UNITS_ATTRIBUTE;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.SPOT_ANALYZERS_TAG;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.SPOT_COLLECTION_NSPOTS_ATTRIBUTE;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.SPOT_COLLECTION_TAG;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.SPOT_ELEMENT_TAG;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.SPOT_FEATURE_DECLARATION_TAG;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.SPOT_FILTER_COLLECTION_TAG;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.SPOT_FRAME_COLLECTION_TAG;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.TIME_UNITS_ATTRIBUTE;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.TRACKMATE_TAG;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.TRACK_ANALYZERS_TAG;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.TRACK_COLLECTION_TAG;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.TRACK_FEATURE_DECLARATION_TAG;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.TRACK_FILTER_COLLECTION_TAG;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.TRACK_ID_ATTRIBUTE;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.TRACK_ID_TAG;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.TRACK_NAME_ATTRIBUTE;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.TRACK_TAG;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.VERSION_ATTRIBUTE;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.VISIBILITY_FEATURE_NAME;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.VOXEL_DEPTH_ATTRIBUTE;
import static org.mastodon.revised.model.mamut.trackmate.TrackMateXMLKeys.WIDTH_ATTRIBUTE;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.mastodon.collection.RefCollections;
import org.mastodon.collection.RefList;
import org.mastodon.collection.RefSet;
import org.mastodon.feature.Dimension;
import org.mastodon.feature.Feature;
import org.mastodon.feature.FeatureModel;
import org.mastodon.feature.FeatureProjection;
import org.mastodon.feature.FeatureProjectionSpec;
import org.mastodon.feature.FeatureSpec;
import org.mastodon.feature.FeatureSpecsService;
import org.mastodon.feature.IntFeatureProjection;
import org.mastodon.graph.algorithm.RootFinder;
import org.mastodon.graph.algorithm.traversal.DepthFirstSearch;
import org.mastodon.graph.algorithm.traversal.GraphSearch.SearchDirection;
import org.mastodon.graph.algorithm.traversal.SearchListener;
import org.mastodon.pool.PoolObject;
import org.mastodon.project.MamutProject;
import org.mastodon.revised.bdv.overlay.util.JamaEigenvalueDecomposition;
import org.mastodon.revised.model.mamut.Link;
import org.mastodon.revised.model.mamut.Model;
import org.mastodon.revised.model.mamut.Spot;
import org.mastodon.spatial.SpatioTemporalIndex;
import mpicbg.spim.data.SpimDataException;
import mpicbg.spim.data.XmlKeys;
import mpicbg.spim.data.sequence.TimePoint;
import mpicbg.spim.data.sequence.TimePoints;
import mpicbg.spim.data.sequence.XmlIoTimePoints;
/**
* Class to export a Mastodon project to MaMuT Fiji plugin.
*
* @author Jean-Yves Tinevez
*
*/
public class MamutExporter
{
private final Model model;
private final MamutProject project;
private final Element root;
/**
* Used to retrieve equivalent radius.
*/
private final JamaEigenvalueDecomposition eig;
/**
* Used to retrieve equivalent radius.
*/
private final double[][] cov;
private final List< ExportFeatureProjection< Spot > > spotFeatureProjections;
private final List< ExportFeatureProjection< Link > > linkFeatureProjections;
private MamutExporter( final Model model, final MamutProject project )
{
this.model = model;
this.project = project;
this.root = new Element( TRACKMATE_TAG );
root.setAttribute( VERSION_ATTRIBUTE, "3.6.0" );
this.eig = new JamaEigenvalueDecomposition( 3 );
this.cov = new double[ 3 ][ 3 ];
spotFeatureProjections = getExportFeatureProjections( model.getFeatureModel(), Spot.class );
linkFeatureProjections = getExportFeatureProjections( model.getFeatureModel(), Link.class );
}
private void write( final File file ) throws IOException
{
try (FileOutputStream fos = new FileOutputStream( file ))
{
final Document document = new Document( root );
final XMLOutputter outputter = new XMLOutputter( Format.getPrettyFormat() );
outputter.output( document, fos );
}
}
private void appendModel()
{
final Element modelElement = new Element( MODEL_TAG );
modelElement.setAttribute( SPATIAL_UNITS_ATTRIBUTE, model.getSpaceUnits() );
modelElement.setAttribute( TIME_UNITS_ATTRIBUTE, model.getTimeUnits() );
final Element featureDeclarationElement = featuresDeclarationToXml();
modelElement.addContent( featureDeclarationElement );
final Element spotElement = spotCollectionToXml();
modelElement.addContent( spotElement );
final Element[] tracksElements = trackCollectionToXml();
for ( final Element element : tracksElements )
modelElement.addContent( element );
root.addContent( modelElement );
}
private void appendSettings()
{
final Element settingsElement = new Element( SETTINGS_TAG );
final Element imageDataElement = imageDataToXml();
settingsElement.addContent( imageDataElement );
final Element initialSpotFilterElement = initialSpotFilterToXml();
settingsElement.addContent( initialSpotFilterElement );
final Element spotFilterCollectionElement = new Element( SPOT_FILTER_COLLECTION_TAG );
settingsElement.addContent( spotFilterCollectionElement );
final Element trackFilterCollectionElement = new Element( TRACK_FILTER_COLLECTION_TAG );
settingsElement.addContent( trackFilterCollectionElement );
final Element analyzerCollection = analyzerCollectionToXml();
settingsElement.addContent( analyzerCollection );
root.addContent( settingsElement );
}
/**
* Try to locates a .settings file for the bdv file and import the content
* that MaMuT can recognize (setup assignments and bookmarks).
*/
private void appendGuiState()
{
final String fs = project.getDatasetXmlFile().getAbsolutePath();
final int ixml = fs.lastIndexOf( ".xml" );
final String settingsFileStr = fs.substring( 0, ixml ) + ".settings" + fs.substring( ixml );
final File settingsFile = new File( settingsFileStr );
if ( settingsFile.exists() && settingsFile.isFile() && settingsFile.canRead() )
{
final SAXBuilder sax = new SAXBuilder();
try
{
final Element guiStateElement = new Element( GUI_STATE_TAG );
final Document doc = sax.build( settingsFile );
final Element root = doc.getRootElement();
final Element setupAssignmentsElement = root.getChild( SETUP_ASSIGNMENTS_TAG ).detach();
guiStateElement.addContent( setupAssignmentsElement );
final Element bookmarksElement = root.getChild( BOOKMARKS_TAG ).detach();
guiStateElement.addContent( bookmarksElement );
this.root.addContent( guiStateElement );
}
catch ( final JDOMException | IOException e )
{
e.printStackTrace();
}
}
}
private Element analyzerCollectionToXml()
{
final Element analyzerCollectionElement = new Element( ANALYZER_COLLECTION_TAG );
final Element spotAnalyzersElement = new Element( SPOT_ANALYZERS_TAG );
analyzerCollectionElement.addContent( spotAnalyzersElement );
final Element edgeAnalyzersElement = new Element( EDGE_ANALYZERS_TAG );
final Element edgeTargetAnalyzerElement = new Element( ANALYZER_TAG );
edgeTargetAnalyzerElement.setAttribute( ANALYZER_KEY_ATTRIBUTE, EDGE_TARGET_ANALYZER_VALUE );
edgeAnalyzersElement.addContent( edgeTargetAnalyzerElement );
analyzerCollectionElement.addContent( edgeAnalyzersElement );
final Element trackAnalyzersElement = new Element( TRACK_ANALYZERS_TAG );
analyzerCollectionElement.addContent( trackAnalyzersElement );
return analyzerCollectionElement;
}
private Element initialSpotFilterToXml()
{
final Element initialSpotFilterElement = new Element( INITIAL_SPOT_FILTER_TAG );
initialSpotFilterElement.setAttribute( FILTER_FEATURE_ATTRIBUTE, QUALITY_FEATURE_NAME );
initialSpotFilterElement.setAttribute( FILTER_VALUE_ATTRIBUTE, Double.toString( 0. ) );
initialSpotFilterElement.setAttribute( FILTER_IS_ABOVE_ATTRIBUTE, Boolean.toString( true ) );
return initialSpotFilterElement;
}
private Element imageDataToXml()
{
final Collection< Attribute > attributes = new ArrayList<>();
// File path.
final File datasetXmlFile = project.getDatasetXmlFile();
attributes.add( new Attribute( FILENAME_ATTRIBUTE, datasetXmlFile.getName() ) );
String folder = datasetXmlFile.getParentFile().getAbsolutePath();
try
{
folder = datasetXmlFile.getParentFile().getCanonicalPath();
}
catch ( final IOException e )
{}
attributes.add( new Attribute( FOLDER_ATTRIBUTE, folder ) );
// Image attributes.
final Document document = getSAXParsedDocument( project.getDatasetXmlFile().getAbsolutePath() );
final List< Element > viewSetupsElements = document
.getRootElement()
.getChild( XmlKeys.SEQUENCEDESCRIPTION_TAG )
.getChild( XmlKeys.VIEWSETUPS_TAG )
.getChildren( XmlKeys.VIEWSETUP_TAG );
double pixelWidth = 1.;
double pixelHeight = 1.0;
double voxelDepth = 1.0;
int width = 1;
int height = 1;
int nslices = 1;
for ( final Element vsEl : viewSetupsElements )
{
final Element vs, uel;
if ( null != ( vs = vsEl.getChild( XmlKeys.VIEWSETUP_VOXELSIZE_TAG ) ) && null != ( uel = vs.getChild( XmlKeys.VOXELDIMENSIONS_SIZE_TAG ) ) )
{
final String val = uel.getContent( 0 ).getValue();
final double[] calibration = Arrays.stream( val.split( " " ) )
.mapToDouble( Double::parseDouble )
.toArray();
pixelWidth = calibration[ 0 ];
pixelHeight = calibration[ 1 ];
voxelDepth = calibration[ 2 ];
}
final Element sel;
if ( null != ( sel = vsEl.getChild( XmlKeys.VIEWSETUP_SIZE_TAG ) ) )
{
final String val = sel.getContent( 0 ).getValue();
final int[] sizes = Arrays.stream( val.split( " " ) )
.mapToInt( Integer::parseInt )
.toArray();
width = sizes[ 0 ];
height = sizes[ 1 ];
nslices = sizes[ 2 ];
}
}
attributes.add( new Attribute( WIDTH_ATTRIBUTE, Integer.toString( width ) ) );
attributes.add( new Attribute( HEIGHT_ATTRIBUTE, Integer.toString( height ) ) );
attributes.add( new Attribute( NSLICES_ATTRIBUTE, Integer.toString( nslices ) ) );
attributes.add( new Attribute( PIXEL_WIDTH_ATTRIBUTE, Double.toString( pixelWidth ) ) );
attributes.add( new Attribute( PIXEL_HEIGHT_ATTRIBUTE, Double.toString( pixelHeight ) ) );
attributes.add( new Attribute( VOXEL_DEPTH_ATTRIBUTE, Double.toString( voxelDepth ) ) );
final Element timePointsElement = document
.getRootElement()
.getChild( XmlKeys.SEQUENCEDESCRIPTION_TAG )
.getChild( XmlKeys.TIMEPOINTS_TAG );
int nframes = 1;
final XmlIoTimePoints xmlIoTimePoints = new XmlIoTimePoints();
try
{
final TimePoints timePoints = xmlIoTimePoints.fromXml( timePointsElement );
nframes = timePoints.size();
}
catch ( final SpimDataException e )
{
e.printStackTrace();
}
attributes.add( new Attribute( NFRAMES_ATTRIBUTE, Integer.toString( nframes ) ) );
final Element imageDataElement = new Element( IMAGE_DATA_TAG );
imageDataElement.setAttributes( attributes );
return imageDataElement;
}
private Element[] trackCollectionToXml()
{
/*
* Track collection element.
*/
final Element allTracksElement = new Element( TRACK_COLLECTION_TAG );
// Collect roots, as candidates for single tracks.
final RefList< Spot > roots = RefCollections.createRefList( model.getGraph().vertices() );
roots.addAll( RootFinder.getRoots( model.getGraph() ) );
// Sort by ID (not needed but hey).
final Comparator< Spot > labelComparator = Comparator.comparingInt( PoolObject::getInternalPoolIndex );
roots.sort( labelComparator );
/*
* We will iterate the graph, cross component by cross component, to
* serialize the tracks.
*/
final DepthFirstSearch< Spot, Link > search = new DepthFirstSearch<>( model.getGraph(), SearchDirection.UNDIRECTED );
final RefSet< Spot > toSkip = RefCollections.createRefSet( model.getGraph().vertices() );
final RefList< Spot > iteratedRoots = RefCollections.createRefList( model.getGraph().vertices() );
for ( final Spot root : roots )
{
// Skip over the roots that were path of a track already dealt with.
if ( toSkip.contains( root ) )
continue;
// Create the track element.
final Element trackElement = trackToXml( root );
final SearchListener< Spot, Link, DepthFirstSearch< Spot, Link > > searchListener = new SearchListener< Spot, Link, DepthFirstSearch< Spot, Link > >()
{
@Override
public void processVertexLate( final Spot vertex, final DepthFirstSearch< Spot, Link > search )
{
/*
* 1 root = 1 track, unless a track has several roots. Add
* the iterated vertex to the list of root to skip if
* needed.
*/
if ( vertex.incomingEdges().isEmpty() )
toSkip.add( vertex );
}
@Override
public void processVertexEarly( final Spot vertex, final DepthFirstSearch< Spot, Link > search )
{}
@Override
public void processEdge( final Link edge, final Spot from, final Spot to, final DepthFirstSearch< Spot, Link > search )
{
// Add iterated edge to the track element.
final Element edgeElement = edgeToXml( edge, from.getInternalPoolIndex(), to.getInternalPoolIndex() );
trackElement.addContent( edgeElement );
}
@Override
public void crossComponent( final Spot from, final Spot to, final DepthFirstSearch< Spot, Link > search )
{}
};
search.setTraversalListener( searchListener );
search.start( root );
// Don't serialize empty track (no edges).
if ( trackElement.getContentSize() > 0 )
{
allTracksElement.addContent( trackElement );
iteratedRoots.add( root );
}
}
/*
* Filtered track collection element.
*/
final Element filteredTracksElement = new Element( FILTERED_TRACKS_TAG );
for ( final Spot spot : iteratedRoots )
{
final Element filteredTrackID = new Element( TRACK_ID_TAG );
filteredTrackID.setAttribute( TRACK_ID_ATTRIBUTE, Integer.toString( spot.getInternalPoolIndex() ) );
filteredTracksElement.addContent( filteredTrackID );
}
return new Element[] { allTracksElement, filteredTracksElement };
}
private Element spotCollectionToXml()
{
final Element spotCollectionElement = new Element( SPOT_COLLECTION_TAG );
spotCollectionElement.setAttribute( SPOT_COLLECTION_NSPOTS_ATTRIBUTE, Integer.toString( model.getGraph().vertices().size() ) );
// Read time points from dataset xml.
List< TimePoint > tps = null;
try
{
final Document document = getSAXParsedDocument( project.getDatasetXmlFile().getAbsolutePath() );
final Element timePointsElement = document
.getRootElement()
.getChild( XmlKeys.SEQUENCEDESCRIPTION_TAG )
.getChild( XmlKeys.TIMEPOINTS_TAG );
final XmlIoTimePoints xmlIoTimePoints = new XmlIoTimePoints();
final TimePoints timePoints = xmlIoTimePoints.fromXml( timePointsElement );
tps = timePoints.getTimePointsOrdered();
}
catch ( final SpimDataException e )
{
e.printStackTrace();
}
final SpatioTemporalIndex< Spot > spots = model.getSpatioTemporalIndex();
for ( int tpIndex = 0; tpIndex < tps.size(); tpIndex++ )
{
final TimePoint tp = tps.get( tpIndex );
final Element frameSpotsElement = new Element( SPOT_FRAME_COLLECTION_TAG );
frameSpotsElement.setAttribute( FRAME_ATTRIBUTE, tp.getName() );
for ( final Spot spot : spots.getSpatialIndex( tpIndex ) )
{
final Element spotElement = spotToXml( spot );
frameSpotsElement.addContent( spotElement );
}
spotCollectionElement.addContent( frameSpotsElement );
}
return spotCollectionElement;
}
private Element edgeToXml( final Link edge, final int sourceSpotID, final int targetSpotID )
{
final Collection< Attribute > attributes = new ArrayList<>();
// Source and target ID.
attributes.add( new Attribute( EDGE_SOURCE_ATTRIBUTE, Integer.toString( sourceSpotID ) ) );
attributes.add( new Attribute( EDGE_TARGET_ATTRIBUTE, Integer.toString( targetSpotID ) ) );
// Link features.
linkFeatureProjections.forEach( p -> attributes.add( new Attribute(
p.attributeName,
Double.toString( p.projection.value( edge ) ) ) ) );
final Element edgeElement = new Element( EDGE_TAG );
edgeElement.setAttributes( attributes );
return edgeElement;
}
private Element trackToXml( final Spot root )
{
final Collection< Attribute > attributes = new ArrayList<>();
// Track name.
attributes.add( new Attribute( TRACK_NAME_ATTRIBUTE, root.getLabel() ) );
// Track ID.
attributes.add( new Attribute( TRACK_ID_ATTRIBUTE, Integer.toString( root.getInternalPoolIndex() ) ) );
// Other track features.
// TODO: when we compute and store track features, modify this.
final Element trackElement = new Element( TRACK_TAG );
trackElement.setAttributes( attributes );
return trackElement;
}
private Element spotToXml( final Spot spot )
{
final Collection< Attribute > attributes = new ArrayList<>();
// Id.
attributes.add( new Attribute( ID_FEATURE_NAME, Integer.toString( spot.getInternalPoolIndex() ) ) );
// Name.
attributes.add( new Attribute( LABEL_FEATURE_NAME, spot.getLabel() ) );
// Position.
attributes.add( new Attribute( POSITION_X_FEATURE_NAME, Double.toString( spot.getDoublePosition( 0 ) ) ) );
attributes.add( new Attribute( POSITION_Y_FEATURE_NAME, Double.toString( spot.getDoublePosition( 1 ) ) ) );
attributes.add( new Attribute( POSITION_Z_FEATURE_NAME, Double.toString( spot.getDoublePosition( 2 ) ) ) );
// Frame and time.
attributes.add( new Attribute( FRAME_FEATURE_NAME, Integer.toString( spot.getTimepoint() ) ) );
attributes.add( new Attribute( POSITION_T_FEATURE_NAME, Double.toString( spot.getTimepoint() ) ) );
// Quality.
attributes.add( new Attribute( QUALITY_FEATURE_NAME, Double.toString( -1. ) ) );
// Visibility.
attributes.add( new Attribute( VISIBILITY_FEATURE_NAME, Integer.toString( 1 ) ) );
// Radius. We have to scale it by transform norm because in MaMuT they
// are before rendering.
spot.getCovariance( cov );
eig.decomposeSymmetric( cov );
final double meanRadius = Arrays.stream( eig.getRealEigenvalues() ).map( Math::sqrt ).average().getAsDouble();
attributes.add( new Attribute( RADIUS_FEATURE_NAME, Double.toString( meanRadius ) ) );
// Spot features.
spotFeatureProjections.forEach( p -> attributes.add( new Attribute(
p.attributeName,
Double.toString( p.projection.value( spot ) ) ) ) );
final Element spotElement = new Element( SPOT_ELEMENT_TAG );
spotElement.setAttributes( attributes );
return spotElement;
}
private Element featuresDeclarationToXml()
{
final Element featuresElement = new Element( FEATURE_DECLARATION_TAG );
appendFeaturesDeclarationOfClass( Spot.class, featuresElement, SPOT_FEATURE_DECLARATION_TAG );
appendFeaturesDeclarationOfClass( Link.class, featuresElement, EDGE_FEATURE_DECLARATION_TAG );
// Create an empty declaration for track features, for now.
appendFeaturesDeclarationOfClass( Boolean.class, featuresElement, TRACK_FEATURE_DECLARATION_TAG );
return featuresElement;
}
@SuppressWarnings( { "unchecked", "rawtypes" } )
private < T > void appendFeaturesDeclarationOfClass( final Class< T > clazz, final Element featuresElement, final String classFeatureDeclarationTag )
{
final List< ExportFeatureProjection< T > > projections;
if ( clazz.equals( Spot.class ) )
projections = ( List ) spotFeatureProjections;
else if ( clazz.equals( Link.class ) )
projections = ( List ) linkFeatureProjections;
else
projections = Collections.emptyList();
final Element classFeaturesElement = new Element( classFeatureDeclarationTag );
for ( final ExportFeatureProjection< T > p : projections )
{
final String isint = ( p.projection instanceof IntFeatureProjection )
? "true"
: "false";
final Element fel = new Element( FEATURE_TAG );
fel.setAttribute( FEATURE_ATTRIBUTE, p.attributeName );
// Mastodon does not support feature name yet.
fel.setAttribute( FEATURE_NAME_ATTRIBUTE, p.featureName );
fel.setAttribute( FEATURE_SHORT_NAME_ATTRIBUTE, p.featureShortName );
final String units = p.projection.units();
fel.setAttribute( FEATURE_DIMENSION_ATTRIBUTE, unitsToDimension( units, model.getSpaceUnits(), model.getTimeUnits() ) );
fel.setAttribute( FEATURE_ISINT_ATTRIBUTE, isint );
classFeaturesElement.addContent( fel );
}
featuresElement.addContent( classFeaturesElement );
}
private static Document getSAXParsedDocument( final String fileName )
{
final SAXBuilder builder = new SAXBuilder();
Document document = null;
try
{
document = builder.build( fileName );
}
catch ( JDOMException | IOException e )
{
e.printStackTrace();
}
return document;
}
/**
* Tries to recover the TrackMate dimension from the unit string and the spatial and
* time units.
*
* @param units
* the unit string.
* @param spaceUnits
* the spatial units.
* @param timeUnits
* the time units.
* @return a dimension string that can be parsed by MaMuT.
*/
private static String unitsToDimension( final String units, final String spaceUnits, final String timeUnits )
{
if ( units.equals( Dimension.COUNTS_UNITS ) )
return "INTENSITY";
else if ( units.equals( Dimension.COUNTS_SQUARED_UNITS ) )
return "INTENSITY_SQUARED";
else if ( units.equals( Dimension.LENGTH.getUnits( spaceUnits, timeUnits ) ) )
return "LENGTH";
else if ( units.equals( Dimension.VELOCITY.getUnits( spaceUnits, timeUnits ) ) )
return "VELOCITY";
else if ( units.equals( Dimension.ANGLE.getUnits( spaceUnits, timeUnits ) ) )
return "TIME";
else if ( units.equals( Dimension.TIME.getUnits( spaceUnits, timeUnits ) ) )
return "ANGLE";
else if ( units.equals( Dimension.RATE.getUnits( spaceUnits, timeUnits ) ) )
return "RATE";
else
return "NONE";
}
/**
* Creates a map from export name to feature projection for all feature projections in {@code featureModel} matching the given {@code target} class.
*
* @param featureModel
* @param target
* @param <T>
*/
public static < T > List< ExportFeatureProjection< T > > getExportFeatureProjections( final FeatureModel featureModel, final Class< T > target )
{
final ArrayList< ExportFeatureProjection< T > > list = new ArrayList<>();
for ( final FeatureSpec< ?, ? > fspec : featureModel.getFeatureSpecs() )
{
if ( fspec.getTargetClass().equals( target ) )
{
@SuppressWarnings( "unchecked" )
final Feature< T > feature = ( Feature< T > ) featureModel.getFeature( fspec );
final String fname = fspec.getKey();
if (null == feature.projections())
continue;
for ( final FeatureProjection< T > projection : feature.projections() )
{
final String pname = projection.getKey().getSpec().getKey();
final String name = isScalarFeature( fspec )
? getProjectionExportName( fname )
: getProjectionExportName( fname, pname, projection.getKey().getSourceIndices() );
list.add( new ExportFeatureProjection<>( projection, sanitize( name ), name, name ) );
}
}
}
return list;
}
public static class ExportFeatureProjection< T >
{
public final FeatureProjection< T > projection;
public final String attributeName;
public final String featureName;
public final String featureShortName;
ExportFeatureProjection( final FeatureProjection< T > projection, final String attributeName, final String featureName, final String featureShortName )
{
this.projection = projection;
this.attributeName = attributeName;
this.featureName = featureName;
this.featureShortName = featureShortName;
}
}
/**
* Produce a set of attribute names for exported feature projections.
* This is to filter these from re-import in {@link TrackMateImporter}
*
* @param specsService
* @param numSources
* @param target
* @param <T>
* @return
*/
public static < T > Set< String > getLikelyExportedFeatureProjections( final FeatureSpecsService specsService, final int numSources, final Class< T > target )
{
final HashSet< String > names = new HashSet<>();
if (null == specsService)
return names;
final List< FeatureSpec< ?, T > > fspecs = specsService.getSpecs( target );
for ( final FeatureSpec< ?, T > fspec : fspecs )
{
final String fname = fspec.getKey();
if ( isScalarFeature( fspec ) )
{
names.add( sanitize( getProjectionExportName( fname ) ) );
continue;
}
for ( final FeatureProjectionSpec pspec : fspec.getProjectionSpecs() )
{
final String pname = pspec.getKey();
switch( fspec.getMultiplicity() )
{
case SINGLE:
names.add( sanitize( getProjectionExportName( fname, pname ) ) );
break;
case ON_SOURCES:
for ( int i = 0; i < numSources; i++ )
names.add( sanitize( getProjectionExportName( fname, pname, i ) ) );
break;
case ON_SOURCE_PAIRS:
for ( int i = 0; i < numSources; i++ )
for ( int j = 0; j < numSources; j++ )
names.add( sanitize( getProjectionExportName( fname, pname, i, j ) ) );
break;
}
}
}
return names;
}
private static boolean isScalarFeature( final FeatureSpec< ?, ? > spec )
{
return spec.getMultiplicity() == SINGLE && spec.getProjectionSpecs().size() == 1;
}
private static String sanitize( final String tag )
{
return tag.replace( ' ', '_' );
}
private static String getProjectionExportName( final String fname )
{
return fname;
}
private static String getProjectionExportName( final String fname, final String pname, final int... sourceIndices )
{
final StringBuilder sb = new StringBuilder( fname ).append( " " ).append( pname );
if ( sourceIndices != null )
{
for ( final int sourceIndex : sourceIndices )
{
sb.append( " ch" );
sb.append( sourceIndex );
}
}
return sb.toString();
}
public static final void export( final File target, final Model model, final MamutProject project ) throws IOException
{
final MamutExporter exporter = new MamutExporter( model, project );
exporter.appendModel();
exporter.appendSettings();
exporter.appendGuiState();
exporter.write( target );
}
}