-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmorpho_gen.cpp
3369 lines (2846 loc) · 108 KB
/
morpho_gen.cpp
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
/*
* Copyright (c) 2009-2019: G-CSC, Goethe University Frankfurt
*
* Author: Markus Breit
* Creation date: 2016-09-07
*
* This file is part of NeuroBox, which is based on UG4.
*
* NeuroBox and UG4 are free software: You can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3
* (as published by the Free Software Foundation) with the following additional
* attribution requirements (according to LGPL/GPL v3 §7):
*
* (1) The following notice must be displayed in the appropriate legal notices
* of covered and combined works: "Based on UG4 (www.ug4.org/license)".
*
* (2) The following notice must be displayed at a prominent place in the
* terminal output of covered works: "Based on UG4 (www.ug4.org/license)".
*
* (3) The following bibliography is recommended for citation and must be
* preserved in all covered files:
* "Reiter, S., Vogel, A., Heppner, I., Rupp, M., and Wittum, G. A massively
* parallel geometric multigrid solver on hierarchically distributed grids.
* Computing and visualization in science 16, 4 (2013), 151-164"
* "Vogel, A., Reiter, S., Rupp, M., Nägel, A., and Wittum, G. UG4 -- a novel
* flexible software system for simulating PDE based models on high performance
* computers. Computing and visualization in science 16, 4 (2013), 165-179"
* "Stepniewski, M., Breit, M., Hoffer, M. and Queisser, G.
* NeuroBox: computational mathematics in multiscale neuroscience.
* Computing and visualization in science (2019).
* "Breit, M. et al. Anatomically detailed and large-scale simulations studying
* synapse loss and synchrony using NeuroBox. Front. Neuroanat. 10 (2016), 8"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
#include "morpho_gen.h"
#include <algorithm> // for max, min, sort
#include <cmath> // for sqrt, fabs
#include <cstdlib> // for rand, RAND_MAX
#include <ctime> // for time
#include <limits> // for numeric_limits
#include <queue> // for queue
#include <sstream> // for stringstream
#include "common/error.h" // for UG_COND_THROW
#include "common/log.h" // for UG_LOGN
#include "common/math/math_vector_matrix/math_matrix_vector_functions.h" // for MatVecMult
#include "common/math/math_vector_matrix/math_vector_functions.h" // for VecSubtract
#include "common/math/misc/math_constants.h" // for PI
#include "common/util/file_util.h" // for FindDirInSt...
#include "common/util/smart_pointer.h" // for SmartPtr
#include "common/util/string_util.h" // for PathFromFil...
#include "lib_algebra/common/operations_vec.h" // for VecProd
#include "lib_algebra/small_algebra/small_matrix/densematrix.h" // for DenseMatrix
#include "lib_algebra/small_algebra/small_matrix/densematrix_inverse.h" // for Invert
#include "lib_algebra/small_algebra/storage/variable_array.h" // for VariableArray1
#include "lib_disc/domain.h" // for Domain3d
#include "lib_disc/domain_util.h" // for LoadDomain
#include "lib_grid/algorithms/element_side_util.h" // for GetOpposing...
#include "lib_grid/algorithms/extrusion/extrude.h" // for Extrude
#include "lib_grid/algorithms/orientation_util.h" // for FixFaceOrie...
#include "lib_grid/algorithms/selection_util.h" // for SelectAssoc...
#include "lib_grid/algorithms/geom_obj_util/edge_util.h" // for EdgeLength
#include "lib_grid/algorithms/geom_obj_util/face_util.h" // for CalculateFa...
#include "lib_grid/algorithms/geom_obj_util/misc_util.h" // for CalculateCe...
#include "lib_grid/algorithms/geom_obj_util/vertex_util.h" // for MergeVertices
#include "lib_grid/algorithms/geom_obj_util/volume_util.h" // for CalculateCe...
#include "lib_grid/algorithms/grid_generation/icosahedron.h" // for GenerateIco...
#include "lib_grid/algorithms/grid_generation/triangle_fill_sweep_line.h" // for TriangleFil...
#include "lib_grid/algorithms/remeshing/delaunay_triangulation.h" // for QualityGrid...
#include "lib_grid/algorithms/selection_util.h" // for SelectInner...
#include "lib_grid/algorithms/subset_util.h" // for AssignSubse...
#include "lib_grid/attachments/attachment_pipe.h" // for AttachmentA...
#include "lib_grid/callbacks/selection_callbacks.h" // for IsSelected
#include "lib_grid/file_io/file_io.h" // for SaveGridHie...
#include "lib_grid/file_io/file_io_ugx.h" // for GridWriterUGX
#include "lib_grid/grid/grid_base_object_traits.h" // for VertexIterator
#include "lib_grid/grid/grid_base_objects.h" // for Face, Edge
#include "lib_grid/grid/grid_util.h" // for CompareVertices
#include "lib_grid/grid_objects/grid_objects_0d.h" // for RegularVertex
#include "lib_grid/grid_objects/grid_objects_1d.h" // for RegularEdge
#include "lib_grid/grid_objects/grid_objects_2d.h" // for Triangle
#include "lib_grid/grid_objects/grid_objects_3d.h" // for Tetrahedron
#include "lib_grid/refinement/global_multi_grid_refiner.h" // for GlobalMulti...
#include "lib_grid/refinement/projectors/cylinder_projector.h" // for CylinderPro...
#include "lib_grid/refinement/projectors/sphere_projector.h" // for SphereProje...
#include "lib_grid/tools/selector_grid.h" // for Selector
#include "lib_grid/tools/selector_grid_elem.h" // for FaceSelector
#include "lib_grid/tools/subset_handler_grid.h" // for SubsetHandler
#include "np_config.h"
#ifdef TETGEN_15_ENABLED
#include "tetgen.h"
#endif
namespace ug {
namespace nernst_planck {
MorphoGen::MorphoGen()
: m_grid(), m_sh(m_grid), m_sel(m_grid),
m_shProj(m_grid), m_projHandler(&m_shProj),
m_tmpHeadHeight(0.0),
m_bFilAnisotropic(false),
m_bWithRefinementProjector(true),
DENDRITE_LENGTH(1200.0),
DENDRITE_RADIUS(200.0),
MEMBRANE_RADIUS(10.0),
m_membraneEnvelopeRadius(20.0),
m_dendriteRimVertices(16),
SPINE_NECK_RADIUS(100.0),
SPINE_NECK_LENGTH(450.0),
SPINE_HEAD_RADIUS(175.0),
FILAMENT_WIDTH(10.0),
FILAMENT_RIM_VERTICES(6),
m_filamentEnvelopeRadius(10.0),
EXTENSION_LENGTH(1.0e5),
EXTENSION_COMPARTMENT_LENGTH(1.0e3),
BOX_MARGIN(150.0),
SHORT_EDGES_FACTOR(0.5),
NECK_FILAMENTS(5),
NUM_FILAMENTS(20),
TETRAHEDRALIZATION_QUALITY(20.0),
INNER_SI(0),
OUTER_SI(1),
MEM_SI(2),
FIL_NECK_SI(3),
MEM_INNER_BND_SI(4),
MEM_OUTER_BND_SI(5),
MEM_NOFLUX_BND_SI(6),
SURF_CH_BND(7),
NOFLUX_BND(8),
DIRI_BND(9),
PSD_INNER_SI(10),
PSD_OUTER_SI(11),
EXT_LEFT_SI(12),
EXT_RIGHT_SI(13),
INTF_LEFT_CONSTRD_SI(14),
INTF_RIGHT_CONSTRD_SI(15),
INTF_LEFT_NODE1D_SI(16),
INTF_RIGHT_NODE1D_SI(17),
INTF_LEFT_NODEHD_SI(18),
INTF_RIGHT_NODEHD_SI(19),
EXT_LEFT_BND_SI(20),
EXT_RIGHT_BND_SI(21),
USELESS_SI(22),
INNER_FRONT_TMP_SI(14),
OUTER_FRONT_TMP_SI(15),
ENVELOPE_END_TMP_SI(16)
{
// handle attachments and accessors
m_grid.attach_to_vertices(aPosition);
m_grid.attach_to_faces(aNormal);
m_aaPos = AAPosition(m_grid, aPosition);
m_aaNorm = AANormal(m_grid, aNormal);
m_sh.set_default_subset_index(0);
// set geometry in refinement projector
m_projHandler.set_geometry(MakeGeometry3d(m_grid, aPosition));
}
void MorphoGen::set_num_neck_filaments(size_t nFil)
{
NECK_FILAMENTS = nFil;
}
void MorphoGen::set_num_filaments(size_t nFil)
{
NUM_FILAMENTS = nFil;
}
void MorphoGen::set_fil_anisotropic(bool filAniso)
{
m_bFilAnisotropic = filAniso;
}
void MorphoGen::set_with_refinement_projector(bool withRP)
{
m_bWithRefinementProjector = withRP;
}
void MorphoGen::set_seed(size_t seed)
{
std::srand(seed);
}
void MorphoGen::set_randomized(bool rand)
{
if (!rand) return;
std::srand(std::time(0));
}
void MorphoGen::set_membrane_envelope_radius(number mem_env_rad)
{
m_membraneEnvelopeRadius = mem_env_rad;
}
void MorphoGen::set_filament_envelope_radius(number fil_env_rad)
{
m_filamentEnvelopeRadius = fil_env_rad;
}
void MorphoGen::set_resolution(size_t nRimVrt)
{
m_dendriteRimVertices = nRimVrt;
}
void MorphoGen::create_circle(const vector3& center, const vector3& axis, number radius, size_t numRimVertices)
{
m_sel.clear();
bool autoselEnabled = m_sel.autoselection_enabled();
m_sel.enable_autoselection(true);
// make sure axis is normed
UG_COND_THROW(fabs(1.0-VecLength(axis)) > 1e-4, "Calling create_circle, axis must be normed.");
// calculate trafo matrix
vector3 axis2;
if (axis[2] != 1.0)
{
axis2[2] = 0.0;
axis2[1] = -axis[0];
axis2[0] = axis[1];
}
else
{
axis2[0] = 1.0;
axis2[1] = axis2[2] = 0.0;
}
axis2 /= VecLength(axis2);
vector3 axis3;
VecCross(axis3, axis, axis2);
matrix33 trafo;
trafo(0,0) = axis[0];
trafo(1,0) = axis[1];
trafo(2,0) = axis[2];
trafo(0,1) = axis2[0];
trafo(1,1) = axis2[1];
trafo(2,1) = axis2[2];
trafo(0,2) = axis3[0];
trafo(1,2) = axis3[1];
trafo(2,2) = axis3[2];
// create edges by going round in the circle
Vertex* firstVrt = *m_grid.create<RegularVertex>();
MatVecMult(m_aaPos[firstVrt], trafo, vector3(0.0, radius, 0.0));
VecAdd(m_aaPos[firstVrt], m_aaPos[firstVrt], center);
number arc_length = 2.0 * PI / (number) numRimVertices;
Vertex* lastVrt = firstVrt;
for (size_t i = 1; i < numRimVertices; ++i)
{
// create a new vertex
Vertex* vNew = *m_grid.create<RegularVertex>();
MatVecMult(m_aaPos[vNew], trafo, vector3(0.0, cos(i*arc_length), -sin(i*arc_length)));
VecScale(m_aaPos[vNew], m_aaPos[vNew], radius);
VecAdd(m_aaPos[vNew], m_aaPos[vNew], center);
// create a new edge
m_grid.create<RegularEdge>(EdgeDescriptor(lastVrt, vNew));
lastVrt = vNew;
}
// one edge is still missing
m_grid.create<RegularEdge>(EdgeDescriptor(lastVrt, firstVrt));
// restore selector
m_sel.enable_autoselection(autoselEnabled);
}
void MorphoGen::create_shaft()
{
m_sel.clear();
bool autoselEnabled = m_sel.autoselection_enabled();
m_sel.enable_autoselection(true);
// create left end circle (new elems are auto-selected)
vector3 left_end_center(0.0);
left_end_center.coord(0) = -DENDRITE_LENGTH / 2.0;
number radius = DENDRITE_RADIUS;
create_circle(left_end_center, vector3(1,0,0), radius, m_dendriteRimVertices);
// assign subset
m_sh.assign_subset(m_sel.begin<Vertex>(), m_sel.end<Vertex>(), MEM_OUTER_BND_SI);
m_sh.assign_subset(m_sel.begin<Edge>(), m_sel.end<Edge>(), MEM_OUTER_BND_SI);
// extrude to build shaft
std::vector<Vertex*> vrts;
vrts.assign(m_sel.vertices_begin(), m_sel.vertices_end());
std::vector<Edge*> edges;
edges.assign(m_sel.edges_begin(), m_sel.edges_end());
// make extruded faces as regular as possible:
// length of extrusion should be as near as possible to current edge length in circle
number numExtrudes = floor(DENDRITE_LENGTH/(2*radius*sin(PI/m_dendriteRimVertices)));
size_t nExtrudes = std::max((size_t) numExtrudes, (size_t) 1);
number extrude_length = DENDRITE_LENGTH / nExtrudes;
vector3 extrudeDir(0.0);
extrudeDir.coord(0) = extrude_length;
for (size_t i = 0; i < nExtrudes; ++i)
Extrude(m_grid, &vrts, &edges, NULL, extrudeDir, m_aaPos, EO_CREATE_FACES, NULL);
// retriangulate
//QualityGridGeneration(m_grid, m_sel.begin<Triangle>(), m_sel.end<Triangle>(),
// m_aaPos, 30);
// restore selector
m_sel.enable_autoselection(autoselEnabled);
}
void MorphoGen::smooth_branching_point(number alpha, int numIterations, const vector3& spine_anchor)
{
Grid::edge_traits::secure_container edges;
Grid::face_traits::secure_container faces;
Grid::volume_traits::secure_container vols;
vector2 toOpp;
vector2 toAnchor;
for (int i = 0; i < numIterations; ++i)
{
std::queue<vector3> newPos;
// iterate through all vertices
geometry_traits<Vertex>::iterator it = m_sel.begin<Vertex>();
geometry_traits<Vertex>::iterator it_end = m_sel.end<Vertex>();
for (; it != it_end; ++it)
{
Vertex* vrt = *it;
const vector3& vPos = m_aaPos[vrt];
vector3 v;
VecSet(v, 0.0);
number weight = 0.0;
// calculate smoothing vector relative to neighbors
m_grid.associated_elements(edges, vrt);
for (size_t ei = 0; ei < edges.size(); ++ei)
{
const vector3& opp = m_aaPos[GetConnectedVertex(edges[ei], vrt)];
toOpp.coord(0) = opp.coord(0) - vPos.coord(0);
toOpp.coord(1) = opp.coord(1) - vPos.coord(1);
toAnchor.coord(0) = spine_anchor.coord(0) - 0.5*(vPos.coord(0) + opp.coord(0));
toAnchor.coord(1) = spine_anchor.coord(1) - 0.5*(vPos.coord(1) + opp.coord(1));
// smooth radially
number prodLength = VecLength(toAnchor) * VecLength(toOpp);
number w = prodLength ? fabs(VecProd(toAnchor, toOpp)) / prodLength : 0.0;
//UG_LOGN("Vertex " << vrt << "at " << m_aaPos[vrt] << ": Add " << opp << " with weight " << w << ".");
VecScaleAdd(v, 1.0, v, w, opp);
weight += w;
}
/*
m_grid.associated_elements(faces, vrt);
for (size_t fi = 0; fi < faces.size(); ++fi)
{
Face* f = faces[fi];
const vector3& opp = CalculateGridObjectCenter(
m_grid.get_opposing_object(vrt, f), m_aaPos);
toOpp.coord(0) = opp.coord(0) - vPos.coord(0);
toOpp.coord(1) = opp.coord(1) - vPos.coord(1);
toAnchor.coord(0) = spine_anchor.coord(0) - 0.5*(vPos.coord(0) + opp.coord(0));
toAnchor.coord(1) = spine_anchor.coord(1) - 0.5*(vPos.coord(1) + opp.coord(1));
// smooth radially
number prodLength = VecLength(toAnchor) * VecLength(toOpp);
number w = prodLength ? fabs(VecProd(toAnchor, toOpp)) / prodLength : 0.0;
VecScaleAdd(v, 1.0, v, w, opp);
weight += w;
}
*/
newPos.push(m_aaPos[vrt]);
if (weight > 0)
{
VecScale(v, v, 1.0 / weight);
VecSubtract(v, v, m_aaPos[vrt]);
VecScale(v, v, alpha);
VecAdd(newPos.back(), m_aaPos[vrt], v);
}
}
// assign new positions
for (it = m_sel.begin<Vertex>(); it != it_end; ++it)
{
m_aaPos[*it] = newPos.front();
newPos.pop();
}
}
}
bool MorphoGen::is_outside_spine_shaft(Vertex* v, const vector3& center, number radius)
{
vector3* coord = &m_aaPos[v];
number subtractZDistSq = center.coord(2) - coord->coord(2);
subtractZDistSq = subtractZDistSq*subtractZDistSq;
number distSqXY1 = VecDistanceSq(center, *coord) - subtractZDistSq;
return coord->coord(2) < 0 || distSqXY1 > radius*radius;
}
bool MorphoGen::is_cut_by_spine_shaft
(
Face* f,
const vector3& center,
number radius,
std::vector<Edge*>& outCutEdges,
std::vector<size_t>& outCutEdgeIndices,
std::vector<vector3>& outCutPositions
)
{
outCutEdges.clear();
outCutEdgeIndices.clear();
outCutPositions.clear();
size_t nEdges = f->num_edges();
for (size_t i = 0; i < nEdges; ++i)
{
const EdgeDescriptor& ed = f->edge_desc(i);
bool outside = is_outside_spine_shaft(ed.vertex(0), center, radius);
if (outside != is_outside_spine_shaft(ed.vertex(1), center, radius))
{
// this edge is cut, find concrete edge in grid
typedef Grid::traits<Edge>::secure_container edge_list_type;
edge_list_type el;
m_grid.associated_elements(el, f);
size_t el_sz = el.size();
for (size_t e = 0; e < el_sz; ++e)
{
if (CompareVertices(el[e], &ed))
{
outCutEdges.push_back(el[e]);
outCutEdgeIndices.push_back(i);
break;
}
}
// calculate cut position
// a quadratic equation needs to be solved here:
// || v1 + a*(v2-v1) - x ||^2 = r^2
vector2 v2minusv1;
v2minusv1.coord(0) = m_aaPos[ed.vertex(1)].coord(0) - m_aaPos[ed.vertex(0)].coord(0);
v2minusv1.coord(1) = m_aaPos[ed.vertex(1)].coord(1) - m_aaPos[ed.vertex(0)].coord(1);
vector2 v1minusCenter;
v1minusCenter.coord(0) = m_aaPos[ed.vertex(0)].coord(0) - center.coord(0);
v1minusCenter.coord(1) = m_aaPos[ed.vertex(0)].coord(1) - center.coord(1);
number scProd = VecProd(v2minusv1, v1minusCenter);
number dist12Sq = VecProd(v2minusv1, v2minusv1);
number dist1CenterSq = VecProd(v1minusCenter, v1minusCenter);
number localCoord = - scProd;
if (localCoord < 0)
localCoord += sqrt(scProd*scProd - (dist1CenterSq-radius*radius)*dist12Sq);
else
localCoord -= sqrt(scProd*scProd - (dist1CenterSq-radius*radius)*dist12Sq);
localCoord /= dist12Sq;
outCutPositions.push_back(vector3());
VecScaleAdd(outCutPositions.back(), (1.0-localCoord), m_aaPos[ed.vertex(0)],
localCoord, m_aaPos[ed.vertex(1)]);
}
}
return outCutEdges.size();
}
void MorphoGen::graft_spine()
{
typedef Grid::traits<Edge>::secure_container edge_list;
typedef Grid::traits<Face>::secure_container face_list;
m_sel.clear();
// find the face nearest do the anchor point of the spine
vector3 anchorPoint(0.0);
anchorPoint.coord(2) = DENDRITE_RADIUS;
Face* anchorFace = FindClosestByCoordinate<Face>(anchorPoint, m_grid.begin<Face>(), m_grid.end<Face>(), m_aaPos);
UG_COND_THROW(!anchorFace, "Could not find face near anchor point for spine.");
// now search neighbors until one is found that is cut by the spine shaft's circumcircle
m_grid.begin_marking();
std::queue<Face*> searchQueue;
m_grid.mark(anchorFace);
searchQueue.push(anchorFace);
anchorFace = NULL;
std::vector<Edge*> cutEdges;
std::vector<size_t> cutEdgeIndices;
std::vector<vector3> cutPositions;
while (!searchQueue.empty())
{
Face* f = searchQueue.front();
searchQueue.pop();
if (is_cut_by_spine_shaft(f, anchorPoint, SPINE_NECK_RADIUS, cutEdges, cutEdgeIndices, cutPositions))
{
anchorFace = f;
while (!searchQueue.empty()) searchQueue.pop();
break;
}
// push neighboring faces to queue
edge_list el;
m_grid.associated_elements(el, f);
size_t el_sz = el.size();
for (size_t e = 0; e < el_sz; ++e)
{
face_list fl;
m_grid.associated_elements(fl, el[e]);
size_t fl_sz = fl.size();
for (size_t f1 = 0; f1 < fl_sz; ++f1)
{
if (!m_grid.is_marked(fl[f1]))
{
m_grid.mark(fl[f1]);
searchQueue.push(fl[f1]);
}
}
}
}
m_grid.end_marking();
UG_COND_THROW(!anchorFace, "No face intersecting with spine cylinder could be found.");
// iterating along the cutting border:
// replace cut face by proper elements realizing the cutting border;
int oldDefSI = m_sh.get_default_subset_index();
m_sh.set_default_subset_index(MEM_OUTER_BND_SI);
UG_COND_THROW(cutEdges.size() != 2, "Number of cut edges is not exactly 2.");
Edge* firstEdge = cutEdges[0];
Face* nextFace = NULL;
Vertex* firstVertex;
Vertex* v5; // new vertex backwards
Vertex* v6; // new vertex forwards
while (true)
{
bool firstStep = cutEdges[0] == firstEdge;
bool lastStep = cutEdges[1] == firstEdge;
// save next face
face_list fl;
m_grid.associated_elements(fl, cutEdges[1]);
size_t fl_sz = fl.size();
for (size_t f = 0; f < fl_sz; ++f)
{
if (fl[f] != anchorFace)
{
nextFace = fl[f];
break;
}
}
// get vertices (to ensure they are in the rifght order: use descriptors)
Vertex* v1 = anchorFace->edge_desc(cutEdgeIndices[0]).vertex(0);
Vertex* v2 = anchorFace->edge_desc(cutEdgeIndices[0]).vertex(1);
Vertex* v3 = anchorFace->edge_desc(cutEdgeIndices[1]).vertex(0);
Vertex* v4 = anchorFace->edge_desc(cutEdgeIndices[1]).vertex(1);
// position new vertices
if (firstStep)
{
firstVertex = v5 = *m_grid.create<RegularVertex>();
m_aaPos[v5] = cutPositions[0];
}
else v5 = v6;
if (!lastStep)
{
v6 = *m_grid.create<RegularVertex>();
m_aaPos[v6] = cutPositions[1];
}
else v6 = firstVertex;
// create new faces
Face* circleFace; // is to point to a face at the circle rim
switch ((cutEdgeIndices[1] - cutEdgeIndices[0] + 4) % 4)
{
case 2: // opposing sides
{
// cut into two quadrilaterals
m_grid.create<Quadrilateral>(QuadrilateralDescriptor(v1, v5, v6, v4));
circleFace = *m_grid.create<Quadrilateral>(QuadrilateralDescriptor(v5, v2, v3, v6));
break;
}
case 3: // edges must be 0 and 3
{
// cut into four triangles
Vertex* v7 = anchorFace->vertex((cutEdgeIndices[0]+2)%4); // missing vertex of quad
circleFace = *m_grid.create<Triangle>(TriangleDescriptor(v1, v5, v6));
m_grid.create<Triangle>(TriangleDescriptor(v2, v7, v5));
m_grid.create<Triangle>(TriangleDescriptor(v7, v3, v6));
m_grid.create<Triangle>(TriangleDescriptor(v5, v7, v6));
break;
}
case 1:
{
// cut into four triangles
Vertex* v7 = anchorFace->vertex((cutEdgeIndices[1]+2)%4); // missing vertex of quad
m_grid.create<Triangle>(TriangleDescriptor(v1, v5, v7));
circleFace = *m_grid.create<Triangle>(TriangleDescriptor(v3, v6, v5));
m_grid.create<Triangle>(TriangleDescriptor(v4, v7, v6));
m_grid.create<Triangle>(TriangleDescriptor(v5, v6, v7));
break;
}
default: UG_THROW("Invalid cut edge indices: " << cutEdgeIndices[0]
<< ", " << cutEdgeIndices[1] << ".");
}
// select circle edge
EdgeDescriptor ed(v5, v6);
typedef Grid::traits<Edge>::secure_container edge_list_type;
edge_list_type el;
m_grid.associated_elements(el, circleFace);
size_t el_sz = el.size();
for (size_t e = 0; e < el_sz; ++e)
{
if (CompareVertices(el[e], &ed))
{
m_sel.select(el[e]);
break;
}
}
// remove old face and edge
m_grid.erase(anchorFace);
if (!firstStep)
m_grid.erase(cutEdges[0]);
// remove first edge in last step; then break
if (lastStep)
{
m_grid.erase(cutEdges[1]);
break;
}
// prepare next step
Edge* connectingEdge = cutEdges[1];
UG_COND_THROW(!nextFace, "Next face could not be found.");
anchorFace = nextFace;
is_cut_by_spine_shaft(anchorFace, anchorPoint, SPINE_NECK_RADIUS, cutEdges, cutEdgeIndices, cutPositions);
// it should not be possible to have other than 2 cut edges
UG_COND_THROW(cutEdges.size() != 2, "Number of cut edges is not exactly 2.");
// reorder cut edges if need be
if (cutEdges[0] != connectingEdge)
{
std::swap(cutEdges[0], cutEdges[1]);
std::swap(cutEdgeIndices[0], cutEdgeIndices[1]);
std::swap(cutPositions[0], cutPositions[1]);
}
}
m_sh.set_default_subset_index(oldDefSI);
// retain rim edges
std::vector<Edge*> rimEdges(m_sel.edges_begin(), m_sel.edges_end());
// remove faces from inside spine shaft
anchorFace = FindClosestByCoordinate<Face>(anchorPoint, m_grid.begin<Face>(), m_grid.end<Face>(), m_aaPos);
UG_COND_THROW(!anchorFace, "Could not find face near anchor point for spine.");
m_sel.select(anchorFace);
SelectionFill<Face>(m_sel, IsSelected(m_sel));
m_sel.deselect(m_sel.edges_begin(), m_sel.edges_end());
SelectInnerSelectionEdges(m_sel);
SelectInnerSelectionVertices(m_sel);
m_grid.erase(m_sel.begin<Face>(), m_sel.end<Face>());
m_grid.erase(m_sel.begin<Edge>(), m_sel.end<Edge>());
m_grid.erase(m_sel.begin<Vertex>(), m_sel.end<Vertex>());
// regularize rim (kind of Laplacian smoothing along rim)
m_sel.select(rimEdges.begin(), rimEdges.end());
SelectAssociatedVertices(m_sel, m_sel.begin<Edge>(), m_sel.end<Edge>());
std::vector<Vertex*> rimVerts(m_sel.begin<Vertex>(), m_sel.end<Vertex>());
std::vector<vector3> rimCoordsNew(rimVerts.size());
size_t nVrt = rimVerts.size();
edge_list el;
for (size_t i = 0; i < 8; ++i)
{
for (size_t rvi = 0; rvi < nVrt; ++rvi)
{
Vertex* v = rimVerts[rvi];
// find connecting rim edges
Edge* connEdge[2];
size_t foundConnEdges = 0;
m_grid.associated_elements(el, v);
size_t el_sz = el.size();
for (size_t e = 0; e < el_sz; ++e)
{
if (m_sel.is_selected(el[e]))
{
connEdge[foundConnEdges] = el[e];
++foundConnEdges;
}
}
UG_COND_THROW(foundConnEdges != 2, "Not exactly two connecting rim edges for rim vertex.");
// compare edge lengths
number el0 = EdgeLength(connEdge[0], m_aaPos);
number el1 = EdgeLength(connEdge[1], m_aaPos);
// move vertex into direction of longer edge
Edge* moveTo = el0 >= el1 ? connEdge[0] : connEdge[1];
number fac = el0 >= el1 ? (el0-el1)/(4.0*el0) : (el1-el0)/(4.0*el1);
Vertex* opp = GetOpposingSide(m_grid, moveTo, v);
VecScaleAdd(rimCoordsNew[rvi], 1.0-fac, m_aaPos[v], fac, m_aaPos[opp]);
// shift radially to achieve correct (x-y) distance
el0 = rimCoordsNew[rvi].coord(0) - anchorPoint.coord(0);
el1 = rimCoordsNew[rvi].coord(1) - anchorPoint.coord(1);
el0 = sqrt(el0*el0 + el1*el1);
fac = SPINE_NECK_RADIUS / el0;
VecScaleAdd(rimCoordsNew[rvi], 1.0-fac, anchorPoint, fac, rimCoordsNew[rvi]);
// finally, shift z coordinate to ensure vertex is inside original face
// to do that solve: v + k*e1 + l*e2 = w + m*(0, 0, -1)
// with e1, e2being the two vectors defining the face associated to long edge
// and w being the current new position of v
face_list fl;
m_grid.associated_elements(fl, moveTo);
UG_COND_THROW(fl.size() != 1, "Not exactly one face associated to rim edge.")
Face* rimFace = fl[0];
const EdgeDescriptor& ed1 = rimFace->edge_desc(0);
const EdgeDescriptor& ed2 = rimFace->edge_desc(1);
vector3 e1, e2;
VecScaleAdd(e1, 1.0, m_aaPos[ed1.vertex(1)], -1.0, m_aaPos[ed1.vertex(0)]);
VecScaleAdd(e2, 1.0, m_aaPos[ed2.vertex(1)], -1.0, m_aaPos[ed2.vertex(0)]);
if (fabs(e2.coord(1)) < 1e-4*fabs(e2.coord(0))) // ensure diagonal is non-zero
std::swap(e1, e2);
vector3 diff;
VecScaleAdd(diff, 1.0, rimCoordsNew[rvi], -1.0, m_aaPos[v]);
number k = (e2.coord(1) * diff.coord(0) - e2.coord(0) * diff.coord(1))
/ (e2.coord(1) * e1.coord(0) - e2.coord(0) * e1.coord(1));
number l = (diff.coord(1) - k*e1.coord(1)) / e2.coord(1);
number m = diff.coord(2) - k*e1.coord(2) - l*e2.coord(2);
rimCoordsNew[rvi].coord(2) -= m;
}
// copy newly calculated positions to attachments
for (size_t rvi = 0; rvi < nVrt; ++rvi)
m_aaPos[rimVerts[rvi]] = rimCoordsNew[rvi];
}
// remove short edges
// TODO: replace this calculation by member: m_elemLength
number arc_length = 2.0 * PI / (number) m_dendriteRimVertices;
number numExtrudes = floor(DENDRITE_LENGTH/(2*DENDRITE_RADIUS*sin(arc_length/2.0)));
size_t nExtrudes = std::max((size_t) numExtrudes, (size_t) 1);
number extrude_length = DENDRITE_LENGTH / nExtrudes;
number min_length = SHORT_EDGES_FACTOR * extrude_length;
for (size_t rvi = 0; rvi < nVrt; ++rvi)
{
Vertex* v = rimVerts[rvi];
m_grid.associated_elements(el, v);
size_t el_sz = el.size();
for (size_t e = 0; e < el_sz; ++e)
{
if (!m_sel.is_selected(el[e]))
{
if (EdgeLength(el[e], m_aaPos) < min_length)
{
Vertex* opp = GetOpposingSide(m_grid, el[e], v);
UG_COND_THROW(!opp, "Opposing side not found.");
MergeVertices(m_grid, v, opp);
// edge list might be invalid after merge
m_grid.associated_elements(el, v);
el_sz = el.size();
e = 0;
}
}
}
}
// extrude twice (with reduced length)
std::vector<Vertex*> vrts;
vrts.assign(m_sel.vertices_begin(), m_sel.vertices_end());
std::vector<Edge*> edges;
edges.assign(m_sel.edges_begin(), m_sel.edges_end());
UG_COND_THROW(!edges.size(), "No rim edges present.");
extrude_length = EdgeLength(edges[0], m_aaPos);
numExtrudes = floor(SPINE_NECK_LENGTH / extrude_length);
nExtrudes = std::max((size_t) numExtrudes, (size_t) 1);
extrude_length = SPINE_NECK_LENGTH / nExtrudes;
vector3 extrudeDir(0.0);
extrudeDir.coord(2) = 0.8*extrude_length;
Extrude(m_grid, &vrts, &edges, NULL, extrudeDir, m_aaPos, EO_CREATE_FACES, NULL);
Extrude(m_grid, &vrts, &edges, NULL, extrudeDir, m_aaPos, EO_CREATE_FACES, NULL);
// save current spine vertices for later usage in other methods
m_tmpSpineEdges = edges;
// project to highest z coordinate in selection
size_t sz = vrts.size();
number maxZ = 0.0;
for (size_t i = 0; i < sz; ++i)
maxZ = std::max(maxZ, m_aaPos[vrts[i]].coord(2));
for (size_t i = 0; i < sz; ++i)
m_aaPos[vrts[i]].coord(2) = maxZ;
// smoothing of branching point
m_sel.deselect(vrts.begin(), vrts.end());
smooth_branching_point(0.25, 8, anchorPoint);
// remove short edges again, but this time merge at other vertex
// TODO: replace this calculation by member: m_elemLength
for (size_t rvi = 0; rvi < nVrt; ++rvi)
{
Vertex* v = rimVerts[rvi];
m_grid.associated_elements(el, v);
size_t el_sz = el.size();
for (size_t e = 0; e < el_sz; ++e)
{
if (!m_sel.is_selected(el[e]))
{
if (EdgeLength(el[e], m_aaPos) < min_length)
{
Vertex* opp = GetOpposingSide(m_grid, el[e], v);
UG_COND_THROW(!opp, "Opposing side not found.");
MergeVertices(m_grid, opp, v);
v = opp;
// edge list might be invalid after merge
m_grid.associated_elements(el, v);
el_sz = el.size();
e = 0;
}
}
}
}
// extrude to full spine neck length
extrude_length = EdgeLength(edges[0], m_aaPos);
number rest_length = SPINE_NECK_LENGTH - (maxZ - DENDRITE_RADIUS);
numExtrudes = floor(rest_length / extrude_length);
nExtrudes = std::max((size_t) numExtrudes, (size_t) 1);
extrude_length = rest_length / nExtrudes;
extrudeDir.coord(2) = extrude_length;
for (size_t i = 0; i < nExtrudes; ++i)
Extrude(m_grid, &vrts, &edges, NULL, extrudeDir, m_aaPos, EO_CREATE_FACES, NULL);
// make spine head
// calculate center, current angle
number curr_z = DENDRITE_RADIUS + SPINE_NECK_LENGTH;
number z_center = curr_z + sqrt(SPINE_HEAD_RADIUS*SPINE_HEAD_RADIUS - SPINE_NECK_RADIUS*SPINE_NECK_RADIUS);
number curr_angle = asin(SPINE_NECK_RADIUS/SPINE_HEAD_RADIUS);
number step_angle = (PI - curr_angle) / 5.0;
number curr_radius = SPINE_NECK_RADIUS;
for (size_t i = 0; i < 5; ++i)
{
curr_angle += step_angle;
number dz = -curr_z;
curr_z = z_center - SPINE_HEAD_RADIUS*cos(curr_angle);
dz += curr_z;
number fac_rad = 1.0 / curr_radius;
curr_radius = SPINE_HEAD_RADIUS*sin(curr_angle);
fac_rad *= curr_radius;
// extrude in z-direction
extrudeDir.coord(2) = dz;
Extrude(m_grid, &vrts, &edges, NULL, extrudeDir, m_aaPos, EO_CREATE_FACES, NULL);
// scale around center of selection
vector3 center = CalculateCenter(vrts.begin(), vrts.end(), m_aaPos);
size_t nVrt = vrts.size();
for (size_t i = 0; i < nVrt; ++i)
{
vector3& v = m_aaPos[vrts[i]];
VecSubtract(v, v, center);
VecScale(v, v, fac_rad);
VecAdd(v, v, center);
}
}
// close spine head by merging top vertices
Vertex* v = MergeMultipleVertices(m_grid, vrts.begin(), vrts.end());
m_tmpHeadHeight = m_aaPos[v].z() - (SPINE_NECK_LENGTH + DENDRITE_RADIUS);
// repair orientation
FixFaceOrientation(m_grid, m_grid.begin<Face>(), m_grid.end<Face>());
// assign PSD subset
m_sel.clear<Vertex>();
m_sel.clear<Edge>();
m_sel.clear<Face>();
m_sel.select(v);
ExtendSelection(m_sel, 1);
SelectAssociatedEdges(m_sel, m_sel.begin<Face>(), m_sel.end<Face>());
SelectAssociatedVertices(m_sel, m_sel.begin<Edge>(), m_sel.end<Edge>());
m_sh.assign_subset(m_sel.begin<Vertex>(), m_sel.end<Vertex>(), PSD_OUTER_SI);
m_sh.assign_subset(m_sel.begin<Edge>(), m_sel.end<Edge>(), PSD_OUTER_SI);
m_sh.assign_subset(m_sel.begin<Face>(), m_sel.end<Face>(), PSD_OUTER_SI);
}
void MorphoGen::defect_for_filament_distribution
(
const DenseVector<VariableArray1<number> >& bndPos,
const DenseVector<VariableArray1<number> >& solNew,
const DenseVector<VariableArray1<number> >& solOld,
DenseVector<VariableArray1<number> >& defOut,
number dt
) const
{
// reset defect
defOut = 0.0;
size_t nFil = solNew.size() / 4;
size_t nBnd = bndPos.size() / 2;
for (size_t i = 0; i < nFil; ++i)
{
const number& xi1 = solNew[4*i];
const number& xi2 = solNew[4*i+1];
const number& vi1 = solNew[4*i+2];
const number& vi2 = solNew[4*i+3];
number& dxi1 = defOut[4*i];
number& dxi2 = defOut[4*i+1];
number& dvi1 = defOut[4*i+2];
number& dvi2 = defOut[4*i+3];
// force, coupling with other filaments
for (size_t j = 0; j < nFil; ++j)
{
if (i == j) continue;
const number& xj1 = solNew[4*j];
const number& xj2 = solNew[4*j+1];
// distance
number dist3 = 0.0;
number diffX = xi1-xj1;
dist3 += diffX*diffX;
number diffY = xi2-xj2;
dist3 += diffY*diffY;
dist3 = sqrt(dist3);
dist3 = 1.0 / (dist3*dist3*dist3);
dvi1 += diffX * dist3;
dvi2 += diffY * dist3;
}
// force, coupling with boundary
for (size_t k = 0; k < nBnd; ++k)
{
// distance
number dist3 = 0.0;