-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrack_load_ori.py
executable file
·1508 lines (999 loc) · 50.7 KB
/
track_load_ori.py
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
"""
Version: 1.5
Summary: Analyze and visualize tracked traces
Author: suxing liu
Author-email: [email protected]
USAGE:
python3 track_load_ori.py -p ~/Ptvpy_test/ -f trace_result.csv -v True
argument:
("-p", "--path", required = True, help="path to trace file")
("-v", "--visualize", required = False, default = False, type = bool, help = "Visualize result or not")
default file format: *.csv
"""
# Import python libraries
import numpy as np
from numpy import mean
from numpy import arctan2, sqrt
from numpy import matrix, average
import glob
import fnmatch
import os, os.path
import math
import sys
#import shutil
import matplotlib.pyplot as plt
import argparse
from openpyxl import load_workbook
from openpyxl import Workbook
from scipy.spatial import distance
import scipy.linalg
from mayavi import mlab
import imagesize
import progressbar
from time import sleep
import itertools
#import warnings
#warnings.filterwarnings("ignore", category=FutureWarning)
#warnings.filterwarnings("ignore")
from tabulate import tabulate
import pandas as pd
import moviepy.editor as mpy
'''
from skimage.morphology import skeletonize
import sknw
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D
from skimage.morphology import skeletonize_3d
from network_3d import skel2graph, plot_graph
from networkx import nx
import dask
import dask.array as da
'''
def mkdir(path):
"""Create result folder"""
# remove space at the beginning
path=path.strip()
# remove slash at the end
path=path.rstrip("\\")
# path exist? # True # False
isExists=os.path.exists(path)
# process
if not isExists:
# construct the path and folder
#print path + ' folder constructed!'
# make dir
os.makedirs(path)
return True
else:
#shutil.rmtree(dirpath)
# if exists, return
#print path+' path exists!'
return False
#colormap mapping
def get_cmap(n, name = 'BrBG'):
"""get the color mapping"""
#viridis, BrBG, hsv, copper
#Returns a function that maps each index in 0, 1, ..., n-1 to a distinct
#RGB color; the keyword argument name must be a standard mpl colormap name
return plt.cm.get_cmap(name,n+1)
# compute the path length along the trace
def pathlength(x,y,z):
n = len(x)
lv = [sqrt((x[i]-x[i-1])**2 + (y[i]-y[i-1])**2 + (z[i]-z[i-1])**2) for i in range(n)]
return sum(lv)
# compute distance between consective point sets
def points_seg_length(coords):
d = np.diff(coords, axis=0)
segdists = np.sqrt((d ** 2).sum( axis = 1))
# calculate length of line
#l = np.sqrt( np.diff(X)**2 + np.diff(Y)**2 + np.diff(Z)**2 )
return sum(segdists)
#compute distance between two point sets in a line
def line_length_2pt(coords):
start = coords[0]
end = coords[len(coords)-1]
dst = distance.euclidean(start, end)
#dist = numpy.linalg.norm(a-b)
return dst
# compute angle between two 3D points
def points_angle(x, y, z, line_length):
theta_offest = np.zeros(4)
r_offest = np.zeros(4)
#calculate angles
for offest in range(0,4):
interval = int(((offest+1)*0.25)*line_length)
if interval >= len(x):
interval = len(x)-1
cx = x[interval] - x[0]
cy = y[interval] - y[0]
cz = z[interval] - z[0]
(r,theta,phi) = asSpherical(cx, cy, cz)
if theta > 90:
theta = 180 -theta
theta_offest[offest] = theta
r_offest[offest] = r
return r_offest[2], theta_offest[2], phi
#coordinates transformation from cartesian coords to sphere coord system
def cart2sph(x, y, z):
hxy = np.hypot(x, y)
r = np.hypot(hxy, z)
elevation = np.arctan2(z, hxy)*180/math.pi
azimuth = np.arctan2(y, x)*180/math.pi
return r[2], azimuth[2], elevation[2]
'''
if azimuth > 90:
angle = 180 - azimuth
elif azimuth < 0:
angle = 90 + azimuth
else:
angle = azimuth
'''
#coordinates transformation from cartesian coords to sphere coord system
def appendSpherical_np(xyz):
ptsnew = np.hstack((xyz, np.zeros(xyz.shape)))
xy = xyz[:,0]**2 + xyz[:,1]**2
ptsnew[:,3] = np.sqrt(xy + xyz[:,2]**2)
ptsnew[:,4] = np.arctan2(np.sqrt(xy), xyz[:,2]) # for elevation angle defined from Z-axis down
#ptsnew[:,4] = np.arctan2(xyz[:,2], np.sqrt(xy)) # for elevation angle defined from XY-plane up
ptsnew[:,5] = np.arctan2(xyz[:,1], xyz[:,0])
return ptsnew[:,3],ptsnew[:,4],ptsnew[:,5]
# remove otliers
def reject_outliers(data, m = 2.):
d = np.abs(data - np.median(data))
mdev = np.median(d)
s = d / (mdev if mdev else 1.)
return data[s < m]
# visualize the traces and return their properities
def trace_visualize(trace_array, array_index_rec, fit_linepts_rec, index_pair_rec, connect_pts_rec):
# properities initialization for traits computation
index_rec = []
X_rec = []
Y_rec = []
Z_rec = []
connect_label_rec = []
index_label_rec = []
length_rec = []
angle_rec = []
diameter_rec = []
projection_radius_rec = []
color_rec = []
#image_chunk = np.zeros((416, 414, 282))
#color = np.arange(0, 1, 1/n_trace).tolist()
index_pair_rec_arr = np.asarray(index_pair_rec)
index_pair_rec_unique = np.unique(index_pair_rec_arr)
#print("index_pair_rec_unique {}\n".format(index_pair_rec_unique))
#print("array_index_rec {}\n".format(array_index_rec))
#array_index_rec_part = np.delete(array_index_rec, index_pair_rec_unique, None)
#print("array_index_rec_part {}\n".format(array_index_rec_part))
#print("len(array_index_rec) {}, len(index_pair_rec_arr) {}, len(connect_pts_rec) {}\n".format(len(array_index_rec),len(index_pair_rec_arr),len(connect_pts_rec)))
cmap = get_cmap(len(array_index_rec))
for idx, index_value in enumerate(array_index_rec):
color_rgb = cmap(idx)[:len(cmap(idx))-1]
if index_value in index_pair_rec_unique:
#if(len(list(filter (lambda x : x == index_value, index_pair_rec_unique))) > 0):
index_loc = np.where(index_pair_rec_arr[:,0] == index_value)
index_loc_list = [x for xs in index_loc for x in xs]
for idx_pair_loc in index_loc_list:
#print("current idx {0}: pair_value ({1},{2})".format(idx, index_value, index_pair_rec_arr[idx_pair_loc, 1]))
coords_arr = np.asarray(connect_pts_rec[idx_pair_loc])
x = coords_arr[:,0]
y = coords_arr[:,1]
z = coords_arr[:,2]
radius_mean = np.mean(trace_array[np.where(trace_array[:,0] == index_pair_rec_arr[idx_pair_loc, 0])][:,4])
#compute line path length
line_length = points_seg_length(coords_arr)
(r, azimuth, elevation) = cart2sph(x, y, z)
X_rec.append(x)
Y_rec.append(y)
Z_rec.append(z)
index_label_rec.append(index_pair_rec_arr[idx_pair_loc, 0])
connect_label_rec.append('1')
index_rec.append(idx)
length_rec.append(line_length)
angle_rec.append(azimuth)
diameter_rec.append(radius_mean)
projection_radius_rec.append(r)
color_rec.append(color_rgb)
else:
#print("current idx {0}: index value {1}".format(idx, index_value))
X = trace_array[np.where(trace_array[:,0] == index_value)][:,1]/X_scale
Y = trace_array[np.where(trace_array[:,0] == index_value)][:,2]/Y_scale
Z = trace_array[np.where(trace_array[:,0] == index_value)][:,3]/Z_scale
radius_mean = np.mean(trace_array[np.where(trace_array[:,0] == index_value)][:,4])
trace_radius = trace_array[np.where(trace_array[:,0] == index_value)][:,4]
scalars = trace_array[np.where(trace_array[:,0] == index_value)][:,4]
#compute line path length
line_length = points_seg_length(np.stack(( X, Y, Z ), axis = 1))
(r, azimuth, elevation) = cart2sph(X, Y, Z)
X_rec.append(X)
Y_rec.append(Y)
Z_rec.append(Z)
index_label_rec.append(index_value)
connect_label_rec.append('0')
index_rec.append(idx)
length_rec.append(line_length)
angle_rec.append(azimuth)
diameter_rec.append(radius_mean)
projection_radius_rec.append(r)
color_rec.append(color_rgb)
#import random
#color = list(random.sample(range(0, 1), len(array_index_rec)))
if args["visualize"]:
print("Visualizing tracked traces...\n")
###########################################################################################################3
#cmap = get_cmap(len(X_rec))
fig_trace = mlab.figure('Root_structure', bgcolor = (1,1,1), fgcolor = (0.5, 0.5, 0.5), size = (720,1080))
for idx, (x, y, z, diameter_rec_value, connect_label_rec_value, index_label_rec_value, color_rec_value) in enumerate(zip(X_rec, Y_rec, Z_rec, diameter_rec, connect_label_rec, index_label_rec, color_rec)):
#color_rgb = cmap(idx)[:len(cmap(idx))-1]
#pts = mlab.points3d(x, y, z, color = color_rgb, mode = 'point')
#pts.actor.property.set(point_size = 5.5)
if (int(connect_label_rec_value) > 0):
pts = mlab.plot3d(x, y, z, color = color_rec_value, opacity = 0.3, representation = 'wireframe', transparent = True, tube_radius = tube_scale*diameter_rec_value)
#pts = mlab.points3d(x, y, z, color = color_rec_value, mode = 'point')
#pts.actor.property.set(point_size = 5.5)
else:
pts = mlab.plot3d(x, y, z, color = color_rec_value, opacity = 0.3, representation = 'surface', transparent = True, tube_radius = tube_scale*diameter_rec_value)
#pts = mlab.text3d(x[0], y[0], z[0], str(index_label_rec_value), scale = (4, 4, 4), color = (1, 0.0, 0.0))
#snapshot = (save_path_result + directory_name + '.png')
#mlab.savefig(snapshot, sizesize = (720,1080))
#obj_file = (save_path_result + 'model.obj')
#mlab.savefig(obj_file)
mlab.show()
############################################################################################################
#############################################################################################################
#animation display
#fig_trace_animation = mlab.figure(bgcolor = (1,1,1), fgcolor = (0.5, 0.5, 0.5), size = (1920,1080))
fig_trace_animation = mlab.figure('Root_structure', bgcolor = (1,1,1), fgcolor = (0.5, 0.5, 0.5), size = (720,1080))
# duration of the animation in seconds (it will loop)
duration = len(X_rec)
def make_frame(t):
idx_t = int(t)
#mlab.clf() # clear the figure (to reset the colors)
#pts = mlab.points3d(X_rec[idx_t], Y_rec[idx_t], Z_rec[idx_t], color = cmap(idx_t)[:len(cmap(idx_t))-1], mode = 'point')
#pts.actor.property.set(point_size = 2.5)
#mlab.clf() # clear the figure (to reset the colors)
#pts = mlab.points3d(X_rec[idx_t], Y_rec[idx_t], Z_rec[idx_t], color = color_rec[idx_t], mode = 'point')
#pts.actor.property.set(point_size = 2.5)
pts = mlab.plot3d(X_rec[idx_t], Y_rec[idx_t], Z_rec[idx_t], color = color_rec[idx_t], opacity = 0.1, representation = 'surface', transparent = True, tube_radius = tube_scale*diameter_rec[idx_t])
#pts = mlab.plot3d(line_x, line_y, line_z, color = color_rgb, opacity = 0.3, representation = 'surface', transparent = True, tube_radius = 1*radius_mean_rec[idx])
pts = mlab.text3d(X_rec[idx_t][len(X_rec[idx_t])-1], Y_rec[idx_t][len(X_rec[idx_t])-1], Z_rec[idx_t][len(X_rec[idx_t])-1], str(idx_t+1), scale = (text_size, text_size, text_size), color = (1, 0.0, 0.0))
mlab.view(camera_azimuth, camera_elevation, camera_distance, camera_focalpoint)
print(mlab.view())
f = mlab.gcf()
f.scene._lift()
return mlab.screenshot(antialiased = True)
animation = mpy.VideoClip(make_frame, duration = duration)
animation.write_gif((save_path_result + directory_name + '.gif'), fps = 5)
#animation.write_videofile((save_path_result + 'structure.mp4'), fps = 5)
#show model
mlab.show()
####################################################################Pipeline Visualiztion
'''
N = len(X)
# We create a list of positions and connections, each describing a line.
# We will collapse them in one array before plotting.
x = list()
y = list()
z = list()
s = list()
connections = list()
# The index of the current point in the total amount of points
index = 0
# Create each line one after the other in a loop
for i in range(N):
x.append(X[i])
y.append(Y[i])
z.append(Z[i])
s.append(scalars[idx])
# This is the tricky part: in a line, each point is connected
# to the one following it. We have to express this with the indices
# of the final set of points once all lines have been combined
# together, this is why we need to keep track of the total number of
# points already created (index)
connections.append(np.vstack(
[np.arange(index, index + N - 1.5),
np.arange(index + 1, index + N - .5)]
).T)
index += N
# Now collapse all positions, scalars and connections in big arrays
x = np.hstack(x)
y = np.hstack(y)
z = np.hstack(z)
s = np.hstack(s)
connections = np.vstack(connections)
# Create the points
src = mlab.pipeline.scalar_scatter(x, y, z, s)
# Connect them
src.mlab_source.dataset.lines = connections
src.update()
# The stripper filter cleans up connected lines
#lines = mlab.pipeline.stripper(src)
#lines = mlab.pipeline.tube(src, tube_radius=0.005, tube_sides=6)
# Finally, display the set of lines
mlab.pipeline.surface(src, colormap = 'Accent', line_width = 3, opacity =.4)
'''
#############################################################################
#show model
#mlab.show()
return index_rec, length_rec, angle_rec, diameter_rec, projection_radius_rec, index_label_rec, X_rec, Y_rec, Z_rec
# visualize the traces and return their properities
def trace_visualize_simple(trace_array, array_index_rec, fit_linepts_rec, index_pair_rec, connect_pts_rec):
# properities initialization
index_rec = []
length_rec = []
angle_rec = []
diameter_rec = []
projection_radius_rec = []
index_label_rec = []
X_rec = []
Y_rec = []
Z_rec = []
color_rec = []
cmap = get_cmap(len(array_index_rec))
#color = np.arange(0, 1, 1/n_trace).tolist()
# collect all the tracked traces and their properties
for idx, index_value in enumerate(array_index_rec):
#t = idx
#print(idx, index_value)
color_rgb = cmap(idx)[:len(cmap(idx))-1]
X = trace_array[np.where(trace_array[:,0] == index_value)][:,1]/X_scale
Y = trace_array[np.where(trace_array[:,0] == index_value)][:,2]/Y_scale
Z = trace_array[np.where(trace_array[:,0] == index_value)][:,3]/Z_scale
radius_mean = np.mean(trace_array[np.where(trace_array[:,0] == index_value)][:,4])
trace_radius = trace_array[np.where(trace_array[:,0] == index_value)][:,4]
scalars = trace_array[np.where(trace_array[:,0] == index_value)][:,4]
####################################################################
#recompute the connected trace properities
coords = np.stack(( X, Y, Z ), axis = 1)
#compute line angle
line_length = points_seg_length(coords)
(r, azimuth, elevation) = cart2sph(X, Y, Z)
'''
if azimuth > 90:
angle = 180 - azimuth
elif azimuth < 0:
angle = 90 + azimuth
else:
angle = azimuth
'''
#print("Trace {0} properities:".format(idx))
#print("Number of points:{}, Length:{:.2f}, Angle:{:.2f} \n".format(len(X), line_length, angle))
# record all parameters
X_rec.append(X)
Y_rec.append(Y)
Z_rec.append(Z)
index_label_rec.append(index_value)
index_rec.append(idx)
length_rec.append(line_length)
angle_rec.append(azimuth)
diameter_rec.append(radius_mean)
projection_radius_rec.append(r)
color_rec.append(color_rgb)
#index_rec, length_rec, angle_rec, diameter_rec, projection_radius_rec, color_rec, index_label_rec, X_rec, Y_rec, Z_rec
##################################################visualize structure
if args["visualize"]:
print("Visualizing tracked traces...")
#cmap = get_cmap(len(X_rec))
fig_myv = mlab.figure(bgcolor = (1,1,1), fgcolor = (0.5, 0.5, 0.5), size = (600,400))
for idx, (x, y, z, diameter_rec_value, index_label_rec_value, color_rec_value) in enumerate(zip(X_rec, Y_rec, Z_rec, diameter_rec, index_label_rec, color_rec)):
#color_rgb = cmap(idx)[:len(cmap(idx))-1]
pts = mlab.points3d(x, y, z, color = color_rec_value, mode = 'point')
pts.actor.property.set(point_size = 5.5)
pts = mlab.plot3d(x, y, z, color = color_rec_value, opacity = 0.3, representation = 'surface', transparent = True, tube_radius = tube_scale*diameter_rec_value)
pts = mlab.text3d(x[0], y[0], z[0], str(index_label_rec_value), scale = (4, 4, 4), color = (1, 0.0, 0.0))
mlab.show()
#########################################################################################
'''
#animation display
#fig_myv = mlab.figure(bgcolor = (1,1,1), fgcolor = (0.5, 0.5, 0.5), size = (1920,1080))
fig_myv = mlab.figure(bgcolor = (1,1,1), fgcolor = (0.5, 0.5, 0.5), size = (1280,720))
cmap = get_cmap(len(X_rec))
mlab.orientation_axes(True)
# duration of the animation in seconds (it will loop)
duration = len(array_index_rec)
def make_frame(t):
idx_t = int(t)
#mlab.clf() # clear the figure (to reset the colors)
pts = mlab.points3d(X_rec[idx_t], Y_rec[idx_t], Z_rec[idx_t], color = cmap(idx_t)[:len(cmap(idx_t))-1], mode = 'point')
pts.actor.property.set(point_size = 2.5)
pts = mlab.plot3d(X_rec[idx_t], Y_rec[idx_t], Z_rec[idx_t], color = cmap(idx_t)[:len(cmap(idx_t))-1], opacity = 0.1, representation = 'surface', transparent = True, tube_radius = tube_scale*diameter_rec[idx_t])
#pts = mlab.plot3d(line_x, line_y, line_z, color = color_rgb, opacity = 0.3, representation = 'surface', transparent = True, tube_radius = 1*radius_mean_rec[idx])
pts = mlab.text3d(X_rec[idx_t][len(X_rec[idx_t])-1], Y_rec[idx_t][len(X_rec[idx_t])-1], Z_rec[idx_t][len(X_rec[idx_t])-1], str(idx_t+1), scale = (text_size, text_size, text_size), color = (1, 0.0, 0.0))
mlab.view(camera_azimuth, camera_elevation, camera_distance, camera_focalpoint)
#print(mlab.view())
f = mlab.gcf()
f.scene._lift()
return mlab.screenshot(antialiased=True)
animation = mpy.VideoClip(make_frame, duration = duration)
animation.write_gif((save_path_result + 'structure.gif'), fps = 5)
#animation.write_videofile((save_path_result + 'structure.mp4'), fps = 5)
#show model
mlab.show()
'''
return index_rec, length_rec, angle_rec, diameter_rec, projection_radius_rec, index_label_rec, X_rec, Y_rec, Z_rec
# SVD fiting lines to 3D points
def line_fiting_3D(data):
# Calculate the mean of the points, i.e. the 'center' of the cloud
datamean = data.mean(axis = 0)
x_range = data[:,0].max() - data[:,0].min()
y_range = data[:,1].max() - data[:,1].min()
z_range = data[:,2].max() - data[:,2].min()
data_range =(x_range, y_range, z_range)
data_range_mean = sum(data_range) / len(data_range)
# Do an SVD on the mean-centered data.
uu, dd, vv = np.linalg.svd(data - datamean)
# Now vv[0] contains the first principal component, i.e. the direction
# vector of the 'best fit' line in the least squares sense.
# Now generate some points along this best fit line, for plotting.
# use -7, 7 since the spread of the data is roughly 14
# and we want it to have mean 0 (like the points we did
# the svd on). Also, it's a straight line, so we only need 2 points.
linepts = vv[0] * np.mgrid[-1*data_range_mean:data_range_mean:2j][:, np.newaxis]
# shift by the mean to get the line in the right place
linepts += datamean
return linepts
# compute trace properities
def trace_compute(trace_array, trace_index):
#import scipy.optimize as optimize
print("Processing tracked trace properities...")
#initialize parameters
index_rec = []
length_euclidean_rec = []
angle_rec = []
diameter_rec = []
projection_radius_rec = []
fit_linepts_rec = []
index_label_rec = []
X_fit = []
Y_fit = []
Z_fit = []
X_rec = []
Y_rec = []
Z_rec = []
p = np.array([0, 0, 0])
q = np.array([0, 0, 1])
r = np.array([0, 1, 1])
#progress bar display
bar = progressbar.ProgressBar(maxval = len(trace_index))
bar.start()
#scan all traces
for idx, index_value in enumerate(trace_index):
#print(idx, index_value)
bar.update(idx+1)
sleep(0.1)
X = trace_array[np.where(trace_array[:,0] == index_value)][:,1]/X_scale
Y = trace_array[np.where(trace_array[:,0] == index_value)][:,2]/Y_scale
Z = trace_array[np.where(trace_array[:,0] == index_value)][:,3]/Z_scale
#traits measurement
##################################################################
radius_mean = np.mean(trace_array[np.where(trace_array[:,0] == index_value)][:,4])
scalars = trace_array[np.where(trace_array[:,0] == index_value)][:,4]
#compute line length
coords = np.stack(( X, Y, Z ), axis = 1)
#print(coords.shape)
'''
#global curve interpolation
degree = 1 # cubic curve
curve = fitting.interpolate_curve(coords.tolist(), degree)
#curve = fitting.approximate_curve(coords.tolist(), degree)
evalpts = np.array(curve.evalpts)
x_curve = evalpts[:, 0]
y_curve = evalpts[:, 1]
z_curve = evalpts[:, 2]
'''
# fitting curve
#(xLinespace, yLinespace, zLinespace) = cubic_spline_interpolate(X, Y, Z)
#fit_linepts = np.stack(( xLinespace, yLinespace, zLinespace ), axis = 1)
# fitting straight line
fit_linepts = line_fiting_3D(coords)
xLinespace = np.array((fit_linepts[0][0], fit_linepts[1][0]))
yLinespace = np.array((fit_linepts[0][1], fit_linepts[1][1]))
zLinespace = np.array((fit_linepts[0][2], fit_linepts[1][2]))
#print(fit_linepts[0], fit_linepts[1])
#line_length = pathlength(X, Y, Z)
#compute line angle
line_length = points_seg_length(coords)
#compute line length bewteen start and end points
line_length_euclidean = line_length_2pt(coords)
#print("line_length {0} properities:".format(line_length))
#print("line_length_2pt {0} properities:".format(line_length_euclidean))
(r, azimuth, elevation) = cart2sph(X, Y, Z)
'''
if azimuth > 90:
angle = 180 - azimuth
elif azimuth < 0:
angle = 90 + azimuth
else:
angle = azimuth
'''
#print("Trace {0} properities:".format(index_value))
#print("Number of points:{}, Length:{:.2f}, Angle:{:.2f} \n".format(len(X), line_length, angle))
#print(popt)
#print("Angle:{0} {1} {2}\n".format(r, theta, phi))
# record all parameters
index_rec.append(idx)
length_euclidean_rec.append(line_length_euclidean)
angle_rec.append(azimuth)
#diameter_rec.append(radius_mean)
#projection_radius_rec.append(r)
fit_linepts_rec.append(fit_linepts)
index_label_rec.append(index_value)
X_fit.append(xLinespace)
Y_fit.append(yLinespace)
Z_fit.append(zLinespace)
#X_fit.append(x_curve)
#Y_fit.append(y_curve)
#Z_fit.append(z_curve)
X_rec.append(X)
Y_rec.append(Y)
Z_rec.append(Z)
bar.finish()
# remove outlier trace
avg_length = mean(length_euclidean_rec)
indexes_length_remove = [idx for idx, element in enumerate(length_euclidean_rec) if element < (avg_length*length_thresh)]
#indexes_angle_remove = [idx for idx, element in enumerate(angle_rec) if element > 70]
#indexes_length_remove_label = [index_label_rec[i] for i in indexes_length_remove]
#print("avg_length is {0}".format(avg_length))
#print("indexes_length_remove is {0}".format(indexes_length_remove))
#print("indexes_angle_remove is {0}".format(indexes_angle_remove))
'''
fig_ori = mlab.figure(bgcolor = (1,1,1), fgcolor = (0.5, 0.5, 0.5), size = (600,400))
for (x_fit, y_fit, z_fit, x_ori, y_ori, z_ori, index_value) in zip(X_fit, Y_fit, Z_fit, X_rec, Y_rec, Z_rec, index_label_rec):
#print("connect_rec_value: {0} index {1}".format(connect_rec_value, index_rec_vis_value))
#pts = mlab.points3d(x_fit, y_fit, z_fit, color = (0.2, 0.4, 0.5), mode = 'point')
pts = mlab.points3d(x_ori, y_ori, z_ori, color = (0.8, 0.0, 0.0), mode = 'point')
pts.actor.property.set(point_size = 5.5)
#pts = mlab.plot3d(x_fit, y_fit, z_fit, color = (0.2, 0.4, 0.5))
pts = mlab.plot3d(x_fit, y_fit, z_fit, opacity = 0.3, representation = 'surface', transparent = True, tube_radius = 0.5)
pts = mlab.text3d(x_ori[0], y_ori[0], z_ori[0], str(index_value), scale = (4, 4, 4), color = (1, 0.0, 0.0))
mlab.show()
'''
#return index_rec, length_euclidean_rec, angle_rec, diameter_rec, projection_radius_rec, index_label_rec, fit_linepts_rec, indexes_length_remove
return index_rec, index_label_rec, fit_linepts_rec, indexes_length_remove, length_euclidean_rec
def angle_between(vector_1, vector_2):
unit_vector_1 = vector_1 / np.linalg.norm(vector_1)
unit_vector_2 = vector_2 / np.linalg.norm(vector_2)
dot_product = np.dot(unit_vector_1, unit_vector_2)
angle = np.arccos(dot_product)
return np.rad2deg(angle)
def interpolate_pts_3D(data, data_range, z_range):
# Calculate the mean of the points, i.e. the 'center' of the cloud
datamean = data.mean(axis=0)
# Do an SVD on the mean-centered data.
uu, dd, vv = np.linalg.svd(data - datamean)
# Now vv[0] contains the first principal component, i.e. the direction
# vector of the 'best fit' line in the least squares sense.
# Now generate some points along this best fit line, for plotting.
# I use -7, 7 since the spread of the data is roughly 14
# and we want it to have mean 0 (like the points we did
# the svd on). Also, it's a straight line, so we only need 2 points.
linepts = vv[0] * np.mgrid[(-1*data_range):data_range:complex(0,z_range)][:, np.newaxis]
# shift by the mean to get the line in the right place
linepts += datamean
return linepts
def solveEquations(P,L,U,y):
y1=np.dot(P,y)
y2=y1
m=0
for m in range(0, len(y)):
for n in range(0, m):
y2[m] = y2[m] - y2[n] * L[m][n]
y2[m] = y2[m] / L[m][m]
y3 = y2
for m in range(len(y) - 1,-1,-1):
for n in range(len(y) - 1, m, -1):
y3[m] = y3[m] - y3[n] * U[m][n]
y3[m] = y3[m] / U[m][m]
return y3
'''
Scipy tool with high complexity.
P stands for the permutation Matrix
L stands for the lower-triangle Matrix
U stands for the upper-triangle Matrix
matrix·x = y
P·matrix = L·U
P·matrix·x = L·U·x = P·y
L·U·x = y1
U·x = y2
x = y3
'''
def doLUFactorization(matrix):
P, L, U = scipy.linalg.lu(matrix)
return P, L, U
#calculate each parameters of location.
def func(x1,x2,t,v1,v2,t1,t2):
ft=((t2-t)**3*v1+(t-t1)**3*v2)/6+(t-t1)*(x2-v2/6)+(t2-t)*(x1-v1/6)
return ft
def cubic_spline_interpolate(x_axis,y_axis,z_axis):
'''
prepare right-side vector
'''
dx=[]
dy=[]
dz=[]
matrix=[]
n=2
while n<len(x_axis):
dx.append(3*(x_axis[n]-2*x_axis[n-1]+x_axis[n-2]))
dy.append(3*(y_axis[n]-2*y_axis[n-1]+y_axis[n-2]))
dz.append(3*(z_axis[n]-2*z_axis[n-1]+z_axis[n-2]))
n=n+1
'''
produce square matrix looks like :
[[2.0, 0.5, 0.0, 0.0], [0.5, 2.0, 0.5, 0.0], [0.0, 0.5, 2.0, 0.5], [0.0, 0.0, 2.0, 0.5]]
the classes of the matrix depends on the length of x_axis(number of nodes)
'''
matrix.append([float(2), float(0.5)])
for m in range(len(x_axis)-4):
matrix[0].append(float(0))
n=2
while n<len(x_axis)-2:
matrix.append([])
for m in range(n-2):
matrix[n-1].append(float(0))
matrix[n-1].append(float(0.5))
matrix[n-1].append(float(2))
matrix[n-1].append(float(0.5))
for m in range(len(x_axis)-n-3):
matrix[n-1].append(float(0))
n=n+1
matrix.append([])
for m in range(n-2):
matrix[n-1].append(float(0))
matrix[n-1].append(float(0.5))
matrix[n-1].append(float(2))
'''
LU Factorization may not be optimal method to solve this regular matrix.
If you guys have better idea to solve the Equation, please contact me.
As the LU Factorization algorithm cost 2*n^3/3 + O(n^2) (e.g. Doolittle algorithm, Crout algorithm, etc).
(How about Rx = Q'y using matrix = QR (Schmidt orthogonalization)?)
If your application field requires interpolating into constant number nodes,
It is highly recommended to cache the P,L,U and reuse them to get O(n^2) complexity.
'''
P, L, U = doLUFactorization(matrix)
u=solveEquations(P,L,U,dx)
v=solveEquations(P,L,U,dy)
w=solveEquations(P,L,U,dz)
'''
define gradient of start/end point
'''
m=0
U=[0]
V=[0]
W=[0]
while m<len(u):
U.append(u[m])
V.append(v[m])
W.append(w[m])
m=m+1
U.append(0)
V.append(0)
W.append(0)
#return U,V,W
n_iteration = 100
m = 1
xLinespace=[]
yLinespace=[]
zLinespace=[]
while m<len(x_axis):
for t in np.arange(m-1,m,1/float(n_iteration)):
xLinespace.append(func(x_axis[m-1],x_axis[m],t,U[m-1],U[m],m-1,m))
yLinespace.append(func(y_axis[m-1],y_axis[m],t,V[m-1],V[m],m-1,m))
zLinespace.append(func(z_axis[m-1],z_axis[m],t,W[m-1],W[m],m-1,m))
m=m+1