Debian Codegraph @

lib/neatogen/constrained_majorization.c

raw
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 v1.0
5 * which accompanies this distribution, and is available at
6 * https://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors: Details at https://graphviz.org
9 *************************************************************************/
10
11 #include "config.h"
12
13 #include <neatogen/digcola.h>
14 #include <util/alloc.h>
15 #ifdef DIGCOLA
16 #include <math.h>
17 #include <stdbool.h>
18 #include <stdlib.h>
19 #include <time.h>
20 #include <stdio.h>
21 #include <float.h>
22 #include <neatogen/stress.h>
23 #include <neatogen/dijkstra.h>
24 #include <neatogen/bfs.h>
25 #include <neatogen/matrix_ops.h>
26 #include <neatogen/kkutils.h>
27 #include <neatogen/conjgrad.h>
28 #include <neatogen/quad_prog_solver.h>
29 #include <neatogen/matrix_ops.h>
30
31 #define localConstrMajorIterations 15
32 #define levels_sep_tol 1e-1
33
34 int stress_majorization_with_hierarchy(vtx_data * graph, /* Input graph in sparse representation */
35 int n, /* Number of nodes */
36 double **d_coords, /* Coordinates of nodes (output layout) */
37 node_t ** nodes, /* Original nodes */
38 int dim, /* Dimensionality of layout */
39 int opts, /* options */
40 int model, /* difference model */
41 int maxi, /* max iterations */
42 double levels_gap)
43 {
44 int iterations = 0; /* Output: number of iteration of the process */
45
46 /*************************************************
47 ** Computation of full, dense, unrestricted k-D **
48 ** stress minimization by majorization **
49 ** This function imposes HIERARCHY CONSTRAINTS **
50 *************************************************/
51
52 int i, k;
53 bool directionalityExist = false;
54 float *lap1 = NULL;
55 float *dist_accumulator = NULL;
56 float *tmp_coords = NULL;
57 float **b = NULL;
58 double *degrees = NULL;
59 float *lap2 = NULL;
60 int lap_length;
61 float *f_storage = NULL;
62 float **coords = NULL;
63
64 double conj_tol = tolerance_cg; /* tolerance of Conjugate Gradient */
65 CMajEnv *cMajEnv = NULL;
66 double y_0;
67 int length;
68 int smart_ini = opts & opt_smart_init;
69 DistType diameter;
70 float *Dij = NULL;
71 /* to compensate noises, we never consider gaps smaller than 'abs_tol' */
72 double abs_tol = 1e-2;
73 /* Additionally, we never consider gaps smaller than 'abs_tol'*<avg_gap> */
74 double relative_tol = levels_sep_tol;
75 int *ordering = NULL, *levels = NULL;
76 float constant_term;
77 double degree;
78 int step;
79 float val;
80 double old_stress, new_stress;
81 bool converged;
82 int len;
83 int num_levels;
84
85 if (graph[0].edists != NULL) {
86 for (i = 0; i < n; i++) {
87 for (size_t j = 1; j < graph[i].nedges; j++) {
88 directionalityExist |= graph[i].edists[j] != 0;
89 }
90 }
91 }
92 if (!directionalityExist) {
93 return stress_majorization_kD_mkernel(graph, n,
94 d_coords, nodes, dim, opts,
95 model, maxi);
96 }
97
98 /******************************************************************
99 ** First, partition nodes into layers: These are our constraints **
100 ******************************************************************/
101
102 if (smart_ini) {
103 double *x;
104 double *y;
105 if (dim > 2) {
106 /* the dim==2 case is handled below */
107 if (stress_majorization_kD_mkernel(graph, n,
108 d_coords + 1, nodes, dim - 1,
109 opts, model, 15) < 0)
110 return -1;
111 /* now copy the y-axis into the (dim-1)-axis */
112 for (i = 0; i < n; i++) {
113 d_coords[dim - 1][i] = d_coords[1][i];
114 }
115 }
116
117 x = d_coords[0];
118 y = d_coords[1];
119 if (compute_y_coords(graph, n, y, n)) {
120 iterations = -1;
121 goto finish;
122 }
123 if (compute_hierarchy(graph, n, abs_tol, relative_tol, y, &ordering,
124 &levels, &num_levels)) {
125 iterations = -1;
126 goto finish;
127 }
128 if (num_levels < 1) {
129 /* no hierarchy found, use faster algorithm */
130 free(levels);
131 return stress_majorization_kD_mkernel(graph, n,
132 d_coords, nodes, dim,
133 opts, model, maxi);
134 }
135
136 if (levels_gap > 0) {
137 /* ensure that levels are separated in the initial layout */
138 double displacement = 0;
139 int stop;
140 for (i = 0; i < num_levels; i++) {
141 displacement +=
142 MAX(0.0,
143 levels_gap - (y[ordering[levels[i]]] +
144 displacement -
145 y[ordering[levels[i] - 1]]));
146 stop = i < num_levels - 1 ? levels[i + 1] : n;
147 for (int j = levels[i]; j < stop; j++) {
148 y[ordering[j]] += displacement;
149 }
150 }
151 }
152 if (dim == 2) {
153 if (IMDS_given_dim(graph, n, y, x, Epsilon)) {
154 iterations = -1;
155 goto finish;
156 }
157 }
158 } else {
159 initLayout(n, dim, d_coords, nodes);
160 if (compute_hierarchy(graph, n, abs_tol, relative_tol, NULL, &ordering,
161 &levels, &num_levels)) {
162 iterations = -1;
163 goto finish;
164 }
165 }
166 if (n == 1) {
167 free(levels);
168 return 0;
169 }
170
171 /****************************************************
172 ** Compute the all-pairs-shortest-distances matrix **
173 ****************************************************/
174
175 if (maxi == 0) {
176 free(levels);
177 return iterations;
178 }
179
180 if (Verbose)
181 start_timer();
182
183 if (model == MODEL_SUBSET) {
184 /* weight graph to separate high-degree nodes */
185 /* and perform slower Dijkstra-based computation */
186 if (Verbose)
187 fprintf(stderr, "Calculating subset model");
188 Dij = compute_apsp_artificial_weights_packed(graph, n);
189 } else if (model == MODEL_CIRCUIT) {
190 Dij = circuitModel(graph, n);
191 if (!Dij) {
192 agwarningf(
193 "graph is disconnected. Hence, the circuit model\n");
194 agerr(AGPREV,
195 "is undefined. Reverting to the shortest path model.\n");
196 }
197 } else if (model == MODEL_MDS) {
198 if (Verbose)
199 fprintf(stderr, "Calculating MDS model");
200 Dij = mdsModel(graph, n);
201 }
202 if (!Dij) {
203 if (Verbose)
204 fprintf(stderr, "Calculating shortest paths");
205 Dij = compute_apsp_packed(graph, n);
206 }
207 if (Verbose) {
208 fprintf(stderr, ": %.2f sec\n", elapsed_sec());
209 fprintf(stderr, "Setting initial positions");
210 start_timer();
211 }
212
213 diameter = -1;
214 length = n + n * (n - 1) / 2;
215 for (i = 0; i < length; i++) {
216 if (Dij[i] > diameter) {
217 diameter = (int) Dij[i];
218 }
219 }
220
221 if (!smart_ini) {
222 /* for numerical stability, scale down layout */
223 /* No Jiggling, might conflict with constraints */
224 double max = 1;
225 for (i = 0; i < dim; i++) {
226 for (int j = 0; j < n; j++) {
227 max = fmax(max, fabs(d_coords[i][j]));
228 }
229 }
230 for (i = 0; i < dim; i++) {
231 for (int j = 0; j < n; j++) {
232 d_coords[i][j] *= 10 / max;
233 }
234 }
235 }
236
237 if (levels_gap > 0) {
238 double sum1, sum2, scale_ratio;
239 int count;
240 sum1 = (float) (n * (n - 1) / 2);
241 sum2 = 0;
242 for (count = 0, i = 0; i < n - 1; i++) {
243 count++; // skip self distance
244 for (int j = i + 1; j < n; j++, count++) {
245 sum2 += distance_kD(d_coords, dim, i, j) / Dij[count];
246 }
247 }
248 scale_ratio = sum2 / sum1;
249 /* double scale_ratio=10; */
250 for (i = 0; i < length; i++) {
251 Dij[i] *= (float) scale_ratio;
252 }
253 }
254
255 /**************************
256 ** Layout initialization **
257 **************************/
258
259 for (i = 0; i < dim; i++) {
260 orthog1(n, d_coords[i]);
261 }
262
263 /* for the y-coords, don't center them, but translate them so y[0]=0 */
264 y_0 = d_coords[1][0];
265 for (i = 0; i < n; i++) {
266 d_coords[1][i] -= y_0;
267 }
268
269 coords = gv_calloc(dim, sizeof(float *));
270 f_storage = gv_calloc(dim * n, sizeof(float));
271 for (i = 0; i < dim; i++) {
272 coords[i] = f_storage + i * n;
273 for (int j = 0; j < n; j++) {
274 coords[i][j] = (float)d_coords[i][j];
275 }
276 }
277
278 /* compute constant term in stress sum
279 * which is \sum_{i<j} w_{ij}d_{ij}^2
280 */
281 constant_term = (float) (n * (n - 1) / 2);
282
283 if (Verbose)
284 fprintf(stderr, ": %.2f sec", elapsed_sec());
285
286 /**************************
287 ** Laplacian computation **
288 **************************/
289
290 lap2 = Dij;
291 lap_length = n + n * (n - 1) / 2;
292 square_vec(lap_length, lap2);
293 /* compute off-diagonal entries */
294 invert_vec(lap_length, lap2);
295
296 /* compute diagonal entries */
297 int count = 0;
298 degrees = gv_calloc(n, sizeof(double));
299 set_vector_val(n, 0, degrees);
300 for (i = 0; i < n - 1; i++) {
301 degree = 0;
302 count++; // skip main diag entry
303 for (int j = 1; j < n - i; j++, count++) {
304 val = lap2[count];
305 degree += val;
306 degrees[i + j] -= val;
307 }
308 degrees[i] -= degree;
309 }
310 for (step = n, count = 0, i = 0; i < n; i++, count += step, step--) {
311 lap2[count] = (float) degrees[i];
312 }
313
314 /*************************
315 ** Layout optimization **
316 *************************/
317
318 b = gv_calloc(dim, sizeof(float *));
319 b[0] = gv_calloc(dim * n, sizeof(float));
320 for (k = 1; k < dim; k++) {
321 b[k] = b[0] + k * n;
322 }
323
324 tmp_coords = gv_calloc(n, sizeof(float));
325 dist_accumulator = gv_calloc(n, sizeof(float));
326 lap1 = gv_calloc(lap_length, sizeof(float));
327
328 old_stress = DBL_MAX; /* at least one iteration */
329
330 cMajEnv =
331 initConstrainedMajorization(lap2, n, ordering, levels, num_levels);
332
333 for (converged = false, iterations = 0;
334 iterations < maxi && !converged; iterations++) {
335
336 /* First, construct Laplacian of 1/(d_ij*|p_i-p_j|) */
337 set_vector_val(n, 0, degrees);
338 sqrt_vecf(lap_length, lap2, lap1);
339 for (count = 0, i = 0; i < n - 1; i++) {
340 len = n - i - 1;
341 /* init 'dist_accumulator' with zeros */
342 set_vector_valf(n, 0, dist_accumulator);
343
344 /* put into 'dist_accumulator' all squared distances
345 * between 'i' and 'i'+1,...,'n'-1
346 */
347 for (k = 0; k < dim; k++) {
348 set_vector_valf(len, coords[k][i], tmp_coords);
349 vectors_mult_additionf(len, tmp_coords, -1, coords[k] + i + 1);
350 square_vec(len, tmp_coords);
351 vectors_additionf(len, tmp_coords, dist_accumulator, dist_accumulator);
352 }
353
354 /* convert to 1/d_{ij} */
355 invert_sqrt_vec(len, dist_accumulator);
356 /* detect overflows */
357 for (int j = 0; j < len; j++) {
358 if (dist_accumulator[j] >= FLT_MAX || dist_accumulator[j] < 0) {
359 dist_accumulator[j] = 0;
360 }
361 }
362
363 count++; /* save place for the main diagonal entry */
364 degree = 0;
365 for (int j = 0; j < len; j++, count++) {
366 val = lap1[count] *= dist_accumulator[j];
367 degree += val;
368 degrees[i + j + 1] -= val;
369 }
370 degrees[i] -= degree;
371 }
372 for (step = n, count = 0, i = 0; i < n; i++, count += step, step--) {
373 lap1[count] = (float) degrees[i];
374 }
375
376 /* Now compute b[] (L^(X(t))*X(t)) */
377 for (k = 0; k < dim; k++) {
378 /* b[k] := lap1*coords[k] */
379 right_mult_with_vector_ff(lap1, n, coords[k], b[k]);
380 }
381
382 /* compute new stress
383 * remember that the Laplacians are negated, so we subtract
384 * instead of add and vice versa
385 */
386 new_stress = 0;
387 for (k = 0; k < dim; k++) {
388 new_stress += vectors_inner_productf(n, coords[k], b[k]);
389 }
390 new_stress *= 2;
391 new_stress += constant_term; // only after mult by 2
392 for (k = 0; k < dim; k++) {
393 right_mult_with_vector_ff(lap2, n, coords[k], tmp_coords);
394 new_stress -= vectors_inner_productf(n, coords[k], tmp_coords);
395 }
396
397 /* check for convergence */
398 converged =
399 fabs(new_stress - old_stress) / fabs(old_stress + 1e-10) <
400 Epsilon;
401 converged |= iterations > 1 && new_stress > old_stress;
402 /* in first iteration we allowed stress increase, which
403 * might result ny imposing constraints
404 */
405 old_stress = new_stress;
406
407 for (k = 0; k < dim; k++) {
408 /* now we find the optimizer of trace(X'LX)+X'B by solving 'dim'
409 * system of equations, thereby obtaining the new coordinates.
410 * If we use the constraints (given by the var's: 'ordering',
411 * 'levels' and 'num_levels'), we cannot optimize
412 * trace(X'LX)+X'B by simply solving equations, but we have
413 * to use a quadratic programming solver
414 * note: 'lap2' is a packed symmetric matrix, that is its
415 * upper-triangular part is arranged in a vector row-wise
416 * also note: 'lap2' is really the negated laplacian (the
417 * laplacian is -'lap2')
418 */
419
420 if (k == 1) {
421 /* use quad solver in the y-dimension */
422 constrained_majorization_new_with_gaps(cMajEnv, b[k],
423 coords, k,
424 localConstrMajorIterations,
425 levels_gap);
426
427 } else {
428 /* use conjugate gradient for all dimensions except y */
429 if (conjugate_gradient_mkernel(lap2, coords[k], b[k], n,
430 conj_tol, n)) {
431 iterations = -1;
432 goto finish;
433 }
434 }
435 }
436 }
437
438 for (i = 0; i < dim; i++) {
439 for (int j = 0; j < n; j++) {
440 d_coords[i][j] = coords[i][j];
441 }
442 }
443
444 free(tmp_coords);
445 free(dist_accumulator);
446 free(degrees);
447 free(lap2);
448
449 free(lap1);
450
451 finish:
452 if (cMajEnv != NULL) {
453 deleteCMajEnv(cMajEnv);
454 }
455 if (b) {
456 free(b[0]);
457 free(b);
458 }
459 free(f_storage);
460 free(coords);
461 free(ordering);
462
463 free(levels);
464
465 return iterations;
466 }
467 #endif /* DIGCOLA */