Graphviz 16.1.3~dev.20261128.0221
Loading...
Searching...
No Matches
stress.c
Go to the documentation of this file.
1/*************************************************************************
2 * Copyright (c) 2011 AT&T Intellectual Property
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v2.0
5 * which accompanies this distribution, and is available at
6 * https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.html
7 *
8 * Contributors: Details at https://graphviz.org
9 *************************************************************************/
10
11#include "config.h"
12
13#include <float.h>
14#include <neatogen/neato.h>
15#include <neatogen/dijkstra.h>
16#include <neatogen/bfs.h>
17#include <neatogen/pca.h>
18#include <neatogen/matrix_ops.h>
19#include <neatogen/conjgrad.h>
21#include <neatogen/kkutils.h>
22#include <neatogen/stress.h>
23#include <math.h>
24#include <stdbool.h>
25#include <stdlib.h>
26#include <time.h>
27#include <util/alloc.h>
28
29// the terms in the stress energy are normalized by dᵢⱼ¯²
30
31/* dimensionality of subspace; relevant
32 * when optimizing within subspace)
33 */
34#define stress_pca_dim 50
35
36 /* a structure used for storing sparse distance matrix */
37typedef struct {
38 size_t nedges;
39 int *edges;
42} dist_data;
43
44static double compute_stressf(float **coords, float *lap, int dim, int n, int exp)
45{
46 /* compute the overall stress */
47
48 int i, j, l, neighbor, count;
49 double sum, dist, Dij;
50 sum = 0;
51 for (count = 0, i = 0; i < n - 1; i++) {
52 count++; /* skip diagonal entry */
53 for (j = 1; j < n - i; j++, count++) {
54 dist = 0;
55 neighbor = i + j;
56 for (l = 0; l < dim; l++) {
57 dist +=
58 (coords[l][i] - coords[l][neighbor]) * (coords[l][i] -
59 coords[l]
60 [neighbor]);
61 }
62 dist = sqrt(dist);
63 if (exp == 2) {
64 Dij = 1.0 / sqrt(lap[count]);
65 sum += (Dij - dist) * (Dij - dist) * lap[count];
66 } else {
67 Dij = 1.0 / lap[count];
68 sum += (Dij - dist) * (Dij - dist) * lap[count];
69 }
70 }
71 }
72
73 return sum;
74}
75
76static double
77compute_stress1(double **coords, dist_data * distances, int dim, int n, int exp)
78{
79 /* compute the overall stress */
80
81 int i, l, node;
82 double sum, dist, Dij;
83 sum = 0;
84 if (exp == 2) {
85 for (i = 0; i < n; i++) {
86 for (size_t j = 0; j < distances[i].nedges; j++) {
87 node = distances[i].edges[j];
88 if (node <= i) {
89 continue;
90 }
91 dist = 0;
92 for (l = 0; l < dim; l++) {
93 dist +=
94 (coords[l][i] - coords[l][node]) * (coords[l][i] -
95 coords[l]
96 [node]);
97 }
98 dist = sqrt(dist);
99 Dij = distances[i].edist[j];
100 sum += (Dij - dist) * (Dij - dist) / (Dij * Dij);
101 }
102 }
103 } else {
104 for (i = 0; i < n; i++) {
105 for (size_t j = 0; j < distances[i].nedges; j++) {
106 node = distances[i].edges[j];
107 if (node <= i) {
108 continue;
109 }
110 dist = 0;
111 for (l = 0; l < dim; l++) {
112 dist +=
113 (coords[l][i] - coords[l][node]) * (coords[l][i] -
114 coords[l]
115 [node]);
116 }
117 dist = sqrt(dist);
118 Dij = distances[i].edist[j];
119 sum += (Dij - dist) * (Dij - dist) / Dij;
120 }
121 }
122 }
123
124 return sum;
125}
126
127/* Initialize node coordinates. If the node already has
128 * a position, use it.
129 * Return true if some node is fixed.
130 */
131int initLayout(int n, int dim, double **coords, node_t **nodes) {
132 node_t *np;
133 double *xp;
134 double *yp;
135 double *pt;
136 int i, d;
137 int pinned = 0;
138
139 xp = coords[0];
140 yp = coords[1];
141 for (i = 0; i < n; i++) {
142 np = nodes[i];
143 if (hasPos(np)) {
144 pt = ND_pos(np);
145 *xp++ = *pt++;
146 *yp++ = *pt++;
147 if (dim > 2) {
148 for (d = 2; d < dim; d++)
149 coords[d][i] = *pt++;
150 }
151 if (isFixed(np))
152 pinned = 1;
153 } else {
154 *xp++ = drand48();
155 *yp++ = drand48();
156 if (dim > 2) {
157 for (d = 2; d < dim; d++)
158 coords[d][i] = drand48();
159 }
160 }
161 }
162
163 for (d = 0; d < dim; d++)
164 orthog1(n, coords[d]);
165
166 return pinned;
167}
168
169float *circuitModel(vtx_data * graph, int nG)
170{
171 int i, j, rv, count;
172 float *Dij = gv_calloc(nG * (nG + 1) / 2, sizeof(float));
173 double **Gm;
174 double **Gm_inv;
175
176 Gm = new_array(nG, nG, 0.0);
177 Gm_inv = new_array(nG, nG, 0.0);
178
179 /* set non-diagonal entries */
180 if (graph->ewgts) {
181 for (i = 0; i < nG; i++) {
182 for (size_t e = 1; e < graph[i].nedges; e++) {
183 j = graph[i].edges[e];
184 /* conductance is 1/resistance */
185 Gm[i][j] = Gm[j][i] = -1.0 / graph[i].ewgts[e]; /* negate */
186 }
187 }
188 } else {
189 for (i = 0; i < nG; i++) {
190 for (size_t e = 1; e < graph[i].nedges; e++) {
191 j = graph[i].edges[e];
192 /* conductance is 1/resistance */
193 Gm[i][j] = Gm[j][i] = -1.0; /* ewgts are all 1 */
194 }
195 }
196 }
197
198 rv = solveCircuit(nG, Gm, Gm_inv);
199
200 if (rv) {
201 float v;
202 count = 0;
203 for (i = 0; i < nG; i++) {
204 for (j = i; j < nG; j++) {
205 if (i == j)
206 v = 0.0;
207 else
208 v = (float) (Gm_inv[i][i] + Gm_inv[j][j] -
209 2.0 * Gm_inv[i][j]);
210 Dij[count++] = v;
211 }
212 }
213 } else {
214 free(Dij);
215 Dij = NULL;
216 }
217 free_array(Gm);
218 free_array(Gm_inv);
219 return Dij;
220}
221
222/* Optimization of the stress function using sparse distance matrix, within a vector-space
223 * Fastest and least accurate method
224 *
225 * NOTE: We use integral shortest path values here, assuming
226 * this is only to get an initial layout. In general, if edge lengths
227 * are involved, we may end up with 0 length edges.
228 */
229static int sparse_stress_subspace_majorization_kD(vtx_data * graph, /* Input graph in sparse representation */
230 int n, /* Number of nodes */
231 double **coords, /* coordinates of nodes (output layout) */
232 int dim, /* dimensionality of layout */
233 int smart_ini, /* smart initialization */
234 int exp, /* scale exponent */
235 int reweight_graph, /* difference model */
236 int n_iterations, /* max #iterations */
237 int num_centers /* #pivots in sparse distance matrix */
238 )
239{
240 int iterations; /* output: number of iteration of the process */
241
242 double conj_tol = tolerance_cg; /* tolerance of Conjugate Gradient */
243
244 /*************************************************
245 ** Computation of pivot-based, sparse, subspace-restricted **
246 ** k-D stress minimization by majorization **
247 *************************************************/
248
249 int i, k, node;
250
251 /*************************************************
252 ** First compute the subspace in which we optimize **
253 ** The subspace is the high-dimensional embedding **
254 *************************************************/
255
256 int subspace_dim = MIN(stress_pca_dim, n); /* overall dimensionality of subspace */
257 double **subspace = gv_calloc(subspace_dim, sizeof(double *));
258 double *d_storage = gv_calloc(subspace_dim * n, sizeof(double));
259 int num_centers_local;
260 DistType **full_coords;
261 /* if i is a pivot than CenterIndex[i] is its index, otherwise CenterIndex[i]= -1 */
262 int *invCenterIndex; /* list the pivot nodes */
263 float *old_weights;
264 /* this matrix stores the distance between each node and each "center" */
265 DistType **Dij;
266 /* this vector stores the distances of each node to the selected "centers" */
267 DistType max_dist;
268 DistType *storage;
269 int *visited_nodes;
270 dist_data *distances;
271 int available_space;
272 int *storage1 = NULL;
273 DistType *storage2 = NULL;
274 int num_visited_nodes;
275 int num_neighbors;
276 int index;
277 DistType *dist_list;
278 vtx_data *lap;
279 int *edges;
280 float *ewgts;
281 double degree;
282 double **directions;
283 float **tmp_mat;
284 double dist_ij;
285 double *b;
286 double *b_restricted;
287 double L_ij;
288 double old_stress, new_stress;
289 bool converged;
290
291 for (i = 0; i < subspace_dim; i++) {
292 subspace[i] = d_storage + i * n;
293 }
294
295 /* compute PHDE: */
296 num_centers_local = MIN(n, MAX(2 * subspace_dim, 50));
297 full_coords = NULL;
298 /* High dimensional embedding */
299 embed_graph(graph, n, num_centers_local, &full_coords, reweight_graph);
300 /* Centering coordinates */
301 center_coordinate(full_coords, n, num_centers_local);
302 /* PCA */
303 PCA_alloc(full_coords, num_centers_local, n, subspace, subspace_dim);
304
305 free(full_coords[0]);
306 free(full_coords);
307
308 /*************************************************
309 ** Compute the sparse-shortest-distances matrix 'distances' **
310 *************************************************/
311
312 int *CenterIndex = gv_calloc(n, sizeof(int));
313 for (i = 0; i < n; i++) {
314 CenterIndex[i] = -1;
315 }
316 invCenterIndex = NULL;
317
318 old_weights = graph[0].ewgts;
319
320 if (reweight_graph) {
321 /* weight graph to separate high-degree nodes */
322 /* in the future, perform slower Dijkstra-based computation */
324 }
325
326 /* compute sparse distance matrix */
327 /* first select 'num_centers' pivots from which we compute distance */
328 /* to all other nodes */
329
330 Dij = NULL;
331 DistType *dist = gv_calloc(n, sizeof(DistType));
332 if (num_centers == 0) { /* no pivots, skip pivots-to-nodes distance calculation */
333 goto after_pivots_selection;
334 }
335
336 invCenterIndex = gv_calloc(num_centers, sizeof(int));
337
338 storage = gv_calloc(n * num_centers, sizeof(DistType));
339 Dij = gv_calloc(num_centers, sizeof(DistType *));
340 for (i = 0; i < num_centers; i++)
341 Dij[i] = storage + i * n;
342
343 // select `num_centers` pivots that are uniformly spread over the graph
344
345 /* the first pivots is selected randomly */
346 node = rand() % n;
347 CenterIndex[node] = 0;
348 invCenterIndex[0] = node;
349
350 if (reweight_graph) {
351 ngdijkstra(node, graph, n, Dij[0]);
352 } else {
353 bfs(node, graph, n, Dij[0]);
354 }
355
356 /* find the most distant node from first pivot */
357 max_dist = 0;
358 for (i = 0; i < n; i++) {
359 dist[i] = Dij[0][i];
360 if (dist[i] > max_dist) {
361 node = i;
362 max_dist = dist[i];
363 }
364 }
365 /* select other dim-1 nodes as pivots */
366 for (i = 1; i < num_centers; i++) {
367 CenterIndex[node] = i;
368 invCenterIndex[i] = node;
369 if (reweight_graph) {
370 ngdijkstra(node, graph, n, Dij[i]);
371 } else {
372 bfs(node, graph, n, Dij[i]);
373 }
374 max_dist = 0;
375 for (int j = 0; j < n; j++) {
376 dist[j] = MIN(dist[j], Dij[i][j]);
377 if (dist[j] > max_dist
378 || (dist[j] == max_dist && rand() % (j + 1) == 0)) {
379 node = j;
380 max_dist = dist[j];
381 }
382 }
383 }
384
385 after_pivots_selection:
386
387 /* Construct a sparse distance matrix 'distances' */
388
389 /* initialize dist to -1, important for 'bfs_bounded(..)' */
390 for (i = 0; i < n; i++) {
391 dist[i] = -1;
392 }
393
394 visited_nodes = gv_calloc(n, sizeof(int));
395 distances = gv_calloc(n, sizeof(dist_data));
396 available_space = 0;
397 size_t nedges = 0;
398 for (i = 0; i < n; i++) {
399 if (CenterIndex[i] >= 0) { /* a pivot node */
400 distances[i].edges = gv_calloc(n - 1, sizeof(int));
401 distances[i].edist = gv_calloc(n - 1, sizeof(DistType));
402 distances[i].nedges = (size_t)n - 1;
403 nedges += (size_t)n - 1;
404 distances[i].free_mem = true;
405 index = CenterIndex[i];
406 for (int j = 0; j < i; j++) {
407 distances[i].edges[j] = j;
408 distances[i].edist[j] = Dij[index][j];
409 }
410 for (int j = i + 1; j < n; j++) {
411 distances[i].edges[j - 1] = j;
412 distances[i].edist[j - 1] = Dij[index][j];
413 }
414 continue;
415 }
416
417 /* a non pivot node */
418
419 num_visited_nodes = 0;
420 num_neighbors = num_visited_nodes + num_centers;
421 if (num_neighbors > available_space) {
422 available_space = n;
423 storage1 = gv_calloc(available_space, sizeof(int));
424 storage2 = gv_calloc(available_space, sizeof(DistType));
425 distances[i].free_mem = true;
426 } else {
427 distances[i].free_mem = false;
428 }
429 distances[i].edges = storage1;
430 distances[i].edist = storage2;
431 distances[i].nedges = (size_t)num_neighbors;
432 nedges += (size_t)num_neighbors;
433 for (int j = 0; j < num_visited_nodes; j++) {
434 storage1[j] = visited_nodes[j];
435 storage2[j] = dist[visited_nodes[j]];
436 dist[visited_nodes[j]] = -1;
437 }
438 /* add all pivots: */
439 for (int j = num_visited_nodes; j < num_neighbors; j++) {
440 index = j - num_visited_nodes;
441 storage1[j] = invCenterIndex[index];
442 storage2[j] = Dij[index][i];
443 }
444
445 storage1 += num_neighbors;
446 storage2 += num_neighbors;
447 available_space -= num_neighbors;
448 }
449
450 free(dist);
451 free(visited_nodes);
452
453 if (Dij != NULL) {
454 free(Dij[0]);
455 free(Dij);
456 }
457
458 /*************************************************
459 ** Laplacian computation **
460 *************************************************/
461
462 lap = gv_calloc(n, sizeof(vtx_data));
463 edges = gv_calloc(nedges + n, sizeof(int));
464 ewgts = gv_calloc(nedges + n, sizeof(float));
465 for (i = 0; i < n; i++) {
466 lap[i].edges = edges;
467 lap[i].ewgts = ewgts;
468 lap[i].nedges = distances[i].nedges + 1; /*add the self loop */
469 dist_list = distances[i].edist - 1; /* '-1' since edist[0] goes for number '1' entry in the lap */
470 degree = 0;
471 if (exp == 2) {
472 for (size_t j = 1; j < lap[i].nedges; j++) {
473 edges[j] = distances[i].edges[j - 1];
474 ewgts[j] = -1.0f / ((float)dist_list[j] * (float)dist_list[j]); // cast to float to prevent overflow
475 degree -= ewgts[j];
476 }
477 } else {
478 for (size_t j = 1; j < lap[i].nedges; j++) {
479 edges[j] = distances[i].edges[j - 1];
480 ewgts[j] = -1.0f / (float) dist_list[j];
481 degree -= ewgts[j];
482 }
483 }
484 edges[0] = i;
485 ewgts[0] = (float) degree;
486 edges += lap[i].nedges;
487 ewgts += lap[i].nedges;
488 }
489
490 /*************************************************
491 ** initialize direction vectors **
492 ** to get an initial layout **
493 *************************************************/
494
495 /* the layout is subspace*directions */
496 directions = gv_calloc(dim, sizeof(double *));
497 directions[0] = gv_calloc(dim * subspace_dim, sizeof(double));
498 for (i = 1; i < dim; i++) {
499 directions[i] = directions[0] + i * subspace_dim;
500 }
501
502 if (smart_ini) {
503 /* smart initialization */
504 for (k = 0; k < dim; k++) {
505 for (i = 0; i < subspace_dim; i++) {
506 directions[k][i] = 0;
507 }
508 }
509 if (dim != 2) {
510 /* use the first vectors in the eigenspace */
511 /* each direction points to its "principal axes" */
512 for (k = 0; k < dim; k++) {
513 directions[k][k] = 1;
514 }
515 } else {
516 /* for the frequent 2-D case we prefer iterative-PCA over PCA */
517 /* Note that we don't want to mix the Lap's eigenspace with the HDE */
518 /* in the computation since they have different scales */
519
520 directions[0][0] = 1; /* first pca projection vector */
521 if (!iterativePCA_1D(subspace, subspace_dim, n, directions[1])) {
522 for (k = 0; k < subspace_dim; k++) {
523 directions[1][k] = 0;
524 }
525 directions[1][1] = 1;
526 }
527 }
528
529 } else {
530 /* random initialization */
531 for (k = 0; k < dim; k++) {
532 for (i = 0; i < subspace_dim; i++) {
533 directions[k][i] = (double) rand() / RAND_MAX;
534 }
535 }
536 }
537
538 /* compute initial k-D layout */
539
540 for (k = 0; k < dim; k++) {
541 right_mult_with_vector_transpose(subspace, n, subspace_dim,
542 directions[k], coords[k]);
543 }
544
545 /*************************************************
546 ** compute restriction of the laplacian to subspace: **
547 *************************************************/
548
549 tmp_mat = NULL;
550 double **matrix = NULL;
551 mult_sparse_dense_mat_transpose(lap, subspace, n, subspace_dim,
552 &tmp_mat);
553 mult_dense_mat_d(subspace, tmp_mat, subspace_dim, n, subspace_dim, &matrix);
554 free(tmp_mat[0]);
555 free(tmp_mat);
556
557 /*************************************************
558 ** Layout optimization **
559 *************************************************/
560
561 b = gv_calloc(n, sizeof(double));
562 b_restricted = gv_calloc(subspace_dim, sizeof(double));
563 old_stress = compute_stress1(coords, distances, dim, n, exp);
564 for (converged = false, iterations = 0;
565 iterations < n_iterations && !converged; iterations++) {
566
567 /* Axis-by-axis optimization: */
568 for (k = 0; k < dim; k++) {
569 /* compute the vector b */
570 /* multiply on-the-fly with distance-based laplacian */
571 /* (for saving storage we don't construct this Lap explicitly) */
572 for (i = 0; i < n; i++) {
573 degree = 0;
574 b[i] = 0;
575 dist_list = distances[i].edist - 1;
576 edges = lap[i].edges;
577 ewgts = lap[i].ewgts;
578 for (size_t j = 1; j < lap[i].nedges; j++) {
579 node = edges[j];
580 dist_ij = distance_kD(coords, dim, i, node);
581 if (dist_ij > 1e-30) { /* skip zero distances */
582 L_ij = -ewgts[j] * dist_list[j] / dist_ij; /* L_ij=w_{ij}*d_{ij}/dist_{ij} */
583 degree -= L_ij;
584 b[i] += L_ij * coords[k][node];
585 }
586 }
587 b[i] += degree * coords[k][i];
588 }
589 right_mult_with_vector_d(subspace, subspace_dim, n, b,
590 b_restricted);
591 if (conjugate_gradient_d(matrix, directions[k], b_restricted,
592 subspace_dim, conj_tol, subspace_dim,
593 false)) {
594 iterations = -1;
595 goto finish0;
596 }
597 right_mult_with_vector_transpose(subspace, n, subspace_dim,
598 directions[k], coords[k]);
599 }
600
601 if (iterations % 2 == 0) { // check for convergence each two iterations
602 new_stress = compute_stress1(coords, distances, dim, n, exp);
603 converged = fabs(new_stress - old_stress) / (new_stress + 1e-10) < Epsilon;
604 old_stress = new_stress;
605 }
606 }
607finish0:
608 free(b_restricted);
609 free(b);
610
611 if (reweight_graph) {
612 restore_old_weights(graph, n, old_weights);
613 }
614
615 for (i = 0; i < n; i++) {
616 if (distances[i].free_mem) {
617 free(distances[i].edges);
618 free(distances[i].edist);
619 }
620 }
621
622 free(distances);
623 free(lap[0].edges);
624 free(lap[0].ewgts);
625 free(lap);
626 free(CenterIndex);
627 free(invCenterIndex);
628 free(directions[0]);
629 free(directions);
630 if (matrix != NULL) {
631 free(matrix[0]);
632 free(matrix);
633 }
634 free(subspace[0]);
635 free(subspace);
636
637 return iterations;
638}
639
640/* compute_weighted_apsp_packed:
641 * Edge lengths can be any float > 0
642 */
644{
645 float *Dij = gv_calloc(n * (n + 1) / 2, sizeof(float));
646
647 float *Di = gv_calloc(n, sizeof(float));
648
649 for (int i = 0, count = 0; i < n; i++) {
650 dijkstra_f(i, graph, n, Di);
651 for (int j = i; j < n; j++) {
652 Dij[count++] = Di[j];
653 }
654 }
655 free(Di);
656 return Dij;
657}
658
659
661float *mdsModel(vtx_data * graph, int nG)
662{
663 int i, j;
664 float *Dij;
665 int shift = 0;
666 double delta = 0.0;
667
668 if (graph->ewgts == NULL)
669 return 0;
670
671 /* first, compute shortest paths to fill in non-edges */
673
674 /* then, replace edge entries will user-supplied len */
675 for (i = 0; i < nG; i++) {
676 shift += i;
677 for (size_t e = 1; e < graph[i].nedges; e++) {
678 j = graph[i].edges[e];
679 if (j < i)
680 continue;
681 delta += fabsf(Dij[i * nG + j - shift] - graph[i].ewgts[e]);
682 Dij[i * nG + j - shift] = graph[i].ewgts[e];
683 }
684 }
685 if (Verbose) {
686 fprintf(stderr, "mdsModel: delta = %f\n", delta);
687 }
688 return Dij;
689}
690
693{
694 int i, j, count;
695 float *Dij = gv_calloc(n * (n + 1) / 2, sizeof(float));
696
697 DistType *Di = gv_calloc(n, sizeof(DistType));
698
699 count = 0;
700 for (i = 0; i < n; i++) {
701 bfs(i, graph, n, Di);
702 for (j = i; j < n; j++) {
703 Dij[count++] = (float)Di[j];
704 }
705 }
706 free(Di);
707 return Dij;
708}
709
711 /* compute all-pairs-shortest-path-length while weighting the graph */
712 /* so high-degree nodes are distantly located */
713
714 float *Dij;
715 int i;
716 float *old_weights = graph[0].ewgts;
717 size_t nedges = 0;
718 size_t deg_i, deg_j;
719 int neighbor;
720
721 for (i = 0; i < n; i++) {
722 nedges += graph[i].nedges;
723 }
724
725 float *weights = gv_calloc(nedges, sizeof(float));
726 int *vtx_vec = gv_calloc(n, sizeof(int));
727
728 if (graph->ewgts) {
729 for (i = 0; i < n; i++) {
731 deg_i = graph[i].nedges - 1;
732 for (size_t j = 1; j <= deg_i; j++) {
733 neighbor = graph[i].edges[j];
734 deg_j = graph[neighbor].nedges - 1;
735 weights[j] = fmaxf((float)(deg_i + deg_j -
736 2 * common_neighbors(graph, neighbor, vtx_vec)), graph[i].ewgts[j]);
737 }
738 empty_neighbors_vec(graph, i, vtx_vec);
739 graph[i].ewgts = weights;
740 weights += graph[i].nedges;
741 }
743 } else {
744 for (i = 0; i < n; i++) {
745 graph[i].ewgts = weights;
747 deg_i = graph[i].nedges - 1;
748 for (size_t j = 1; j <= deg_i; j++) {
749 neighbor = graph[i].edges[j];
750 deg_j = graph[neighbor].nedges - 1;
751 weights[j] =
752 (float)(deg_i + deg_j - 2 * common_neighbors(graph, neighbor, vtx_vec));
753 }
754 empty_neighbors_vec(graph, i, vtx_vec);
755 weights += graph[i].nedges;
756 }
757 Dij = compute_apsp_packed(graph, n);
758 }
759
760 free(vtx_vec);
761 free(graph[0].ewgts);
762 graph[0].ewgts = NULL;
763 if (old_weights != NULL) {
764 for (i = 0; i < n; i++) {
765 graph[i].ewgts = old_weights;
766 old_weights += graph[i].nedges;
767 }
768 }
769 return Dij;
770}
771
772/* Accumulator type for diagonal of Laplacian. Needs to be as large
773 * as possible. Use long double; configure to double if necessary.
774 */
775#define DegType long double
776
778int stress_majorization_kD_mkernel(vtx_data * graph, /* Input graph in sparse representation */
779 int n, /* Number of nodes */
780 double **d_coords, /* coordinates of nodes (output layout) */
781 node_t ** nodes, /* original nodes */
782 int dim, /* dimensionality of layout */
783 int opts, /* options */
784 int model, /* model */
785 int maxi /* max iterations */
786 )
787{
788 int iterations; /* output: number of iteration of the process */
789
790 double conj_tol = tolerance_cg; /* tolerance of Conjugate Gradient */
791 float *Dij = NULL;
792 int i, j, k;
793 float **coords = NULL;
794 float *f_storage = NULL;
795 float constant_term;
796 int count;
797 DegType degree;
798 int lap_length;
799 float *lap2 = NULL;
800 DegType *degrees = NULL;
801 int step;
802 float val;
803 double old_stress, new_stress;
804 bool converged;
805 float **b = NULL;
806 float *tmp_coords = NULL;
807 float *dist_accumulator = NULL;
808 float *lap1 = NULL;
809 int smart_ini = opts & opt_smart_init;
810 int exp = opts & opt_exp_flag;
811 int len;
812 int havePinned; /* some node is pinned */
813
814 /*************************************************
815 ** Computation of full, dense, unrestricted k-D **
816 ** stress minimization by majorization **
817 *************************************************/
818
819 /****************************************************
820 ** Compute the all-pairs-shortest-distances matrix **
821 ****************************************************/
822
823 if (maxi < 0)
824 return 0;
825
826 if (Verbose)
827 start_timer();
828
829 if (model == MODEL_SUBSET) {
830 /* weight graph to separate high-degree nodes */
831 /* and perform slower Dijkstra-based computation */
832 if (Verbose)
833 fprintf(stderr, "Calculating subset model");
835 } else if (model == MODEL_CIRCUIT) {
836 Dij = circuitModel(graph, n);
837 if (!Dij) {
839 "graph is disconnected. Hence, the circuit model\n");
841 "is undefined. Reverting to the shortest path model.\n");
842 }
843 } else if (model == MODEL_MDS) {
844 if (Verbose)
845 fprintf(stderr, "Calculating MDS model");
846 Dij = mdsModel(graph, n);
847 }
848 if (!Dij) {
849 if (Verbose)
850 fprintf(stderr, "Calculating shortest paths");
851 if (graph->ewgts)
853 else
854 Dij = compute_apsp_packed(graph, n);
855 }
856
857 if (Verbose) {
858 fprintf(stderr, ": %.2f sec\n", elapsed_sec());
859 fprintf(stderr, "Setting initial positions");
860 start_timer();
861 }
862
863 /**************************
864 ** Layout initialization **
865 **************************/
866
867 if (smart_ini && n > 1) {
868 havePinned = 0;
869 /* optimize layout quickly within subspace */
870 /* perform at most 50 iterations within 30-D subspace to
871 get an estimate */
873 d_coords, dim, smart_ini, exp,
874 model == MODEL_SUBSET, 50,
875 num_pivots_stress) < 0) {
876 iterations = -1;
877 goto finish1;
878 }
879
880 for (i = 0; i < dim; i++) {
881 /* for numerical stability, scale down layout */
882 double max = 1;
883 for (j = 0; j < n; j++) {
884 if (fabs(d_coords[i][j]) > max) {
885 max = fabs(d_coords[i][j]);
886 }
887 }
888 for (j = 0; j < n; j++) {
889 d_coords[i][j] /= max;
890 }
891 /* add small random noise */
892 for (j = 0; j < n; j++) {
893 d_coords[i][j] += 1e-6 * (drand48() - 0.5);
894 }
895 orthog1(n, d_coords[i]);
896 }
897 } else {
898 havePinned = initLayout(n, dim, d_coords, nodes);
899 }
900 if (Verbose)
901 fprintf(stderr, ": %.2f sec", elapsed_sec());
902 if (n == 1 || maxi == 0) {
903 free(Dij);
904 return 0;
905 }
906
907 if (Verbose) {
908 fprintf(stderr, ": %.2f sec\n", elapsed_sec());
909 fprintf(stderr, "Setting up stress function");
910 start_timer();
911 }
912 coords = gv_calloc(dim, sizeof(float *));
913 f_storage = gv_calloc(dim * n, sizeof(float));
914 for (i = 0; i < dim; i++) {
915 coords[i] = f_storage + i * n;
916 for (j = 0; j < n; j++) {
917 coords[i][j] = (float)d_coords[i][j];
918 }
919 }
920
921 /* compute constant term in stress sum */
922 /* which is \sum_{i<j} w_{ij}d_{ij}^2 */
923 assert(exp == 1 || exp == 2);
924 constant_term = (float)n * (n - 1) / 2;
925
926 /**************************
927 ** Laplacian computation **
928 **************************/
929
930 lap_length = n * (n + 1) / 2;
931 lap2 = Dij;
932 if (exp == 2) {
933 square_vec(lap_length, lap2);
934 }
935 /* compute off-diagonal entries */
936 invert_vec(lap_length, lap2);
937
938 /* compute diagonal entries */
939 count = 0;
940 degrees = gv_calloc(n, sizeof(DegType));
941 for (i = 0; i < n - 1; i++) {
942 degree = 0;
943 count++; /* skip main diag entry */
944 for (j = 1; j < n - i; j++, count++) {
945 val = lap2[count];
946 degree += val;
947 degrees[i + j] -= val;
948 }
949 degrees[i] -= degree;
950 }
951 for (step = n, count = 0, i = 0; i < n; i++, count += step, step--) {
952 lap2[count] = degrees[i];
953 }
954
955 /*************************
956 ** Layout optimization **
957 *************************/
958
959 b = gv_calloc(dim, sizeof(float *));
960 b[0] = gv_calloc(dim * n, sizeof(float));
961 for (k = 1; k < dim; k++) {
962 b[k] = b[0] + k * n;
963 }
964
965 tmp_coords = gv_calloc(n, sizeof(float));
966 dist_accumulator = gv_calloc(n, sizeof(float));
967 lap1 = gv_calloc(lap_length, sizeof(float));
968
969
970 old_stress = DBL_MAX; // at least one iteration
971 if (Verbose) {
972 fprintf(stderr, ": %.2f sec\n", elapsed_sec());
973 fprintf(stderr, "Solving model: ");
974 start_timer();
975 }
976
977 for (converged = false, iterations = 0;
978 iterations < maxi && !converged; iterations++) {
979
980 /* First, construct Laplacian of 1/(d_ij*|p_i-p_j|) */
981 /* set_vector_val(n, 0, degrees); */
982 memset(degrees, 0, n * sizeof(DegType));
983 if (exp == 2) {
984 sqrt_vecf(lap_length, lap2, lap1);
985 }
986 for (count = 0, i = 0; i < n - 1; i++) {
987 len = n - i - 1;
988 /* init 'dist_accumulator' with zeros */
989 set_vector_valf(len, 0, dist_accumulator);
990
991 /* put into 'dist_accumulator' all squared distances between 'i' and 'i'+1,...,'n'-1 */
992 for (k = 0; k < dim; k++) {
993 size_t x;
994 for (x = 0; x < (size_t)len; ++x) {
995 float tmp = coords[k][i] + -1.0f * (coords[k] + i + 1)[x];
996 dist_accumulator[x] += tmp * tmp;
997 }
998 }
999
1000 /* convert to 1/d_{ij} */
1001 invert_sqrt_vec(len, dist_accumulator);
1002 /* detect overflows */
1003 for (j = 0; j < len; j++) {
1004 if (dist_accumulator[j] >= FLT_MAX || dist_accumulator[j] < 0) {
1005 dist_accumulator[j] = 0;
1006 }
1007 }
1008
1009 count++; /* save place for the main diagonal entry */
1010 degree = 0;
1011 if (exp == 2) {
1012 for (j = 0; j < len; j++, count++) {
1013 val = lap1[count] *= dist_accumulator[j];
1014 degree += val;
1015 degrees[i + j + 1] -= val;
1016 }
1017 } else {
1018 for (j = 0; j < len; j++, count++) {
1019 val = lap1[count] = dist_accumulator[j];
1020 degree += val;
1021 degrees[i + j + 1] -= val;
1022 }
1023 }
1024 degrees[i] -= degree;
1025 }
1026 for (step = n, count = 0, i = 0; i < n; i++, count += step, step--) {
1027 lap1[count] = degrees[i];
1028 }
1029
1030 /* Now compute b[] */
1031 for (k = 0; k < dim; k++) {
1032 /* b[k] := lap1*coords[k] */
1033 right_mult_with_vector_ff(lap1, n, coords[k], b[k]);
1034 }
1035
1036
1037 /* compute new stress */
1038 /* remember that the Laplacians are negated, so we subtract instead of add and vice versa */
1039 new_stress = 0;
1040 for (k = 0; k < dim; k++) {
1041 new_stress += vectors_inner_productf(n, coords[k], b[k]);
1042 }
1043 new_stress *= 2;
1044 new_stress += constant_term; /* only after mult by 2 */
1045 for (k = 0; k < dim; k++) {
1046 right_mult_with_vector_ff(lap2, n, coords[k], tmp_coords);
1047 new_stress -= vectors_inner_productf(n, coords[k], tmp_coords);
1048 }
1049 /* Invariant: old_stress > 0. In theory, old_stress >= new_stress
1050 * but we use fabs in case of numerical error.
1051 */
1052 {
1053 double diff = old_stress - new_stress;
1054 double change = fabs(diff);
1055 converged = change / old_stress < Epsilon || new_stress < Epsilon;
1056 }
1057 old_stress = new_stress;
1058
1059 for (k = 0; k < dim; k++) {
1060 node_t *np;
1061 if (havePinned) {
1062 copy_vectorf(n, coords[k], tmp_coords);
1063 if (conjugate_gradient_mkernel(lap2, tmp_coords, b[k], n,
1064 conj_tol, n) < 0) {
1065 iterations = -1;
1066 goto finish1;
1067 }
1068 for (i = 0; i < n; i++) {
1069 np = nodes[i];
1070 if (!isFixed(np))
1071 coords[k][i] = tmp_coords[i];
1072 }
1073 } else {
1074 if (conjugate_gradient_mkernel(lap2, coords[k], b[k], n,
1075 conj_tol, n) < 0) {
1076 iterations = -1;
1077 goto finish1;
1078 }
1079 }
1080 }
1081 if (Verbose && iterations % 5 == 0) {
1082 fprintf(stderr, "%.3f ", new_stress);
1083 if ((iterations + 5) % 50 == 0)
1084 fprintf(stderr, "\n");
1085 }
1086 }
1087 if (Verbose) {
1088 fprintf(stderr, "\nfinal e = %f %d iterations %.2f sec\n",
1089 compute_stressf(coords, lap2, dim, n, exp),
1090 iterations, elapsed_sec());
1091 }
1092
1093 for (i = 0; i < dim; i++) {
1094 for (j = 0; j < n; j++) {
1095 d_coords[i][j] = coords[i][j];
1096 }
1097 }
1098finish1:
1099 free(f_storage);
1100 free(coords);
1101
1102 free(lap2);
1103 if (b) {
1104 free(b[0]);
1105 free(b);
1106 }
1107 free(tmp_coords);
1108 free(dist_accumulator);
1109 free(degrees);
1110 free(lap1);
1111 return iterations;
1112}
Memory allocation wrappers that exit on failure.
static void * gv_calloc(size_t nmemb, size_t size)
Definition alloc.h:26
#define Epsilon
Definition arcball.h:137
#define MIN(a, b)
Definition arith.h:28
#define MAX(a, b)
Definition arith.h:33
void bfs(int vertex, vtx_data *graph, int n, DistType *dist)
compute vector dist of distances of all nodes from vertex
Definition bfs.c:24
int solveCircuit(int nG, double **Gm, double **Gm_inv)
Definition circuit.c:22
double drand48(void)
Definition utils.c:1478
int conjugate_gradient_d(double **A, double *x, double *b, int n, double tol, int max_iterations, bool ortho1)
Definition conjgrad.c:92
int conjugate_gradient_mkernel(float *A, float *x, float *b, int n, double tol, int max_iterations)
Definition conjgrad.c:161
void embed_graph(vtx_data *graph, int n, int dim, DistType ***Coords, int reweight_graph)
Definition embed_graph.c:30
void center_coordinate(DistType **coords, int n, int dim)
static double dist(int dim, double *x, double *y)
static double len(glCompPoint p)
Definition glutils.c:138
static bool Verbose
Definition gml2gv.c:26
void free(void *)
node NULL
Definition grammar.y:181
void agwarningf(const char *fmt,...)
Definition agerror.c:175
int agerr(agerrlevel_t level, const char *fmt,...)
Definition agerror.c:157
@ AGPREV
Definition cgraph.h:951
#define ND_pos(n)
Definition types.h:520
Agraph_t * graph(char *name)
Definition gv.cpp:34
static opts_t opts
Definition gvgen.c:415
void compute_new_weights(vtx_data *graph, int n)
Definition kkutils.c:147
double distance_kD(double **coords, int dim, int i, int j)
Definition kkutils.c:113
void fill_neighbors_vec_unweighted(vtx_data *graph, int vtx, int *vtx_vec)
Definition kkutils.c:34
size_t common_neighbors(vtx_data *graph, int u, int *v_vector)
Definition kkutils.c:21
void restore_old_weights(vtx_data *graph, int n, float *old_weights)
Definition kkutils.c:178
void empty_neighbors_vec(vtx_data *graph, int vtx, int *vtx_vec)
Definition kkutils.c:43
void dijkstra_f(int vertex, vtx_data *graph, int n, float *dist)
Definition dijkstra.c:268
void ngdijkstra(int vertex, vtx_data *graph, int n, DistType *dist)
Definition dijkstra.c:155
#define isFixed(n)
Definition macros.h:19
#define hasPos(n)
Definition macros.h:18
#define neighbor(t, i, edim, elist)
Definition make_map.h:41
void right_mult_with_vector_d(double *const *matrix, int dim1, int dim2, const double *vector, double *restrict result)
Definition matrix_ops.c:305
void right_mult_with_vector_transpose(double **matrix, int dim1, int dim2, double *vector, double *result)
Definition matrix_ops.c:290
void invert_vec(int n, float *vec)
Definition matrix_ops.c:420
void mult_sparse_dense_mat_transpose(vtx_data *A, double **B, int dim1, int dim2, float ***CC)
Definition matrix_ops.c:157
void invert_sqrt_vec(int n, float *vec)
Definition matrix_ops.c:438
void set_vector_valf(int n, float val, float *result)
Definition matrix_ops.c:398
void orthog1(int n, double *vec)
Definition matrix_ops.c:201
void copy_vectorf(int n, float *source, float *dest)
Definition matrix_ops.c:382
void sqrt_vecf(int n, float *source, float *target)
Definition matrix_ops.c:429
void mult_dense_mat_d(double **A, float **B, int dim1, int dim2, int dim3, double ***CC)
Definition matrix_ops.c:131
void square_vec(int n, float *vec)
Definition matrix_ops.c:413
void right_mult_with_vector_ff(const float *packed_matrix, int n, const float *vector, float *restrict result)
Definition matrix_ops.c:339
double vectors_inner_productf(int n, float *vector1, float *vector2)
Definition matrix_ops.c:388
#define delta
Definition maze.c:138
static const int dim
#define MODEL_SUBSET
Definition neato.h:18
#define MODEL_MDS
Definition neato.h:19
#define MODEL_CIRCUIT
Definition neato.h:17
NEATOPROCS_API void free_array(double **rv)
Definition stuff.c:54
NEATOPROCS_API double ** new_array(int i, int j, double val)
Definition stuff.c:39
void PCA_alloc(DistType **coords, int dim, int n, double **new_coords, int new_dim)
Definition pca.c:25
bool iterativePCA_1D(double **coords, int dim, int n, double *new_direction)
Definition pca.c:72
static int nedges
total no. of edges used in routing
Definition routespl.c:33
int DistType
Definition sparsegraph.h:39
float * compute_apsp_artificial_weights_packed(vtx_data *graph, int n)
Definition stress.c:710
static double compute_stressf(float **coords, float *lap, int dim, int n, int exp)
Definition stress.c:44
int stress_majorization_kD_mkernel(vtx_data *graph, int n, double **d_coords, node_t **nodes, int dim, int opts, int model, int maxi)
at present, if any nodes have pos set, smart_ini is false
Definition stress.c:778
#define DegType
Definition stress.c:775
static float * compute_weighted_apsp_packed(vtx_data *graph, int n)
Definition stress.c:643
static int sparse_stress_subspace_majorization_kD(vtx_data *graph, int n, double **coords, int dim, int smart_ini, int exp, int reweight_graph, int n_iterations, int num_centers)
Definition stress.c:229
float * circuitModel(vtx_data *graph, int nG)
Definition stress.c:169
int initLayout(int n, int dim, double **coords, node_t **nodes)
Definition stress.c:131
float * mdsModel(vtx_data *graph, int nG)
update matrix with actual edge lengths
Definition stress.c:661
float * compute_apsp_packed(vtx_data *graph, int n)
assumes integral weights > 0
Definition stress.c:692
static double compute_stress1(double **coords, dist_data *distances, int dim, int n, int exp)
Definition stress.c:77
#define stress_pca_dim
Definition stress.c:34
#define opt_smart_init
Definition stress.h:30
#define opt_exp_flag
Definition stress.h:31
#define tolerance_cg
Definition stress.h:21
#define num_pivots_stress
Definition stress.h:28
DistType * edist
Definition stress.c:40
bool free_mem
Definition stress.c:41
size_t nedges
Definition stress.c:38
int * edges
Definition stress.c:39
float * ewgts
Definition sparsegraph.h:32
size_t nedges
no. of neighbors, including self
Definition sparsegraph.h:30
int * edges
Definition sparsegraph.h:31
double elapsed_sec(void)
Definition timing.c:23
void start_timer(void)
Definition timing.c:21