forked from megdec/vascularmd
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArterialTree.py
More file actions
5218 lines (3588 loc) · 149 KB
/
Copy pathArterialTree.py
File metadata and controls
5218 lines (3588 loc) · 149 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
####################################################################################################
# Author: Meghane Decroocq
#
# This file is part of vascularmd project (https://github.com/megdec/vascularmd)
#
# This program is free software: you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundation, version 3 of the License.
#
####################################################################################################
from multiprocessing import Pool, Process, cpu_count, set_start_method
import pyvista as pv # Meshing
import vtk
from scipy.spatial import KDTree
import warnings
import pickle
# Trigonometry functions
from math import pi
from numpy.linalg import norm
from numpy import dot, cross
# Plot
import matplotlib.pyplot as plt # Tools for plots
from mpl_toolkits.mplot3d import Axes3D # 3D display
import gc
import os
import networkx as nx
from utils import *
from Nfurcation import Nfurcation
from Spline import Spline
class ArterialTree:
#####################################
########## CONSTRUCTOR ############
#####################################
def __init__(self, patient_name, database_name, filename = None, automatic_resampling = True):
# Initiate attributes
self.patient_name = patient_name
self.database_name = database_name
self._surface_mesh = None
self._volume_mesh = None
if filename == None:
self._full_graph = None
self._topo_graph = None
self._model_graph = None
self._crsec_graph = None
else:
self.__load_file(filename)
self.__set_topo_graph()
self._model_graph = None
self._crsec_graph = None
if automatic_resampling:
self.automatic_resampling()
#####################################
############# GETTERS #############
#####################################
def get_full_graph(self):
""" Return the full graph """
if self._full_graph is None:
warnings.warn("No full graph found.")
return self._full_graph
def get_topo_graph(self):
""" Return the topo graph """
if self._topo_graph is None:
warnings.warn("No topo graph found.")
return self._topo_graph
def get_model_graph(self):
""" Return the model graph """
if self._model_graph is None:
warnings.warn("No model graph found.")
return self._model_graph
def get_crsec_graph(self):
""" Return the crsec graph """
if self._crsec_graph is None:
warnings.warn("No crsec graph found.")
return self._crsec_graph
def get_surface_mesh(self):
""" Return the surface mesh """
if self._surface_mesh is None:
warnings.warn("No surface mesh found.")
else:
return pv.PolyData(self._surface_mesh[0], self._surface_mesh[1])
def get_volume_mesh(self, formt = "pyvista"):
""" Return the volume mesh """
if self._volume_mesh is None:
warnings.warn("No volume mesh found.")
else:
if formt == "pyvista":
#return self.write_pyvista_mesh_from_vtk(self._volume_mesh[2], self._volume_mesh[0])
cells = self._volume_mesh[0]
cell_types = self._volume_mesh[1]
points = self._volume_mesh[2]
return pv.UnstructuredGrid(cells, cell_types, points)
elif formt == "meshio":
import meshio
points = self._volume_mesh[2]
cells = [("hexahedron", self._volume_mesh[0][:,1:])]
return meshio.Mesh(points, cells)
else:
warnings.warn("Wrong format argument given. The accepted formats are 'pyvista' and 'meshio'.")
def get_surface_link(self):
if self._surface_mesh is None:
warnings.warn("No surface mesh found.")
else:
if len(self._surface_mesh) < 3:
warnings.warn("The surface mesh links were not computed.")
else:
return self._surface_mesh[2]
def get_volume_link(self):
if self._volume_mesh is None:
warnings.warn("No volume mesh found.")
else:
if len(self._volume_mesh) < 4:
warnings.warn("The volume mesh links were not computed.")
else:
return self._volume_mesh[3]
def get_number_of_faces(self):
if self._surface_mesh is None:
warnings.warn("No surface mesh found.")
else:
return self._surface_mesh[0].shape[0]
def get_number_of_cells(self):
if self._volume_mesh is None:
warnings.warn("No volume mesh found.")
else:
return self._volume_mesh[0].shape[0]
def get_bifurcations(self):
""" Returns a list of all bifurcation objects in the network """
if self._crsec_graph is None:
raise ValueError("No crsec graph found.")
else:
bifurcations = []
for n in self._model_graph.nodes():
if self._model_graph.nodes[n]['type'] == "bif":
bifurcations.append(self._model_graph.nodes[n]['bifurcation'])
return bifurcations
def get_inlet_outlet(self):
""" Returns the informations about the inlet and outlet of the model (useful for CFD)"""
if self._model_graph is None:
raise ValueError("Please compute model first.")
else:
inlet_nodes = []
outlet_nodes = []
boundary_info = []
for n in self._model_graph.nodes():
if self._model_graph.nodes[n]['type'] == "end":
if self._model_graph.in_degree(n) == 0: # Inlet case
inlet_nodes.append(n)
else:
outlet_nodes.append(n)
for n in inlet_nodes:
spl = self._model_graph.edges[[e for e in self._model_graph.out_edges(n)][0]]["spline"]
tg = spl.tangent(0.0)
center = self._model_graph.nodes[n]["coords"]
boundary_info.append([center, tg, "inlet"])
for n in outlet_nodes:
spl = self._model_graph.edges[[e for e in self._model_graph.in_edges(n)][0]]["spline"]
tg = spl.tangent(1.0)
center = self._model_graph.nodes[n]["coords"]
boundary_info.append([center, tg, "outlet"])
return boundary_info
#####################################
############# SETTERS #############
#####################################
def check_full_graph(self):
""" Validity check for the full graph """
valid = True
valid_degrees = [(0, 1), (1, 0), (0, 2), (2, 0), (1, 1), (1, 2), (1, 3), (1, 4)]
for n in self._full_graph.nodes():
degrees = (self._full_graph.in_degree(n), self._full_graph.out_degree(n))
if degrees not in valid_degrees:
valid = False
return valid
def reset_model_mesh(self):
""" Reset the computation of model and mesh (to preserve coherency with topo and full graphs) """
self._model_graph = None
self._crsec_graph = None
self._surface_mesh = None
self._volume_mesh = None
def set_full_graph(self, G):
""" Set the full graph of the arterial tree."""
self._full_graph = G
self.__set_topo_graph()
self.reset_model_mesh()
if not self.check_full_graph():
print("Warning: the input centerline is invalid.")
def set_topo_graph(self, G, replace = True):
""" Set the topo graph of the arterial tree."""
self._topo_graph = G
if replace:
self.topo_to_full(replace)
self.reset_model_mesh()
def set_model_graph(self, G, replace = True, down_replace = True):
""" Set the model graph of the arterial tree."""
self._model_graph = G
if replace:
self._crsec_graph = None
if down_replace:
self.model_to_full()
def set_crsec_graph(self, G):
""" Set the crsec graph of the arterial tree."""
self._crsec_graph = G
def automatic_resampling(self, mind = 0.4, maxd = 0.6):
""" Automatically resample data points to a target data point density in order to facilitate the visualization and model edition """
for e in self._topo_graph.edges():
data = np.vstack((self._topo_graph.nodes[e[0]]["coords"], self._topo_graph.edges[e]["coords"], self._topo_graph.nodes[e[1]]["coords"]))
# Estimate the data density
l = length_polyline(data)[-1]
d = len(data) / l
num = len(data)
resamp_data = data
if d > maxd:
while d > maxd:
num -= 1
if num < 4:
num = 4
resamp_data = resample(data, num)
l = length_polyline(resamp_data)[-1]
d = num / l
if num == 4:
break
elif d < mind:
while d < mind:
num+=1
if num < 4:
num = 4
resamp_data = resample(data, num)
l = length_polyline(resamp_data)[-1]
d = num / l
new_data = resamp_data[1:-1, :]
self._topo_graph.edges[e]["coords"] = new_data
self._topo_graph.edges[e]["full_id"] = [0]*len(new_data)
# Re-write full
self.topo_to_full()
def __load_file(self, filename):
"""Converts a centerline file to a graph and set full_graph attribute.
Keyword arguments:
filename -- path to centerline file
"""
if type(filename) is list:
print('Loading edg and nds files...')
self._full_graph = self.__edg_nds_to_graph(filename[0], filename[1])
else:
if filename[-4:] == ".swc":
print('Loading ' + filename[-3:] + ' file...')
self._full_graph = self.__swc_to_graph(filename)
elif filename[-4:] == ".vtk" or filename[-4:] == ".vtp":
print('Loading ' + filename[-3:] + ' file...')
self._full_graph = self.__vtk_to_graph(filename)
elif filename[-4:] == ".txt":
print('Loading ' + filename[-3:] + ' file...')
self._full_graph = self.__txt_to_graph(filename)
elif filename[-4:] == ".tre":
print('Loading ' + filename[-3:] + ' file...')
self._full_graph = self.__tre_to_graph(filename)
else:
raise ValueError("The provided files must be in swc, vtp, tre or vtk format.")
if not self.check_full_graph():
print("Warning: the input centerline is invalid.")
def __set_topo_graph(self):
""" Set the topo graph of the arterial tree.
All edges of but the terminal and bifurcation edges are collapsed.
The coordinates of the collapsed regular points are stored as an edge attribute. The nodes are labelled (end, bif, reg) """
self._topo_graph = self._full_graph.copy()
nx.set_node_attributes(self._topo_graph, "reg", name="type")
nx.set_node_attributes(self._topo_graph, None, name="full_id")
nx.set_edge_attributes(self._topo_graph, None, name="full_id")
#nx.set_node_attributes(self._full_graph, None, name="topo_id")
for n in self._full_graph.nodes():
# If regular nodes
if self._full_graph.in_degree(n) == 1 and self._full_graph.out_degree(n) == 1:
# Create tables of regular nodes data
coords = np.vstack((list(self._topo_graph.in_edges(n, data=True))[0][2]['coords'], self._topo_graph.nodes[n]['coords'], list(self._topo_graph.out_edges(n, data=True))[0][2]['coords']))
# Create new edge by merging the 2 edges of regular point
self._topo_graph.add_edge(list(self._topo_graph.predecessors(n))[0], list(self._topo_graph.successors(n))[0], coords = coords)
# Remove regular point
self._topo_graph.remove_node(n)
else :
# Add node type attribute
if self._topo_graph.out_degree(n) == 0 or self._topo_graph.in_degree(n) == 0:
if self._topo_graph.out_degree(n) == 2 or self._topo_graph.in_degree(n) == 2:
self._topo_graph.nodes[n]['type'] = "sink"
else:
self._topo_graph.nodes[n]['type'] = "end"
else:
self._topo_graph.nodes[n]['type'] = "bif"
# Store the matching of full graph node numbers
for n in self._topo_graph.nodes():
self._topo_graph.nodes[n]["full_id"] = n
#self._full_graph.nodes[n]["topo_id"] = [n]
for e in self._topo_graph.edges():
path = list(nx.all_simple_paths(self._full_graph, source=e[0], target=e[1]))[0]
self._topo_graph.edges[e]["full_id"] = path[1:-1]
#for i in range(1, len(path)-1):
#self._full_graph.nodes[path[i]]["topo_id"] = [e, i-1]
# Relabel nodes
self._topo_graph = nx.convert_node_labels_to_integers(self._topo_graph, first_label=1, ordering='default', label_attribute=None)
# Remove the previous model and mesh computations as the full graph was modified
self.reset_model_mesh()
#####################################
########## APPROXIMATION ##########
#####################################
def model_network(self, radius_model = True, criterion="AIC", akaike=False, max_distance = 6, max_distance_radius = np.inf):
""" Create Nfurcation objects and approximate centerlines using splines. The network model is stored in the model_graph attribute."""
print('Modeling the network...')
# Check if the input data is ok for modelling
if not self.check_full_graph():
print("The network cannot be modeled as the input centerline is invalid.")
else:
# If there is a crsec_graph, remove it
if self._crsec_graph != None:
self._crsec_graph = None
self._model_graph = self._topo_graph.copy()
nx.set_node_attributes(self._model_graph, None, name='bifurcation')
nx.set_node_attributes(self._model_graph, False, name='combine')
nx.set_node_attributes(self._model_graph, None, name='tangent')
nx.set_node_attributes(self._model_graph, None, name='ref')
nx.set_edge_attributes(self._model_graph, None, name='spline')
# Get inlet id
sources = []
for n in self._topo_graph.nodes():
if self._topo_graph.in_degree(n) == 0:
sources.append(n)
# Bifurcation models
all_id = [n for n in self._topo_graph.nodes()]
original_label = dict(zip(all_id, all_id))
# dfs
for source in sources:
dfs = list(nx.dfs_successors(self._topo_graph, source=source).values())
for l in dfs:
for n in l:
if n in [nds for nds in self._topo_graph.nodes()]:
n = original_label[n]
if self._topo_graph.nodes[n]['type'] == "bif":
original_label = self.__model_furcation(n, original_label, criterion, akaike, max_distance)
# Spline models
# Straight tube case
for e in self._model_graph.edges():
if self._model_graph.nodes[e[0]]['type'] == "end" and self._model_graph.nodes[e[1]]['type'] == "end" :
self.__model_vessel(e, criterion=criterion, akaike=akaike, radius_model=radius_model, max_distance = max_distance)
# Sink case
nds_list = list(self._model_graph.nodes())
for n in nds_list:
if self._model_graph.nodes[n]['type'] == "sink":
sink_edg = [e for e in self._model_graph.in_edges(n)] + [e for e in self._model_graph.out_edges(n)]
self.__model_vessel(sink_edg[0], criterion=criterion, akaike=akaike, radius_model=radius_model, max_distance = max_distance)
# Add rotation attributes
nx.set_edge_attributes(self._model_graph, None, name='alpha')
nx.set_edge_attributes(self._model_graph, 0, name='connect')
# Add rotation information on bifs and edges
for n in self._model_graph.nodes():
if self._model_graph.nodes[n]["type"] == "end" and self._model_graph.in_degree(n) == 0:
self.__compute_rotations(n)
if self._model_graph.nodes[n]["type"] == "sep":
self.__compute_rotations(n)
def __model_furcation(self, n, original_label, criterion, akaike, max_distance):
""" Extract bifurcation parameters from the data and modify the model graph to add the bifurcation object and edges.
Keyword arguments:
n -- bifurcation node (model graph)
"""
LEN_OUT = 1.5 # length of daughter branches = LEN_OUT x radius
LEN_IN = 4 # length of mother branch = LEN_IN x radius
R_BIF = 3 # smoothing degree for the bifurcations
MIN_LEN_IN = 3 # Minimum length to consider before merging
from Model import Model
original_label_modif = original_label
# Get original label dictionary
all_id = [nds for nds in self._topo_graph.nodes()]
label_dict_topo = dict(zip(all_id, all_id))
all_id = [nds for nds in self._model_graph.nodes()]
label_dict_model = dict(zip(all_id, all_id))
nmax = max(list(self._model_graph.nodes())) + 1
e_in = [e for e in self._model_graph.in_edges(n)]
e_out = [e for e in self._model_graph.out_edges(n)]
e_out.sort()
apex_found = False
nb_min = 10
while not apex_found:
apex_found = True
splines = []
# Approximate vessels
for i in range(len(e_out)):
data = np.vstack((self._model_graph.nodes[n]['coords'], self._model_graph.edges[e_out[i]]['coords'], self._model_graph.nodes[e_out[i][1]]['coords']))
nb_data_out = self._model_graph.edges[e_out[i]]['coords'].shape[0] + 1
e_act = e_out[i]
n_act = e_act[1]
while data.shape[0] < nb_min:
if self._model_graph.out_degree(n_act)!= 0:
e_next = (n_act, [e for e in self._model_graph.successors(n_act)][0]) # Get a successor edge
data = np.vstack((data, self._model_graph.edges[e_next]['coords'], self._model_graph.nodes[e_next[1]]['coords'])) # Add data
e_act = e_next
n_act = e_next[1]
#elif self._model_graph.nodes[n_act]["type"] == "sink" and self._model_graph.out_degree(n_act) == 0: # If in sink, cross the next bifurcation
# e_next = list(self._model_graph.in_edges(n_act))
# if e_act in e_next:
# e_next.remove(e_act)
# e_next = e_next[0] # Get a successor edge (in in the sink case)
# data = np.vstack((data, self._model_graph.edges[e_next]['coords'][::-1], self._model_graph.nodes[e_next[0]]['coords'])) # Add data (reversed because in sink)
# e_act = e_next
# n_act = e_next[0]
else: break
values = np.zeros((4,4))
constraint = [False] * 4
if self._model_graph.nodes[e_in[0][0]]['type'] != "bif":
data = np.vstack((self._model_graph.nodes[e_in[0][0]]['coords'], self._model_graph.edges[e_in[0]]['coords'], data))
if self._model_graph.nodes[e_in[0][0]]['type'] == "sep":
values[0,:] = self._model_graph.nodes[e_in[0][0]]['coords']
constraint[0] = True
values[1,:] = self._model_graph.nodes[e_in[0][0]]['tangent']
constraint[1] = True
else:
values[0,:] = self._model_graph.nodes[n]['coords']
constraint[0] = True
values[1,:] = self._model_graph.nodes[n]['tangent']
constraint[1] = True
spl = Spline()
spl.approximation(data, constraint, values, False, criterion = criterion, max_distance = max_distance)
#spl.show(data=data)
splines.append(spl)
# Reorder nodes
if len(e_out) > 2:
order, label_dict_model, label_dict_topo, original_label_modif = self.__reorder_branches(n, splines, original_label)
# Reorder splines
splines_reordered = []
for j in range(len(splines)):
splines_reordered.append(splines[order[j]])
splines = splines_reordered
AP = []
tAP = []
for i in range(len(splines)):
tAP.append([])
# Find apex
for i in range(len(splines)-1):
# Compute apex value
ap, t = splines[i].first_intersectionv2(splines[i+1])
if t[0] == 1.0 or t[1] == 1.0:
# Splines were included in each other, add more data
apex_found = False
nb_min += 10
AP.append(ap)
tAP[i].append(t[0])
tAP[i+1].append(t[1])
self._topo_graph = nx.relabel_nodes(self._topo_graph, label_dict_topo)
self._model_graph = nx.relabel_nodes(self._model_graph, label_dict_model)
combine = False
merge_next = False
# Get index of the in spline with max diameter for C0
if len(splines) == 2: # The vessel with the bigger radius is used to set C0
r = 0
ind = 0
for i in range(len(splines)):
rad = splines[i].radius(max(tAP[i]))
if rad > r:
r = rad
ind = i
else:
min_t = 1
for i in range(len(AP)): # The vessel with the smallest tAP is used to set C0
t = splines[1].project_point_to_centerline(AP[i])
if t < min_t:
min_t = t
ind = i
t_ap = min(tAP[ind])
l_ap = splines[ind].time_to_length(t_ap)
if l_ap - splines[ind].radius(t_ap)* MIN_LEN_IN > 0.2: # We can cut!
if l_ap - splines[ind].radius(t_ap)* LEN_IN > 0.2:
t_cut = splines[ind].length_to_time(l_ap - splines[ind].radius(t_ap)*LEN_IN)
else:
t_cut = splines[ind].length_to_time(l_ap - splines[ind].radius(t_ap)*MIN_LEN_IN)
if t_cut < 10**(-2):
pt_cut = splines[ind].point(t_cut)
spline_cut, tmp_spl = splines[ind].split_time(0.1)
new_t_cut = spline_cut.project_point_to_centerline(pt_cut)
spline_in, tmp_spl = spline_cut.split_time(new_t_cut)
else:
spline_in, tmp_spl = splines[ind].split_time(t_cut)
model = splines[ind].get_model()
T = model[0].get_t()
thres = np.argmax(T>t_cut)
thres = thres - 1
data = self._model_graph.edges[e_in[0]]['coords']
D_in = data[:thres,:]
C0 = [splines[ind].point(t_cut, True), splines[ind].tangent(t_cut, True)]
else: # Merge with LAST one to create trifurcation or combine (length criterion)
print("Combine!")
combine = True
nbifprec = list(self._model_graph.predecessors(e_in[0][0]))[0]
branch = list(self._model_graph.successors(nbifprec))
branch = branch.index(e_in[0][0])
bifprec = self._model_graph.nodes[nbifprec]['bifurcation']
C0 = bifprec.get_apexsec()[branch][0] # If merged bifurcations, C0 is the apex section of the previous bifurcation
if not merge_next: # Keep on building the model
# Compute apical and end cross sections + new data
C = [C0]
AC = []
spl_out = []
D_out = []
for i in range(len(splines)):
t_ap = max(tAP[i])
t_cut = splines[i].length_to_time(splines[i].radius(t_ap)*LEN_OUT + splines[i].time_to_length(t_ap))
n_next = e_out[i][1]
if t_cut > splines[i].project_point_to_centerline(self._topo_graph.nodes[n_next]['coords'][:-1]) and self._topo_graph.nodes[n_next]['type'] == "bif":
merge_next = True
print("Merging to next!")
break
else:
if t_cut > 1.0 - 10**(-2):
pt_cut = splines[i].point(t_cut)
tmp_spl, spline_cut = splines[i].split_time(0.9)
new_t_cut = spline_cut.project_point_to_centerline(pt_cut)
tmp_spl, spl = spline_cut.split_time(new_t_cut)
else:
tmp_spl, spl = splines[i].split_time(t_cut)
# Cut spline_out
spl_out.append(spl)
# Separate data points
model = splines[i].get_model()
T = model[0].get_t()
thres = np.argmax(T>t_cut)
nb_in = len(np.vstack((self._model_graph.nodes[e_in[0][0]]['coords'], self._model_graph.edges[e_in[0]]['coords'])))
thres = thres - nb_in - 1
data = self._model_graph.edges[e_out[i]]['coords']
if thres >= len(data):
D_out.append(np.array([]).reshape(0,4))
elif thres < 0:
D_out.append(data)
else:
D_out.append(data[thres:,:])
C.append([splines[i].point(t_cut, True), splines[i].tangent(t_cut, True)])
AC.append([])
tap_ordered = tAP[i][:]
tap_ordered.sort()
for t_ap in tap_ordered:
AC[i].append([splines[i].point(t_ap, True), splines[i].tangent(t_ap, True)])
if merge_next:
self.merge_branch(n_next) # Merge in topo graph and recompute
self.merge_branch(n_next, mode = "model")
# Re-model furcation
original_label = self.__model_furcation(n, original_label, criterion, akaike, max_distance)
else: # Build bifurction and include it in graph
original_label = original_label_modif
bif = Nfurcation("crsec", [C, AC, AP, R_BIF])
#bif.show(True)
ref = bif.get_reference_vectors()
endsec = bif.get_endsec()
if combine:
# Add in edge and bif
self._model_graph.remove_node(n)
self._model_graph.add_node(nmax, coords = bif.get_X(), bifurcation = bif, combine = combine, type = "bif", ref = None, tangent = None) # Add bif node
self._model_graph.add_edge(e_in[0][0], nmax, coords = np.array([]).reshape(0,4), spline = bif.get_tspl()[0]) # Add in edge
# Relabel sep node
all_id = [n for n in self._model_graph.nodes()]
label_dict = dict(zip(all_id, all_id))
label_dict[e_in[0][0]] = n
self._model_graph = nx.relabel_nodes(self._model_graph, label_dict)
nbif = nmax
nmax += 1
else:
# Add in edge and bif
self._model_graph.add_node(n, coords = endsec[0][0], bifurcation = None, combine = combine, type = "sep", ref = ref[0], tangent = endsec[0][1]) # Change bif node to sep
self._model_graph.edges[e_in[0]]['coords'] = D_in
self._model_graph.edges[e_in[0]]['spline'] = spline_in
self._model_graph.nodes[e_in[0][0]]['coords'] = spline_in.point(0.0, True)
self._model_graph.add_node(nmax, coords = bif.get_X(), bifurcation = bif, combine = combine, type = "bif", ref = None, tangent = None) # Add bif node
self._model_graph.add_edge(n, nmax, coords = np.array([]).reshape(0,4), spline = bif.get_tspl()[0]) # Add in edge
nbif = nmax
nmax += 1
for i in range(len(splines)): # Add out edges
self._model_graph.add_node(nmax, coords = C[i+1][0], bifurcation = None, combine = False, type = "sep", ref = ref[i+1], tangent = C[i+1][1])
self._model_graph.add_edge(nbif, nmax, coords = np.array([]).reshape(0,4), spline = bif.get_tspl()[i+1])
if self._topo_graph.nodes[e_out[i][1]]["type"] == "end": # Add the cut out splines if end segments
self._model_graph.add_edge(nmax, e_out[i][1], coords = D_out[i], spline = spl_out[i])
self._model_graph.nodes[e_out[i][1]]['coords'] = spl_out[i].point(1.0, True)
else:
self._model_graph.add_edge(nmax, e_out[i][1], coords = D_out[i], spline = None) # Do not add the cut out splines
if not combine:
self._model_graph.remove_edge(e_out[i][0], e_out[i][1])
nmax += 1
return original_label
def __reorder_branches(self, n, splines, original_label, dist_threshold = 1.5):
""" Reorder branches to handle planar furcation case.
Keyword arguments:
n -- furcation node
splines -- list of splines
dist_threshold -- minimum distance between evaluated points
"""
# Get label dictionnaries
all_id = [nds for nds in self._topo_graph.nodes()]
label_dict_topo = dict(zip(all_id, all_id))
all_id = [nds for nds in self._model_graph.nodes()]
label_dict_model = dict(zip(all_id, all_id))
# Get edges and nodes ids
edg_id = [edg for edg in self._model_graph.out_edges(n)]
edg_id.sort()
nds_id = [e[1] for e in edg_id]
# Order by angles
dist_min = False
tmax = False
l = 1
while not dist_min and not tmax:
dist_min = True
# Spline evaluation at length l
pt = []
for s in range(len(splines)):
t = splines[s].length_to_time(l)
if t == 1.0:
tmax = True
# We can't search further
pt.append(splines[s].point(t))
# Check distance condition
for j in range(len(pt)-1):
if norm(pt[j] - pt[j+1]) < dist_threshold:
# Distance condition is not satisfied
dist_min = False
if not dist_min: # Search further points
l += 1
# Get angles
angles = np.zeros((len(pt), len(pt)))
for j in range(len(pt)):
for k in range(len(pt)):
if k > j:
# Compute angle
v1 = pt[j] - self._model_graph.nodes[n]['coords'][:-1]
v2 = pt[k] - self._model_graph.nodes[n]['coords'][:-1]
a = angle(v1, v2)
angles[j, k] = a
angles[k, j] = a
# Get index of maximum angles
ind = np.argmax(angles)
ind = np.unravel_index(ind, (len(pt), len(pt)))
order = [ind[0]]
angles[:, ind[0]] = [2*pi] * len(pt)
for j in range(len(pt)-1):
ind = np.argmin(angles[order[j-1]])
order.append(ind)
angles[:, ind] = [2*pi] * len(pt)
# Relabel nodes
for j in range(len(nds_id)):
label_dict_model[nds_id[order[j]]] = nds_id[j]
label_dict_topo[nds_id[order[j]]] = nds_id[j]
original_label[nds_id[order[j]]] = nds_id[j]
return order, label_dict_model, label_dict_topo, original_label
def __model_vessel(self, e, criterion, akaike, radius_model, max_distance):
""" Compute vessel spline model with end tangent constraint and add it to model graph
Keyword arguments:
e -- vessel (model graph)
"""
# Merge data of both sides
if self._model_graph.nodes[e[0]]['type'] == 'sink': # Out sink
sink_edg = [e for e in self._model_graph.out_edges(e[0])]
pts = np.vstack((self._model_graph.nodes[sink_edg[0][1]]['coords'], self._model_graph.edges[sink_edg[0]]['coords'][::-1, :], self._model_graph.nodes[sink_edg[0][0]]['coords']))
pts = np.vstack((pts, self._model_graph.edges[sink_edg[1]]['coords'], self._model_graph.nodes[sink_edg[1][1]]['coords']))
edg_type = 'out_sink'
sink = e[0]
ends = (sink_edg[0][1], sink_edg[1][1])
elif self._model_graph.nodes[e[1]]['type'] == 'sink': #In sink
sink_edg = [e for e in self._model_graph.in_edges(e[1])]
pts1 = np.vstack((self._model_graph.nodes[sink_edg[0][0]]['coords'], self._model_graph.edges[sink_edg[0]]['coords'], self._model_graph.nodes[sink_edg[0][1]]['coords']))
pts = np.vstack((pts1, self._model_graph.edges[sink_edg[1]]['coords'][::-1, :], self._model_graph.nodes[sink_edg[1][0]]['coords']))
edg_type = 'in_sink'
sink = e[1]
ends = (sink_edg[0][0], sink_edg[1][0])
else: # Normal edge
pts = np.vstack((self._model_graph.nodes[e[0]]['coords'], self._model_graph.edges[e]['coords'], self._model_graph.nodes[e[1]]['coords']))
edg_type = 'edg'
ends = (e[0], e[1])
if len(pts) <=6:
pts = resample(pts, 6)
# Fit spline
values = np.zeros((4,4))
constraint = [False] * 4
if self._model_graph.nodes[ends[0]]['type'] != "end":
values[0,:] = self._model_graph.nodes[ends[0]]['coords']
constraint[0] = True
if edg_type == "out_sink":
values[1,:] = -self._model_graph.nodes[ends[0]]['tangent']
else:
values[1,:] = self._model_graph.nodes[ends[0]]['tangent']
constraint[1] = True
if self._model_graph.nodes[ends[1]]['type'] != "end":
values[-1,:] = self._model_graph.nodes[ends[1]]['coords']
constraint[-1] = True
if edg_type == "in_sink":
values[-2,:] = -self._model_graph.nodes[ends[1]]['tangent']
else:
values[-2,:] = self._model_graph.nodes[ends[1]]['tangent']
constraint[-2] = True
spl = Spline()
spl.approximation(pts, constraint, values, False, criterion=criterion, akaike=akaike, radius_model=radius_model, max_distance = max_distance)
# If not sink
if edg_type == "edg":
self._model_graph.edges[e]['spline'] = spl
self._model_graph.nodes[e[1]]['coords'] = spl.point(1.0, True)
else:
# Remove sink point
self._model_graph.remove_node(sink)
# Add new edge
self._model_graph.add_edge(ends[0], ends[1], spline = spl, data = pts[1:-1, :])
def __compute_rotations(self, n):
""" Compute the rotation angle alpha and the connecting node for vessel of edge e
Keyword arguments:
e -- vessel (model graph)
"""
if self._model_graph.nodes[n]['type'] == "end" and self._model_graph.in_degree(n)==0: # Inlet case
sep_end = False
# path to the next sep node
path = [n]
nd = n
reach_end = False
while not reach_end: