forked from bldeng/ParaHeat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EdgeBasedGeodesicSolver.cpp
817 lines (686 loc) · 24.7 KB
/
EdgeBasedGeodesicSolver.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
// BSD 3-Clause License
//
// Copyright (c) 2019, Jiong Tao, Bailin Deng, Yue Peng
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "EdgeBasedGeodesicSolver.h"
#include "surface_mesh/IO.h"
#include "OMPHelper.h"
#include <iostream>
#include <utility>
#include <limits>
EdgeBasedGeodesicSolver::EdgeBasedGeodesicSolver()
: model_scaling_factor(1.0),
bfs_laplacian_coef(NULL),
current_SX(NULL),
prev_SX(NULL),
need_compute_residual_norms(false),
n_vertices(0),
n_faces(0),
n_edges(0),
n_halfedges(0),
n_interior_edges(0),
iter_num(0),
primal_residual_sqr_norm(0),
dual_residual_sqr_norm(0),
primal_residual_sqr_norm_threshold(0),
dual_residual_sqr_norm_threshold(0),
output_progress(false),
optimization_converge(false),
optimization_end(false) {
}
const Eigen::VectorXd& EdgeBasedGeodesicSolver::get_distance_values() {
return geod_dist_values;
}
bool EdgeBasedGeodesicSolver::solve(const char *mesh_file,
const Parameters& para) {
param = para;
std::cout << "Reading triangle mesh......" << std::endl;
if (!load_input(mesh_file)) {
return false;
}
normalize_mesh();
std::cout << "Initialize BFS path......" << std::endl;
Timer timer;
Timer::EventID start = timer.get_time();
// Precompute breadth-first propagation order
init_bfs_paths();
std::cout << "Gauss-Seidel initilization of gradients......" << std::endl;
Timer::EventID before_GS = timer.get_time();
gauss_seidel_init_gradients();
Timer::EventID before_ADMM = timer.get_time();
std::cout << "ADMM solver for integrable gradients......" << std::endl;
prepare_integrate_geodesic_distance();
compute_integrable_gradients();
Timer::EventID after_ADMM = timer.get_time();
std::cout << "Recovery of geodesic distance......" << std::endl;
integrate_geodesic_distance();
Timer::EventID end = timer.get_time();
std::cout << std::endl;
std::cout << "====== Timing ======" << std::endl;
std::cout << "Pre-computation of BFS paths: "
<< timer.elapsed_time(start, before_GS) << " seconds" << std::endl;
std::cout << "Gauss-Seidel initialization of gradients: "
<< timer.elapsed_time(before_GS, before_ADMM) << " seconds"
<< std::endl;
std::cout << "ADMM solver for integrable gradients: "
<< timer.elapsed_time(before_ADMM, after_ADMM) << " seconds"
<< std::endl;
std::cout << "Integration of gradients: "
<< timer.elapsed_time(after_ADMM, end) << " seconds" << std::endl;
std::cout << "Total time: " << timer.elapsed_time(start, end) << " seconds"
<< std::endl;
return true;
}
void EdgeBasedGeodesicSolver::init_bfs_paths() {
bfs_vertex_list.resize(n_vertices);
bfs_vertex_list.fill(-1);
transition_halfedge_idx.setConstant(n_vertices, -1);
bfs_laplacian_coef_addr.resize(n_vertices + 1);
bfs_laplacian_coef_addr(0) = 0;
// Store source vertices as the first layer
std::vector<bool> visited(n_vertices, false);
std::vector<int> front1 = param.source_vertices, front2;
std::vector<int> *current_front = &front1, *next_front = &front2;
int n_sources = param.source_vertices.size();
std::vector<int> bfs_segment_addr_vec;
bfs_segment_addr_vec.push_back(0);
bfs_segment_addr_vec.push_back(n_sources);
int id = 0;
for (; id < n_sources; ++id) {
int current_source_vtx = param.source_vertices[id];
visited[current_source_vtx] = true;
bfs_vertex_list(id) = current_source_vtx;
bfs_laplacian_coef_addr(id + 1) = bfs_laplacian_coef_addr(id)
+ mesh.valence(MeshType::Vertex(current_source_vtx)) + 1;
}
while (!current_front->empty()) {
next_front->clear();
for (int k = 0; k < static_cast<int>(current_front->size()); ++k) {
MeshType::Vertex vh(current_front->at(k));
MeshType::Halfedge_around_vertex_circulator vhc, vhc_end;
vhc = vhc_end = mesh.halfedges(vh);
do {
MeshType::Halfedge heh = *vhc;
MeshType::Vertex next_vh = mesh.to_vertex(heh);
int next_v = next_vh.idx();
if (!visited[next_v]) {
next_front->push_back(next_v);
bfs_vertex_list(id) = next_v;
// Each segment stores the weights for neighbors and the current vertex for GS update
bfs_laplacian_coef_addr(id + 1) = bfs_laplacian_coef_addr(id)
+ mesh.valence(next_vh) + 1;
transition_halfedge_idx(id) = heh.idx();
id++;
}
visited[next_v] = true;
} while (++vhc != vhc_end);
}
bfs_segment_addr_vec.push_back(
bfs_segment_addr_vec.back() + next_front->size());
std::swap(current_front, next_front);
}
bfs_segment_addr = Eigen::Map < Eigen::VectorXi
> (bfs_segment_addr_vec.data(), bfs_segment_addr_vec.size());
}
bool EdgeBasedGeodesicSolver::load_input(const char* mesh_file) {
if (!surface_mesh::read_mesh(mesh, mesh_file)) {
std::cerr << "Error: unable to read input mesh from the file " << mesh_file
<< std::endl;
return false;
}
mesh.free_memory(); // Free unused memory
n_vertices = mesh.n_vertices();
n_faces = mesh.n_faces();
n_edges = mesh.n_edges();
n_halfedges = mesh.n_halfedges();
if (n_vertices == 0 || n_faces == 0 || n_edges == 0) {
std::cerr << "Error: zero mesh element count " << std::endl;
return false;
}
for (int i = 0; i < static_cast<int>(param.source_vertices.size()); ++i) {
if (param.source_vertices[i] < 0
|| param.source_vertices[i] >= n_vertices) {
std::cerr << "Error: invalid source vertex index "
<< param.source_vertices[i] << std::endl;
return false;
}
}
return true;
}
void EdgeBasedGeodesicSolver::normalize_mesh() {
std::vector<surface_mesh::Point> &pos = mesh.points();
surface_mesh::Point min_coord = pos.front(), max_coord = pos.front();
std::vector<surface_mesh::Point>::iterator iter = pos.begin(), iter_end = pos
.end();
for (++iter; iter != iter_end; ++iter) {
surface_mesh::Point &coord = *iter;
min_coord.minimize(coord);
max_coord.maximize(coord);
}
model_scaling_factor = surface_mesh::norm(max_coord - min_coord);
surface_mesh::Point center_pos = (min_coord + max_coord) * 0.5;
for (iter = pos.begin(); iter != iter_end; ++iter) {
surface_mesh::Point &coord = *iter;
coord -= center_pos;
coord /= model_scaling_factor;
}
}
void EdgeBasedGeodesicSolver::gauss_seidel_init_gradients() {
edge_vector.resize(3, n_edges);
DenseVector edge_sqr_length;
edge_sqr_length.setZero(n_edges);
face_area.resize(n_faces);
int n_halfedges = mesh.n_halfedges();
DenseVector halfedge_halfcot; // Collect the half cotan value for edge halfedge, to be used for computing cotan Laplacian weights
halfedge_halfcot.setZero(n_halfedges);
double step_length = 0;
HeatScalar init_source_val = 1;
VectorHS current_d;
VectorHS temp_d;
VectorHS vertex_area;
int gs_iter = 0;
int segment_count = 0;
int n_segments = 0;
int segment_begin_addr = 0, segment_end_addr = 0;
bool end_gs_loop = false;
bool reset_iter = true;
bool need_check_residual = false;
HeatScalar eps = 0;
VectorHS heatflow_residuals;
OMP_PARALLEL
{
// Compute Laplacian weights
OMP_FOR
for (int i = 0; i < n_edges; ++i) {
// Precompute edge vectors and squared edge length,
// to be used later for computing cotan weights and areas
MeshType::Halfedge heh = mesh.halfedge(MeshType::Edge(i), 0);
Eigen::Vector3d edge_vec = to_eigen_vec3d(
mesh.position(mesh.to_vertex(heh))
- mesh.position(mesh.from_vertex(heh)));
double l2 = edge_vec.squaredNorm();
edge_vector.col(i) = edge_vec;
edge_sqr_length(i) = l2;
}
OMP_SINGLE
{
// Compute heat flow step size
double h = edge_sqr_length.array().sqrt().mean();
step_length = h * h;
}
OMP_FOR
for (int i = 0; i < n_faces; ++i) {
// Compute face areas and half-cotan weights for halfedges
Eigen::Vector3i fh_idx, fe_idx;
Eigen::Vector3d edge_l2;
int k = 0;
MeshType::Halfedge_around_face_circulator fhc, fhc_end;
fhc = fhc_end = mesh.halfedges(MeshType::Face(i));
do {
MeshType::Halfedge heh = *fhc;
fh_idx(k) = heh.idx();
fe_idx(k) = mesh.edge(heh).idx();
edge_l2(k) = edge_sqr_length(fe_idx(k));
k++;
} while (++fhc != fhc_end);
double area = edge_vector.col(fe_idx(0)).cross(edge_vector.col(fe_idx(1)))
.norm() * 0.5;
for (int j = 0; j < 3; ++j) {
halfedge_halfcot(fh_idx(j)) = 0.125
* (edge_l2((j + 1) % 3) + edge_l2((j + 2) % 3) - edge_l2(j)) / area;
}
face_area(i) = area;
}
OMP_SINGLE
{
// Allocate arrays for storing relevant vertices and weights for Laplacian operator at each vertex
edge_sqr_length.resize(0);
int n_laplacian_vertices = n_edges * 2 + n_vertices;
bfs_laplacian_coef = new std::pair<int, double>[n_laplacian_vertices];
vertex_area.setZero(n_vertices);
}
OMP_FOR
for (int i = 0; i < n_vertices; ++i) {
// Compute and store vertex indices and weights for Laplacian operators
int start_addr = bfs_laplacian_coef_addr(i), end_addr =
bfs_laplacian_coef_addr(i + 1);
DenseVector weights;
IndexVector vtx_idx;
int n = end_addr - start_addr;
weights.setZero(n);
vtx_idx.setZero(n);
int v_idx = bfs_vertex_list(i);
MeshType::Vertex vh(v_idx);
int k = 0;
MeshType::Halfedge_around_vertex_circulator vhc, vhc_end;
vhc = vhc_end = mesh.halfedges(vh);
do {
MeshType::Halfedge heh = *vhc;
double w = halfedge_halfcot(heh.idx())
+ halfedge_halfcot(mesh.opposite_halfedge(heh).idx());
vtx_idx(k) = mesh.to_vertex(heh).idx();
weights(k) = w;
k++;
} while (++vhc != vhc_end);
vtx_idx(k) = v_idx;
weights(k) = weights.head(k).sum(); // Store the sum of neighbor weights, to be used for Gauss-Seidel update
weights *= step_length;
double A = 0;
MeshType::Face_around_vertex_circulator vfc, vfc_end;
vfc = vfc_end = mesh.faces(vh);
do {
A += face_area((*vfc).idx());
} while (++vfc != vfc_end);
double vertex_A = A / 3.0;
vertex_area(v_idx) = vertex_A;
weights(k) += vertex_A;
for (int j = start_addr; j < end_addr; ++j) {
bfs_laplacian_coef[j] = std::pair<int, double>(vtx_idx(j - start_addr),
weights(j - start_addr));
}
}
OMP_SINGLE
{
// Set up heat value arrays
halfedge_halfcot.resize(0);
int n_sources = param.source_vertices.size();
HeatScalar total_source_area = 0;
for (int i = 0; i < n_sources; ++i) {
total_source_area += vertex_area(param.source_vertices[i]);
}
init_source_val = std::sqrt(
std::min(HeatScalar(n_vertices) / HeatScalar(n_sources),
vertex_area.sum() / total_source_area));
vertex_area.resize(0);
current_d.setZero(n_vertices);
for (int i = 0; i < n_sources; ++i) {
current_d(param.source_vertices[i]) = init_source_val;
}
n_segments = bfs_segment_addr.size() - 1;
int buffer_size = (Eigen::Map < IndexVector
> (&(bfs_segment_addr[1]), n_segments) - Eigen::Map < IndexVector
> (&(bfs_segment_addr[0]), n_segments)).maxCoeff();
temp_d.setZero(buffer_size);
heatflow_residuals.setZero(n_vertices);
}
compute_heatflow_residual(current_d, init_source_val, heatflow_residuals);
OMP_SINGLE
{
// Rescale heat source values to make the initial residual norm close to 1
HeatScalar init_residual_norm = heatflow_residuals.norm();
eps = std::max(HeatScalar(1e-16),
init_residual_norm * HeatScalar(param.heat_solver_eps));
std::cout << "Initial residual: " << init_residual_norm << ", threshold: "
<< eps << std::endl;
}
}
while (!end_gs_loop) {
OMP_PARALLEL
{
// Gauss-Seidel update of heat values in breadth-first order
OMP_SINGLE
{
segment_begin_addr = bfs_segment_addr(segment_count);
segment_end_addr = bfs_segment_addr(segment_count + 1);
}
OMP_FOR
for (int i = segment_begin_addr; i < segment_end_addr; ++i) {
int lap_coef_begin_addr = bfs_laplacian_coef_addr(i);
int lap_coef_end_addr = bfs_laplacian_coef_addr(i + 1);
HeatScalar new_heat_value = 0;
if (segment_count == 0) { // Check whether the current vertex is a source
new_heat_value += init_source_val;
}
for (int j = lap_coef_begin_addr; j < lap_coef_end_addr - 1; ++j) {
std::pair<int, double> &coef = bfs_laplacian_coef[j];
new_heat_value += current_d(coef.first) * coef.second;
}
temp_d(i - segment_begin_addr) = new_heat_value
/ bfs_laplacian_coef[lap_coef_end_addr - 1].second;
}
OMP_FOR
for (int i = segment_begin_addr; i < segment_end_addr; ++i) {
current_d(bfs_vertex_list(i)) = temp_d(i - segment_begin_addr);
}
OMP_SINGLE
{
segment_count++;
reset_iter = (segment_count == n_segments);
if (reset_iter) {
gs_iter++;
segment_count = 0;
}
end_gs_loop = gs_iter >= param.heat_solver_max_iter;
need_check_residual =
end_gs_loop
|| (reset_iter
&& (gs_iter % param.heat_solver_convergence_check_frequency
== 0));
}
if (need_check_residual) {
compute_heatflow_residual(current_d, init_source_val,
heatflow_residuals);
OMP_SINGLE
{
HeatScalar residual_norm = heatflow_residuals.norm();
std::cout << "Gauss-Seidel iteration " << gs_iter
<< ", current residual: " << residual_norm
<< ", threshold: " << eps << std::endl;
if (residual_norm <= eps) {
end_gs_loop = true;
}
}
}
}
}
OMP_PARALLEL
{
OMP_SINGLE
{
temp_d.resize(0);
heatflow_residuals.resize(0);
vertex_area.resize(0);
delete[] bfs_laplacian_coef;
bfs_laplacian_coef_addr.resize(0);
init_grad.resize(3, n_faces);
}
// Compute initial gradient and get target edge difference.
OMP_FOR
for (int i = 0; i < n_faces; ++i) {
Matrix3HS edge_vecs;
Vector3HS heat_vals;
int k = 0;
MeshType::Halfedge_around_face_circulator fhc, fhc_end;
fhc = fhc_end = mesh.halfedges(MeshType::Face(i));
do {
MeshType::Halfedge heh = *fhc;
MeshType::Edge eh = mesh.edge(heh);
Eigen::Vector3d current_edge = edge_vector.col(eh.idx());
if (mesh.halfedge(eh, 0) != heh) {
current_edge *= -1;
}
edge_vecs(0, k) = HeatScalar(current_edge[0]);
edge_vecs(1, k) = HeatScalar(current_edge[1]);
edge_vecs(2, k) = HeatScalar(current_edge[2]);
heat_vals(k) = current_d(mesh.to_vertex(heh).idx());
++k;
} while (++fhc != fhc_end);
heat_vals.normalize();
edge_vecs.normalize();
Vector3HS N = edge_vecs.col(0).cross(edge_vecs.col(1)).normalized();
Vector3HS V = edge_vecs.col(0) * heat_vals(1)
+ edge_vecs.col(1) * heat_vals(2) + edge_vecs.col(2) * heat_vals(0);
Vector3HS grad_vec = V.cross(N).normalized();
init_grad(0, i) = grad_vec(0);
init_grad(1, i) = grad_vec(1);
init_grad(2, i) = grad_vec(2);
}
}
}
void EdgeBasedGeodesicSolver::compute_heatflow_residual(
const VectorHS &heat_values, HeatScalar init_source_val,
VectorHS &residuals) {
OMP_FOR
for (int i = 0; i < n_vertices; ++i) {
int lap_coef_begin_addr = bfs_laplacian_coef_addr(i);
int lap_coef_end_addr = bfs_laplacian_coef_addr(i + 1);
HeatScalar res = 0;
if (i < static_cast<int>(param.source_vertices.size())) { // Check whether the current vertex is a source
res += init_source_val;
}
for (int j = lap_coef_begin_addr; j < lap_coef_end_addr; ++j) {
std::pair<int, double> &coef = bfs_laplacian_coef[j];
res += heat_values(coef.first) * coef.second
* ((j == (lap_coef_end_addr - 1)) ? (-1) : 1);
}
residuals(i) = res;
}
}
void EdgeBasedGeodesicSolver::prepare_integrate_geodesic_distance() {
transition_from_vtx.setConstant(n_vertices, -1);
transition_edge_idx.setConstant(n_vertices, -1);
IndexVector num_rows;
num_rows.setZero(n_edges);
Z.resize(3 * n_faces);
S.resize(3, n_faces);
Q.resize(3, n_faces);
edges_Y_index.setConstant(2, n_edges, -1); // the set of rows in Y associated with each edge.
OMP_PARALLEL
{
// Set up incident relation between edges and faces.
OMP_SINGLE
{
for (int i = 0; i < n_faces; ++i) {
MeshType::Face f = MeshType::Face(i);
MeshType::Halfedge_around_face_circulator fhc, fhc_end;
fhc = fhc_end = mesh.halfedges(f);
int k = 0;
do {
MeshType::Edge e = mesh.edge(*fhc);
int edge_index = mesh.edge(*fhc).idx();
Eigen::Vector3d e_vector = to_eigen_vec3d(
mesh.position(mesh.from_vertex(*fhc))
- mesh.position(mesh.to_vertex(*fhc)));
if (*fhc == mesh.halfedge(e, 0)) // the halfedge with index 0 as orientation halfedge
{
Q(k, i) = 1;
Z(3 * i + k) = init_grad.col(i).dot(e_vector);
} else {
Q(k, i) = -1;
Z(3 * i + k) = init_grad.col(i).dot(-e_vector);
}
S(k, i) = edge_index;
edges_Y_index(num_rows(edge_index)++, edge_index) = 3 * i + k;
k++;
} while (++fhc != fhc_end);
}
}
// Set up transition vector needed in recovering distance step.
OMP_FOR
for (int i = 0; i < n_vertices; ++i) {
MeshType::Halfedge heh(transition_halfedge_idx(i));
if (heh.is_valid()) {
MeshType::Vertex from_vh = mesh.from_vertex(heh);
MeshType::Edge e = mesh.edge(heh);
transition_from_vtx(i) = from_vh.idx();
if (heh == mesh.halfedge(e, 0)) {
transition_edge_idx(i) = -e.idx() - 1;
} else {
transition_edge_idx(i) = e.idx();
}
}
}
OMP_SINGLE
{
mesh.clear();
transition_halfedge_idx.resize(0);
init_grad.resize(3, 0);
D.setZero(3 * n_faces);
X.resize(n_edges);
Y.setZero(3 * n_faces);
SX1.setZero(3 * n_faces);
SX2.setZero(3 * n_faces);
current_SX = &SX1;
prev_SX = &SX2;
primal_residual_sqr_norm_threshold = param.grad_solver_eps
* param.grad_solver_eps;
dual_residual_sqr_norm_threshold = param.grad_solver_eps
* param.grad_solver_eps;
(*prev_SX) = (*current_SX);
}
// Initialize X.
OMP_FOR
for (int i = 0; i < n_edges; ++i) {
int n_var = 0;
double r = 0;
for (int j = 0; j < 2; ++j) {
int index = edges_Y_index(j, i);
if (index >= 0) {
r += Z(index);
n_var++;
}
}
X(i) = r / n_var;
}
// Initialize SX.
OMP_FOR
for (int i = 0; i < n_faces; ++i) {
(*prev_SX)(3 * i) = X(S(0, i));
(*prev_SX)(3 * i + 1) = X(S(1, i));
(*prev_SX)(3 * i + 2) = X(S(2, i));
}
}
}
void EdgeBasedGeodesicSolver::compute_integrable_gradients() {
optimization_end = false;
iter_num = 0;
OMP_PARALLEL
{
while (!optimization_end) {
update_Y();
update_X();
update_dual_variables();
}
}
}
void EdgeBasedGeodesicSolver::integrate_geodesic_distance() {
geod_dist_values.setZero(n_vertices);
int n_segments = bfs_segment_addr.size() - 1;
int segment_count = 1; // We update the distance values strting from the second layer of BFS vertex list
int segment_begin_addr, segment_end_addr;
bool end_propagation = false;
OMP_PARALLEL
{
while (!end_propagation) {
OMP_SINGLE
{
segment_begin_addr = bfs_segment_addr(segment_count);
segment_end_addr = bfs_segment_addr(segment_count + 1);
}
OMP_FOR
for (int i = segment_begin_addr; i < segment_end_addr; ++i) {
double from_d = geod_dist_values(transition_from_vtx(i));
int edge_index = transition_edge_idx(i);
if (edge_index >= 0) {
geod_dist_values(bfs_vertex_list(i)) = from_d + X(edge_index);
} else {
geod_dist_values(bfs_vertex_list(i)) = from_d - X(-(edge_index + 1));
}
}
OMP_SINGLE
{
segment_count++;
end_propagation = (segment_count >= n_segments);
}
}
}
// Recover geodesic distance in the original scale
geod_dist_values *= model_scaling_factor;
}
void EdgeBasedGeodesicSolver::update_Y() {
OMP_FOR
for (int i = 0; i < n_faces; ++i) {
Eigen::Vector3d y = prev_SX->segment(3 * i, 3) - D.segment(3 * i, 3);
Eigen::Vector3d q = Q.col(i).cast<double>();
Y.segment(3 * i, 3) = y - 1.0 / 3 * q.dot(y) * q;
}
}
void EdgeBasedGeodesicSolver::update_X() {
OMP_FOR
for (int i = 0; i < n_edges; ++i) {
int n_aux_var = 0;
double r = 0;
for (int j = 0; j < 2; ++j) {
int index = edges_Y_index(j, i);
if (index >= 0) {
r += param.penalty * (Y(index) + D(index)) + Z(index);
n_aux_var++;
}
}
X(i) = r / ((param.penalty + 1) * n_aux_var);
}
}
void EdgeBasedGeodesicSolver::update_dual_variables() {
OMP_FOR
for (int i = 0; i < n_faces; ++i) {
(*current_SX)(3 * i) = X(S(0, i));
(*current_SX)(3 * i + 1) = X(S(1, i));
(*current_SX)(3 * i + 2) = X(S(2, i));
}
OMP_SINGLE
{
need_compute_residual_norms = ((iter_num + 1)
% param.grad_solver_convergence_check_frequency == 0);
}
OMP_SECTIONS
{
OMP_SECTION
{
if (need_compute_residual_norms) {
primal_residual_sqr_norm = (Y - (*current_SX)).squaredNorm();
}
}
OMP_SECTION
{
if (need_compute_residual_norms) {
dual_residual_sqr_norm = ((*current_SX) - (*prev_SX)).squaredNorm()
* param.penalty * param.penalty;
}
}
OMP_SECTION
{
D += Y - (*current_SX);
}
}
OMP_SINGLE
{
iter_num++;
optimization_converge = need_compute_residual_norms
&& (primal_residual_sqr_norm <= primal_residual_sqr_norm_threshold
&& dual_residual_sqr_norm <= dual_residual_sqr_norm_threshold);
optimization_end = optimization_converge
|| iter_num >= param.grad_solver_max_iter;
output_progress = need_compute_residual_norms
&& (iter_num % param.grad_solver_output_frequency == 0);
if (optimization_converge) {
std::cout << "Solver converged." << std::endl;
} else if (optimization_end) {
std::cout << "Maximum number of iterations reached." << std::endl;
}
if (output_progress || optimization_end) {
std::cout << "Iteration " << iter_num << ":" << std::endl;
std::cout << "Primal residual squared norm: " << primal_residual_sqr_norm
<< ", threshold:" << primal_residual_sqr_norm_threshold
<< std::endl;
std::cout << "Dual residual squared norm: " << dual_residual_sqr_norm
<< ", threshold:" << dual_residual_sqr_norm_threshold
<< std::endl;
}
std::swap(current_SX, prev_SX);
}
}