-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconsensus_skeleton.cpp
More file actions
2530 lines (2005 loc) · 73.3 KB
/
Copy pathconsensus_skeleton.cpp
File metadata and controls
2530 lines (2005 loc) · 73.3 KB
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
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//consensus_skeleton.cpp
//generate consensus tree from multiple neurons
//(1) use a volume image to recode and accumulate the locations of nodes for all trees
//(2) keep one node for each small window, record its confidence value as a feature value (eswc) by the votes
//(3) final result is a minimum spanning tree from 2)
#include "consensus_skeleton.h"
#include "mst_boost_prim.h"
#include "kd-tree.h"
#include <QtGlobal>
#include <iostream>
#include "basic_4dimage.h"
#include "algorithm"
#include <string.h>
#include "sort_eswc.h"
#include <cmath>
#include <climits>
#include <numeric>
#include <algorithm>
#include <string>
#include "resample_swc.h"
#define MAX_NUM_OF_NODES_CAN_HANDLE_EFFICIENTLY 20000
using namespace std;
#ifdef _MSC_VER
#define LONG_LONG_MAX _I64_MAX
inline float roundf(float num)
{
return num > 0 ? std::floor(num + 0.5f) : std::ceil(num - 0.5f);
}
inline long lroundf(float num) { return static_cast<long>(roundf(num)); }
#endif
#define getParent(n,nt) ((nt).listNeuron.at(n).pn<0)?(1000000000):((nt).hashNeuron.value((nt).listNeuron.at(n).pn))
#define dist(a,b) sqrt(((a).x-(b).x)*((a).x-(b).x)+((a).y-(b).y)*((a).y-(b).y)+((a).z-(b).z)*((a).z-(b).z))
template <class T> T pow2(T a)
{
return a*a;
}
#ifndef MIN
#define MIN(a, b) ( ((a)<(b))? (a) : (b) )
#endif
#ifndef MAX
#define MAX(a, b) ( ((a)>(b))? (a) : (b) )
#endif
struct NeuronSize{
float x;
float y;
float z;
};
unsigned int v_min(vector<unsigned int> x)
{
sort(x.begin(), x.end());
return x[0];
}
unsigned int v_max(vector<unsigned int> x)
{
sort(x.begin(), x.end());
return x[x.size()-1];
}
int max_image_value( unsigned char * img1d, V3DLONG siz)
{
int max_v = 0;
for(int i = 0; i < siz; i++ )
{
if (int(img1d[i]) > max_v)
max_v = img1d[i];
}
return max_v;
}
double mean_image_value( unsigned char * img1d, V3DLONG siz)
{
double sum_v= 0;
int count = 0 ;
for(int i = 0; i < siz; i++ )
{
if (int(img1d[i]) > 1){
sum_v += img1d[i];
count++;
}
}
return sum_v/count;
}
double median(vector<double> x)
{
sort(x.begin(), x.end());
return x[x.size()/2];
}
bool tightRange(vector<double> x, double &low, double &high)
{// to further tighten the diversity for the input swcs
// first use median to filter out anything that is not in the range of the input [low, high]
double median_size = median(x);
cout << "median:"<<median_size<<endl;
cout << "filtering with the max range:"<< low <<"~"<<high<<endl;
low = median_size*low;
high = median_size*high;
//Not typical gaussian, so the gaussian range it is not well suited:
// then calculate the mean and the standard deviation
// low = mean - 3*std
// hight = mean + 3*std
// vector<double> valid_x;
// double sum = 0;
// for (int i = 0; i<x.size(); i++)
// {
// if ( (x[i]> low ) && (x[i] < high))
// {
// valid_x.push_back(x[i]);
// sum += x[i];
// }
// }
// //reset and return the statistical range
// low = 0;
// high = 0;
// if ( valid_x.size() >0)
// {
// double m_mean = sum/valid_x.size();
// double variance = 0 ;
// for (int i = 0; i<valid_x.size(); i++)
// {
// variance += (valid_x[i]-m_mean)*(valid_x[i]-m_mean);
// }
// variance = variance/valid_x.size();
// double std = sqrt(variance);
// cout << "mean:"<<m_mean<<endl;
// cout << "standard deviation:"<<std<<endl;
// low = m_mean - 3*std;
// high = m_mean + 3*std;
// }
// cout << "low:"<<low<<endl;
// cout << "high:"<<high<<endl;
return true;
}
double computeTotalLength(const NeuronTree & nt)
{
double Length = 0;
QList<NeuronSWC> list = nt.listNeuron;
for (int i=0;i<list.size();i++)
{
NeuronSWC curr = list.at(i);
int parent = getParent(i,nt);
if (parent==VOID) continue;
double l = dist(curr,list.at(parent));
Length += l;
}
return Length;
}
int computeNumberOfBifurcations(const NeuronTree & nt)
{
QVector<QVector<V3DLONG> > childs;
V3DLONG neuronNum = nt.listNeuron.size();
childs = QVector< QVector<V3DLONG> >(neuronNum, QVector<V3DLONG>() );
for (V3DLONG i=0;i<neuronNum;i++)
{
V3DLONG par = nt.listNeuron[i].pn;
if (par<0) continue;
childs[nt.hashNeuron.value(par)].push_back(i);
}
int N_bifs = 0;
QList<NeuronSWC> list = nt.listNeuron;
for (int i=0;i<list.size();i++)
{
if (childs[i].size()>1)
N_bifs++;
}
return N_bifs;
}
double computeFragmentation(const NeuronTree & nt)
{
double Fragmentation = 0.0;
int N_branch = 0;
QList<NeuronSWC> list = nt.listNeuron;
V3DLONG neuronNum = nt.listNeuron.size();
if (neuronNum <1)
return 0;
QVector<QVector<V3DLONG> > childs;
childs = QVector< QVector<V3DLONG> >(neuronNum, QVector<V3DLONG>() );
for (V3DLONG i=0;i<neuronNum;i++)
{
V3DLONG par = nt.listNeuron[i].pn;
if (par<0) continue;
childs[nt.hashNeuron.value(par)].push_back(i);
}
//find the root
int rootidx = 0;
for (int i=0;i<list.size();i++)
{
if (list.at(i).pn==-1){
//compute the first tree in the forest
rootidx = i;
break;
}
}
QStack<int> stack = QStack<int>();
stack.push(rootidx);
int t,tmp,fragment;
while (!stack.isEmpty())
{
t = stack.pop();
QVector<V3DLONG> child = childs[t];
for (int i=0;i<child.size();i++)
{
N_branch++;
tmp = child[i];
fragment = 0;
while (childs[tmp].size()==1)
{
int ch = childs[tmp].at(0);
fragment++;
tmp = ch;
}
Fragmentation += fragment;
//we are reaching a tip point or another branch point, computation for this branch is over
int chsz = childs[tmp].size();
if (chsz>1) //another branch
{
stack.push(tmp);
}
}
}
if (N_branch>0)
{
Fragmentation /= N_branch;
}
else
{
Fragmentation=0.0;
}
return Fragmentation;
}
#define DIST(a,b) sqrt(((a).x-(b).x)*((a).x-(b).x)+((a).y-(b).y)*((a).y-(b).y)+((a).z-(b).z)*((a).z-(b).z))
bool prune_branch(NeuronTree nt, NeuronTree & result, double prune_size)
{
V3DLONG siz = nt.listNeuron.size();
vector<V3DLONG> branches(siz,0); //number of branches on the pnt: 0-tip, 1-internal, >=2-branch
for (V3DLONG i=0;i<siz;i++)
{
if (nt.listNeuron[i].pn<0) continue;
V3DLONG pid = nt.hashNeuron.value(nt.listNeuron[i].pn);
branches[pid]++;
}
//calculate the shortest edge starting from each tip point
vector<bool> to_prune(siz, false);
for (V3DLONG i=0;i<siz;i++)
{
if (branches[i]!=0) continue;
//only consider tip points
vector<V3DLONG> segment;
double edge_length = 0;
V3DLONG cur = i;
V3DLONG pid;
do
{
NeuronSWC s = nt.listNeuron[cur];
segment.push_back(cur);
pid = nt.hashNeuron.value(s.pn);
edge_length += DIST(s, nt.listNeuron[pid]);
cur = pid;
}
while (branches[pid]==1 && pid>0);
if (pid<0)
{
printf("The input tree has only 1 root point. Please check.\n");
return false;
}
if (edge_length < prune_size)
{
for (int j=0;j<segment.size();j++)
to_prune[segment[j]] = true;
}
}
//prune branches
result.listNeuron.clear();
result.hashNeuron.clear();
for (V3DLONG i=0;i<siz;i++)
{
if (!to_prune[i])
{
NeuronSWC s = nt.listNeuron[i];
result.listNeuron.append(s);
result.hashNeuron.insert(nt.listNeuron[i].n, result.listNeuron.size()-1);
}
}
return true;
}
bool prune_all_inputs(vector<NeuronTree> & nt_list, double prune_length){
cout<<"Prune short branches ( lengh < clustering distance) to have meaninful bifurcation comparisons:"<<endl;
for(int i = 0; i < nt_list.size(); i++) {
NeuronTree result;
prune_branch(nt_list[i], result, prune_length);
result.file = nt_list[i].file;//keep the file name info
nt_list[i].copy(result);
}
return true;
}
bool sort_all_inputs(vector<NeuronTree> & nt_list, double bridge_gap){
// to avoid processing huge input swcs
vector<int > rm_ids;
for(int i = 0; i < nt_list.size(); i++) {
NeuronTree tree = nt_list[i];
if (tree.listNeuron.size()> MAX_NUM_OF_NODES_CAN_HANDLE_EFFICIENTLY )
{
cout<<"This neuron is too big to process: likely to be an outlier anyway.Otherwise, please resample it "
"to have less than MAX_NUM_OF_NODES_CAN_HANDLE_EFFICIENTLY(20000) nodes"<<endl;
rm_ids.push_back(i);
}
if ( tree.listNeuron.size() <1)
{
cout<<"This neuron is empty."<<endl;
rm_ids.push_back(i);
}
}
for (int i = rm_ids.size()-1; i>=0 ;i--){
// erase in reverse order to avid invalidating the iterator while erasing
nt_list.erase(nt_list.begin()+rm_ids[i]);
}
cout<<"Sort all input neurons:"<<endl;
for(int i = 0; i < nt_list.size(); i++){
QList<NeuronSWC> sorted;
if (!SortESWC (nt_list[i].listNeuron, sorted, VOID, bridge_gap))
{
cout <<"fail to sort neuron (idx starts at 1):" << i+1 <<endl;
}
nt_list[i].listNeuron=sorted;
}
cout<<"Done sorting."<<endl;
return true;
}
bool remove_outliers(vector<NeuronTree> & nt_list,QString SelectedNeuronsAnoFileName)
{
// use total length and # of bifurcations to remove outliers
cout<<"\nOutlier detection:"<<endl;
vector<double> nt_lens;
vector<double> nt_N_frags;
for(int i = 0; i < nt_list.size(); i++){
NeuronTree tree = nt_list[i];
double len = computeTotalLength(tree);
cout<<"len ="<< len<<endl;
nt_lens.push_back(len);
//int N_bifs = computeNumberOfBifurcations(tree);
double N_frags = computeFragmentation(tree);
cout<<"N_frags ="<< N_frags<<endl;
nt_N_frags.push_back(N_frags+0.0);
}
//criteria 1: total length
double low_len=0.25, high_len = 4;
tightRange(nt_lens, low_len, high_len);
//criteria 2: fragmentations (fragmentation:number of compartments that constitute a branch between two bifurcation points or between a bifurcation point and a terminal tip.)
double low_bi = 0.25, high_bi = 4;//many trees have smaller branches which cause small fragmentation, allow bigger fragmentations ( long branches, even though it might overtrace,
//but by allowing the long branches, we can include more candidates if the center/core branches are there.
tightRange(nt_N_frags, low_bi, high_bi);
vector<int > rm_ids;
cout <<"Remove SWCs, whose total length is > "<< high_len <<" or <" << low_len<<endl;
cout <<"Remove SWCs, whose Fragmentation is > "<< high_bi <<" or <" << low_bi<<endl;
cout <<"Total lengths:"<<endl;
for(int i=0; i < nt_list.size(); i++){
cout << nt_lens[i]<<" ";
}
cout << endl;
cout <<"Fragmentations:"<<endl;
for(int i=0; i < nt_list.size(); i++){
cout << nt_N_frags[i]<<" ";
}
cout << endl;
for(int i = 0; i < nt_list.size(); i++){
double len = nt_lens[i];
double N_frags = nt_N_frags[i];
if ( len > high_len || len < low_len )
{
cout <<"Remove neuron "<< i<<":"<< nt_list[i].file.toStdString().c_str() << " with "<< len<< " in total length"<<endl;
rm_ids.push_back(i);
}
else
if (N_frags > high_bi || N_frags < low_bi)
{
cout <<"Remove neuron "<< i<<":"<< nt_list[i].file.toStdString().c_str() << " with "<< N_frags<< "fragmentation"<<endl;
rm_ids.push_back(i);
}
}
for (int i =rm_ids.size()-1; i>=0 ;i--){
// erase in reverse order to avid invalidating the iterator while erasing
nt_list.erase(nt_list.begin()+rm_ids[i]);
}
cout<<"\n"<< nt_list.size()<< " neurons left are going to be included for consensus."<<endl;
if (nt_list.size()<1)
return false;
QFile file(SelectedNeuronsAnoFileName);
if (!file.open(QFile::WriteOnly|QFile::Truncate))
{
cout <<"Error opening the file "<<SelectedNeuronsAnoFileName.toStdString().c_str() << endl;
return false;
}
QTextStream stream (&file);
for (int i =0 ; i < nt_list.size(); i++){
stream<< "SWCFILE="<<nt_list[i].file<<"\n";
}
file.close();
cout<<" output ano file: "<<SelectedNeuronsAnoFileName.toStdString().c_str()<<endl;
return true;
}
//define an SWC as isolated, if there are only less than "count" SWCs in its "radius"-proximity, in the normalized space.
void isIsolated(vector<int>& isolated,vector<double>& nt_lens,vector<double>& nt_N_bifs, double radius, int count) {
int n = isolated.size();
vector<double> norm_lens, norm_nbifs;
norm_lens.resize(n);
norm_nbifs.resize(n);
normalizeVector(nt_lens,norm_lens);
normalizeVector(nt_N_bifs,norm_nbifs);
vector< vector<double> > dist;
dist.resize(n);
for (int i=0; i<n; i++) dist[i].resize(n);
buildDistanceMatrix(dist,norm_lens,norm_nbifs);
for (int i=0; i<n; i++) {
isolated[i] = 0;
int neighborCount = 0;
for (int j=0; j<n; j++) {
if (i!=j && dist[i][j]<radius) neighborCount++;
}
if (neighborCount < count)
isolated[i] = 1;
}
}
void normalizeVector(vector<double>& original, vector<double>& normalized) {
double minVal, maxVal;
minVal = maxVal = original[0];
for(int i=1; i<original.size(); i++) {
if (original[i] < minVal) minVal = original[i];
else if (original[i] > maxVal) maxVal = original[i];
}
for(int i=0; i<original.size(); i++) {
normalized[i] = (original[i]-minVal)/(maxVal-minVal);
}
}
void buildDistanceMatrix(vector< vector<double> >& dist, vector<double>& x, vector<double>& y) {
int n = x.size();
for (int i=0;i<n;i++) {
for (int j=i+1;j<n;j++) {
dist[i][j] = dist[j][i] = sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]));
}
}
}
struct MyBoundingBox{
float min_x;
float min_y;
float min_z;
float max_x;
float max_y;
float max_z;
};
MyBoundingBox neuron_trees_bb(vector<NeuronTree> nt_list)
{
MyBoundingBox bb ={0,0,0,0,0,0};
bb.min_x = LONG_MAX;
bb.min_y = LONG_MAX;
bb.min_z = LONG_MAX;
bb.max_x = 0;
bb.max_y = 0;
bb.max_z = 0;
for (int j = 0; j < nt_list.size(); j++){
NeuronTree nt = nt_list[j];
for (int i = 0; i < nt.listNeuron.size(); i++)
{
NeuronSWC a = nt.listNeuron.at(i);
bb.min_x = MIN(a.x - a.r,bb.min_x );
bb.max_x = MAX(a.x + a.r,bb.max_x );
bb.min_y = MIN(a.y - a.r,bb.min_y );
bb.max_y = MAX(a.y + a.r,bb.max_y );
bb.min_z = MIN(a.z - a.r,bb.min_z );
bb.max_z = MAX(a.z + a.r,bb.max_z );
}
}
return bb;
}
void non_max_suppresion( unsigned char * img1d, V3DLONG sz_x, V3DLONG sz_y,V3DLONG sz_z, double threshold_votes, Point3D offset,
vector<Point3D> &node_list, vector<unsigned int> &vote_list,unsigned int win_size)
{ // extract the local maximum voted skelenton node locations : node_list
// the corresponding votes are collected in: vote_list
V3DLONG num_nodes =0;
for (V3DLONG id_x = 0 + win_size/2; id_x < sz_x- win_size/2; id_x++)
for (V3DLONG id_y = 0 + win_size/2; id_y < sz_y- win_size/2; id_y++)
for (V3DLONG id_z = 0 + win_size/2; id_z < sz_z- win_size/2; id_z++)
{
//nn, find the local max value within window size
unsigned char max_val = 0 ;
//int pre_dis_sqr = 3 * (win_size/2) *(win_size/2)-1;
V3DLONG max_idx = 0 ;
for ( V3DLONG xx = id_x - win_size/2;xx< id_x + win_size/2;xx++)
for ( V3DLONG yy = id_y - win_size/2;yy< id_y + win_size/2;yy++)
for ( V3DLONG zz = id_z - win_size/2;zz< id_z + win_size/2;zz++)
{
V3DLONG idx = zz * (sz_x*sz_y) + yy * sz_x + xx;
//int dis_sqr = (xx-id_x)* (xx-id_x)+ (yy-id_y)* (yy-id_y)+ (yy-id_z)* (zz-id_z);
//if (dis_sqr < double(win_size*win_size)/4.0)
//{
if (img1d[idx] < threshold_votes)
{
img1d[idx] =0;
}
if (img1d[idx] > max_val){
max_val = img1d[idx] ;
max_idx = idx;
//pre_dis_sqr = dis_sqr;
}
//}
}
if ( max_val >= threshold_votes)
{// found non-zero max that passes the majority votes threshold
for ( V3DLONG xx =id_x - win_size/2;xx< id_x + win_size/2;xx++)
for ( V3DLONG yy = id_y - win_size/2;yy< id_y + win_size/2;yy++)
for ( V3DLONG zz = id_z - win_size/2;zz< id_z + win_size/2;zz++)
{
V3DLONG idx = zz * (sz_x*sz_y) + yy * sz_x + xx;
//int dis_sqr = (xx-id_x)* (xx-id_x)+ (yy-id_y)* (yy-id_y)+ (yy-id_z)* (zz-id_z);
//if (dis_sqr < double(win_size*win_size)/4.0)
//{
img1d[idx] = 0;
//}
}
img1d[max_idx] = max_val;
}
}
//collect SWC nodes from the local max points
for (V3DLONG id_x = 0 + win_size/2; id_x < sz_x- win_size/2; id_x++)
for (V3DLONG id_y = 0 + win_size/2; id_y < sz_y- win_size/2; id_y++)
for (V3DLONG id_z = 0 + win_size/2; id_z < sz_z- win_size/2; id_z++)
{
V3DLONG idx = id_z * (sz_x*sz_y) + id_y * sz_x + id_x;
if (img1d[idx] >=threshold_votes)
{
num_nodes++;
Point3D p;
p.x = id_x+offset.x;
p.y = id_y+offset.y;
p.z = id_z+offset.z;
node_list.push_back(p);
vote_list.push_back(img1d[idx]);
}
}
return;
}
QHash<V3DLONG, V3DLONG> NeuronNextPn(const NeuronTree &neurons)
{
QHash<V3DLONG, V3DLONG> neuron_id_table;
for (V3DLONG i=0;i<neurons.listNeuron.size(); i++)
neuron_id_table.insert(V3DLONG(neurons.listNeuron.at(i).n), i);
return neuron_id_table;
}
void AddToMaskImage(NeuronTree neurons,unsigned char* pImMask,V3DLONG sx,V3DLONG sy,V3DLONG sz,int dialate_radius,
int imageCount, V3DPluginCallback2 & callback)
{
NeuronSWC *p_cur = 0;
double xs = 0, ys = 0, zs = 0, xe = 0, ye = 0, ze = 0, rs = 0, re = 0;
V3DLONG pagesz = sx*sy;
V3DLONG tol_sz = pagesz*sz;
for (V3DLONG ii=0; ii<neurons.listNeuron.size(); ii++)
{
V3DLONG i,j,k;
p_cur = (NeuronSWC *)(&(neurons.listNeuron.at(ii)));
xs = p_cur->x;
ys = p_cur->y;
zs = p_cur->z;
//rs = p_cur->r;
// when radii estimation are not taken into consideration for consensus,
// ignore radii;
// here register swc nodes to its nearby 3x3 neighborhood volume in the mask image
// to be more robust/smooth
rs = dialate_radius;
double ballx0, ballx1, bally0, bally1, ballz0, ballz1, tmpf;
ballx0 = xs - rs; ballx0 = qBound(double(0), ballx0, double(sx-1));
ballx1 = xs + rs; ballx1 = qBound(double(0), ballx1, double(sx-1));
if (ballx0>ballx1) {tmpf = ballx0; ballx0 = ballx1; ballx1 = tmpf;}
bally0 = ys - rs; bally0 = qBound(double(0), bally0, double(sy-1));
bally1 = ys + rs; bally1 = qBound(double(0), bally1, double(sy-1));
if (bally0>bally1) {tmpf = bally0; bally0 = bally1; bally1 = tmpf;}
ballz0 = zs - rs; ballz0 = qBound(double(0), ballz0, double(sz-1));
ballz1 = zs + rs; ballz1 = qBound(double(0), ballz1, double(sz-1));
if (ballz0>ballz1) {tmpf = ballz0; ballz0 = ballz1; ballz1 = tmpf;}
//mark all voxels close to the swc node(s)
for (k = ballz0; k <= ballz1; k++){
for (j = bally0; j <= bally1; j++){
for (i = ballx0; i <= ballx1; i++){
V3DLONG ind = (k)*pagesz + (j)*sx + i;
ind = MIN(ind,tol_sz);
ind = MAX(ind, 0);
if (pImMask[ind]<=imageCount) {
pImMask[ind] +=1;}
}
}
}
}
}
bool generate_vote_map(vector<NeuronTree> & nt_list, int dialate_radius, unsigned char * img1d, V3DLONG sz_x, V3DLONG sz_y, V3DLONG sz_z, Point3D offset)
{
cout <<"\nGenerate vote map "<<endl;
long long tol_sz = sz_x* sz_y*sz_z;
cout << "vote_map image size(memory) = " << tol_sz<<": " <<sz_x<<"x "<<sz_y<<" x"<<sz_z<< endl;
V3DLONG pagesz = sz_x*sz_y;
for (int j =0; j < nt_list.size(); j++){
NeuronTree nt = nt_list[j];
for (int i =0; i < nt.listNeuron.size(); i++)
{
NeuronSWC node = nt.listNeuron.at(i);
double xs=node.x-offset.x;
double ys=node.y-offset.y;
double zs=node.z-offset.z;
double rs = dialate_radius; //expansion
double ballx0, ballx1, bally0, bally1, ballz0, ballz1, tmpf;
ballx0 = xs - rs; ballx0 = qBound(double(0), ballx0, double(sz_x-1));
ballx1 = xs + rs; ballx1 = qBound(double(0), ballx1, double(sz_x-1));
if (ballx0>ballx1) {tmpf = ballx0; ballx0 = ballx1; ballx1 = tmpf;}
bally0 = ys - rs; bally0 = qBound(double(0), bally0, double(sz_y-1));
bally1 = ys + rs; bally1 = qBound(double(0), bally1, double(sz_y-1));
if (bally0>bally1) {tmpf = bally0; bally0 = bally1; bally1 = tmpf;}
ballz0 = zs - rs; ballz0 = qBound(double(0), ballz0, double(sz_z-1));
ballz1 = zs + rs; ballz1 = qBound(double(0), ballz1, double(sz_z-1));
if (ballz0>ballz1) {tmpf = ballz0; ballz0 = ballz1; ballz1 = tmpf;}
//mark all voxels close to the swc node(s)
for (int kk = ballz0; kk <= ballz1; kk++){
for (int jj = bally0; jj <= bally1; jj++){
for (int ii = ballx0; ii <= ballx1; ii++){
V3DLONG ind = (kk)*pagesz + (jj)*sz_x + ii;
ind = MIN(ind,tol_sz);
ind = MAX(ind, 0);
if (img1d[ind]<=j) {
img1d[ind]++;
}
}
}
}
// V3DLONG id_x = (node.x-offset.x) +0.5; //round up
// V3DLONG id_y = (node.y-offset.y) +0.5;
// V3DLONG id_z = (node.z-offset.z) +0.5;
// V3DLONG idx = id_z * (sz_x*sz_y) + id_y * sz_x + id_x;
// if (idx <tol_sz && VOTED[idx] == 0 ){
// img1d[idx] ++ ;
// VOTED[idx] = 1;
// }
}
}
//for debug only
// Image4DSimple *image = new Image4DSimple();
// image->setData(img1d, sz_x, sz_y, sz_z, 1, V3D_UINT8);
// callback.saveImage(image, "./vote_map.v3draw");
return true;
}
void label_image(unsigned char * img1d, V3DLONG xs, V3DLONG ys, V3DLONG zs, double rs,
unsigned char * VOTED, V3DLONG sx, V3DLONG sy,V3DLONG sz)
{
double ballx0, ballx1, bally0, bally1, ballz0, ballz1, tmpf;
long long pagesz = sx*sy;
ballx0 = xs - rs; ballx0 = qBound(double(0), ballx0, double(sx-1));
ballx1 = xs + rs; ballx1 = qBound(double(0), ballx1, double(sx-1));
if (ballx0>ballx1) {tmpf = ballx0; ballx0 = ballx1; ballx1 = tmpf;}
bally0 = ys - rs; bally0 = qBound(double(0), bally0, double(sy-1));
bally1 = ys + rs; bally1 = qBound(double(0), bally1, double(sy-1));
if (bally0>bally1) {tmpf = bally0; bally0 = bally1; bally1 = tmpf;}
ballz0 = zs - rs; ballz0 = qBound(double(0), ballz0, double(sz-1));
ballz1 = zs + rs; ballz1 = qBound(double(0), ballz1, double(sz-1));
if (ballz0>ballz1) {tmpf = ballz0; ballz0 = ballz1; ballz1 = tmpf;}
//mark all voxels close to the swc node(s)
for (V3DLONG k = ballz0; k <= ballz1; k++){
for (V3DLONG j = bally0; j <= bally1; j++){
for (V3DLONG i = ballx0; i <= ballx1; i++){
long long ind = (k)*pagesz + (j)*sx + i;
if (VOTED[ind] == 0 /* and distance < rs*/) {
img1d[ind]++;
VOTED[ind] = 1;}
}
}
}
}
bool generate_vote_map_resample(vector<NeuronTree> & nt_list, int dialate_radius, unsigned char * img1d, V3DLONG sz_x, V3DLONG sz_y, V3DLONG sz_z, Point3D offset)
{
cout <<"\nGenerate vote map with resampling "<<endl;
long long tol_sz = sz_x* sz_y*sz_z;
cout << "vote_map image size(memory) = " << tol_sz<<": " <<sz_x<<"x "<<sz_y<<" x"<<sz_z<< endl;
// from leaf nodes to roots, resample between nodes if necessary
unsigned char * VOTED = new unsigned char[tol_sz];
for (V3DLONG n_id =0;n_id <nt_list.size();n_id++){
NeuronTree neurons = nt_list[n_id];
NeuronSWC *p_cur = 0;
//create a LUT
QHash<V3DLONG, V3DLONG> neuron_id_table = NeuronNextPn(neurons);
//compute mask
double xs = 0, ys = 0, zs = 0, xe = 0, ye = 0, ze = 0, rs = 0, re = 0;
for(long long i = 0; i < tol_sz; i++) VOTED[i] = 0;
for (V3DLONG ii=0; ii<neurons.listNeuron.size(); ii++)
{
V3DLONG i,j,k;
p_cur = (NeuronSWC *)(&(neurons.listNeuron.at(ii)));
xs = p_cur->x - offset.x;
ys = p_cur->y - offset.y;
zs = p_cur->z - offset.z;
rs = dialate_radius;
label_image(img1d, xs, ys, zs, rs, VOTED, sz_x, sz_y, sz_z);
//find previous node
if (p_cur->pn < 0)
continue;//root node skip the following
//get the parent info
const NeuronSWC & pp = neurons.listNeuron.at(neuron_id_table.value(p_cur->pn));
xe = pp.x- offset.x;
ye = pp.y- offset.y;
ze = pp.z- offset.z;
re = pp.r;
//judge if two points overlap, if yes, then do nothing as the sphere has already been drawn
if (xe==xs && ye==ys && ze==zs)
{
continue;
}
// interpolate along the line
double l =sqrt((xe-xs)*(xe-xs)+(ye-ys)*(ye-ys)+(ze-zs)*(ze-zs));
double dx = (xe - xs);
double dy = (ye - ys);
double dz = (ze - zs);
double x = xs;
double y = ys;
double z = zs;
int steps = lroundf(l);
steps = (steps < fabs(dx))? fabs(dx):steps;
steps = (steps < fabs(dy))? fabs(dy):steps;
steps = (steps < fabs(dz))? fabs(dz):steps;
if (steps<1)
steps =1;
double xIncrement = double(dx) / (steps*2);
double yIncrement = double(dy) / (steps*2);
double zIncrement = double(dz) / (steps*2);
for (int i = 0; i <= steps; i++)
{
x += xIncrement;
y += yIncrement;
z += zIncrement;
label_image(img1d, x, y, z, rs, VOTED, sz_x, sz_y, sz_z);
}
}
}
return true;
}
bool vote_map(vector<NeuronTree> & nt_list, int dialate_radius, QString outfileName,V3DPluginCallback2 & callback){
//initialize the image volume to record/accumulate the location votes from neurons
MyBoundingBox bbUnion = neuron_trees_bb(nt_list);
V3DLONG sz_x,sz_y,sz_z;
//for swcs generated from vaa3d, all meta offset are disgarded, so the swc coordinates are in model coordinates
//this will matches with the original image ( on the upper left corner)
sz_x = bbUnion.max_x;
sz_y = bbUnion.max_y;
sz_z = bbUnion.max_z;
V3DLONG tol_sz = sz_x * sz_y * sz_z;
cout << "image size = " << tol_sz<<": " <<sz_x<<" x "<<sz_y<<" x "<<sz_z<< endl;
unsigned char* pImMask = 0;
pImMask = new unsigned char [tol_sz];
memset(pImMask,0,tol_sz*sizeof(unsigned char));
for (int j = 0; j < nt_list.size(); j++){
NeuronTree nt = nt_list[j];
AddToMaskImage(nt, pImMask, sz_x, sz_y, sz_z,dialate_radius,j,callback);
}
if ( outfileName.size() >0)
{
Image4DSimple *image = new Image4DSimple();
for (int i = 0 ; i< tol_sz;i++)
{
pImMask[i]= pImMask[i]*1.0/nt_list.size() *255;
}
image->setData(pImMask, sz_x, sz_y, sz_z, 1, V3D_UINT8);
callback.saveImage(image, &(outfileName.toStdString()[0]));
}
return true;
}
bool soma_sort(double search_distance_th, QList<NeuronSWC> consensus_nt_list, double soma_x, double soma_y, double soma_z, QList<NeuronSWC> &out_sorted_consensus_nt_list, double bridge_size)
{
cout<<"\nsorting:"<<endl;
NeuronTree consensus_nt;
QList <NeuronSWC> listNeuron;
QHash <int, int> hashNeuron;
listNeuron.clear();
hashNeuron.clear();
//set node
NeuronSWC S;
for (V3DLONG i=0;i<consensus_nt_list.size();i++)
{
NeuronSWC curr = consensus_nt_list.at(i);
S.n = curr.n;
S.type = curr.type;
S.x = curr.x;
S.y = curr.y;
S.z = curr.z;
S.r = curr.r;
S.pn = curr.pn;
S.seg_id = curr.seg_id;