fruchterman_reingold.hpp 15.6 KB
Newer Older
Tiago Peixoto's avatar
Tiago Peixoto committed
1
2
// Copyright 2004 The Trustees of Indiana University.

3
4
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
Tiago Peixoto's avatar
Tiago Peixoto committed
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
// http://www.boost.org/LICENSE_1_0.txt)

//  Authors: Douglas Gregor
//           Andrew Lumsdaine
#ifndef BOOST_GRAPH_FRUCHTERMAN_REINGOLD_FORCE_DIRECTED_LAYOUT_HPP
#define BOOST_GRAPH_FRUCHTERMAN_REINGOLD_FORCE_DIRECTED_LAYOUT_HPP

#include <cmath>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/named_function_params.hpp>
#include <boost/graph/simple_point.hpp>
#include <vector>
#include <list>
#include <algorithm> // for std::min and std::max

namespace boost {

struct square_distance_attractive_force {
  template<typename Graph, typename T>
  T
  operator()(typename graph_traits<Graph>::edge_descriptor,
             T k,
             T d,
             const Graph&) const
  {
    return d * d / k;
  }
};

struct square_distance_repulsive_force {
  template<typename Graph, typename T>
  T
  operator()(typename graph_traits<Graph>::vertex_descriptor,
             typename graph_traits<Graph>::vertex_descriptor,
             T k,
             T d,
             const Graph&) const
  {
    return k * k / d;
  }
};

template<typename T>
struct linear_cooling {
  typedef T result_type;

  linear_cooling(std::size_t iterations)
    : temp(T(iterations) / T(10)), step(0.1) { }

  linear_cooling(std::size_t iterations, T temp)
    : temp(temp), step(temp / T(iterations)) { }

  T operator()()
  {
    T old_temp = temp;
    temp -= step;
    if (temp < T(0)) temp = T(0);
    return old_temp;
  }

 private:
  T temp;
  T step;
};

struct all_force_pairs
{
  template<typename Graph, typename ApplyForce >
  void operator()(const Graph& g, ApplyForce apply_force)
  {
    typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;
76
    int i, N = num_vertices(g);
77
    #pragma omp parallel for default(shared) private(i) schedule(dynamic)
78
79
80
81
82
83
84
85
86
87
88
89
    for (i = 0; i < N; ++i)
    {
      typename graph_traits<Graph>::vertex_descriptor v = vertex(i, g);
      if (v == graph_traits<Graph>::null_vertex())
          continue;
      for (int j = i+1; j < N; ++j)
      {
        typename graph_traits<Graph>::vertex_descriptor u = vertex(j, g);
        if (u == graph_traits<Graph>::null_vertex())
            continue;
        apply_force(u, v);
        apply_force(v, u);
Tiago Peixoto's avatar
Tiago Peixoto committed
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
      }
    }
  }
};

template<typename Dim, typename PositionMap>
struct grid_force_pairs
{
  template<typename Graph>
  explicit
  grid_force_pairs(Dim width, Dim height, PositionMap position, const Graph& g)
    : width(width), height(height), position(position)
  {
#ifndef BOOST_NO_STDC_NAMESPACE
    using std::sqrt;
#endif // BOOST_NO_STDC_NAMESPACE
    two_k = Dim(2) * sqrt(width*height / num_vertices(g));
  }

  template<typename Graph, typename ApplyForce >
  void operator()(const Graph& g, ApplyForce apply_force)
  {
    typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;
    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;
    typedef std::list<vertex_descriptor> bucket_t;
    typedef std::vector<bucket_t> buckets_t;

    std::size_t columns = std::size_t(width / two_k + Dim(1));
    std::size_t rows = std::size_t(height / two_k + Dim(1));
    buckets_t buckets(rows * columns);
120
121

    int i, N = num_vertices(g);
122
    #pragma omp parallel for default(shared) private(i) schedule(dynamic)
123
124
125
126
127
128
129
    for (i = 0; i < N; ++i)
    {
      typename graph_traits<Graph>::vertex_descriptor v = vertex(i, g);
      if (v == graph_traits<Graph>::null_vertex())
          continue;
      std::size_t column = std::size_t((position[v].x + width  / 2) / two_k);
      std::size_t row    = std::size_t((position[v].y + height / 2) / two_k);
Tiago Peixoto's avatar
Tiago Peixoto committed
130
131
132

      if (column >= columns) column = columns - 1;
      if (row >= rows) row = rows - 1;
133
134
135
136
      #pragma omp critical
      {
        buckets[row * columns + column].push_back(v);
      }
Tiago Peixoto's avatar
Tiago Peixoto committed
137
138
    }

139
    N = rows * columns;
140
    #pragma omp parallel for default(shared) private(i) schedule(dynamic)
141
142
143
144
    for (i = 0; i < N; ++i)
    {
        std::size_t row = i / rows;
        std::size_t column = i % rows;
Tiago Peixoto's avatar
Tiago Peixoto committed
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
        bucket_t& bucket = buckets[row * columns + column];
        typedef typename bucket_t::iterator bucket_iterator;
        for (bucket_iterator u = bucket.begin(); u != bucket.end(); ++u) {
          // Repulse vertices in this bucket
          bucket_iterator v = u;
          for (++v; v != bucket.end(); ++v) {
            apply_force(*u, *v);
            apply_force(*v, *u);
          }

          std::size_t adj_start_row = row == 0? 0 : row - 1;
          std::size_t adj_end_row = row == rows - 1? row : row + 1;
          std::size_t adj_start_column = column == 0? 0 : column - 1;
          std::size_t adj_end_column = column == columns - 1? column : column + 1;
          for (std::size_t other_row = adj_start_row; other_row <= adj_end_row;
               ++other_row)
161
            for (std::size_t other_column = adj_start_column;
Tiago Peixoto's avatar
Tiago Peixoto committed
162
163
164
                 other_column <= adj_end_column; ++other_column)
              if (other_row != row || other_column != column) {
                // Repulse vertices in this bucket
165
                bucket_t& other_bucket
Tiago Peixoto's avatar
Tiago Peixoto committed
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
                  = buckets[other_row * columns + other_column];
                for (v = other_bucket.begin(); v != other_bucket.end(); ++v)
                  apply_force(*u, *v);
              }
        }
      }
  }

 private:
  Dim width;
  Dim height;
  PositionMap position;
  Dim two_k;
};

template<typename Dim, typename PositionMap, typename Graph>
inline grid_force_pairs<Dim, PositionMap>
make_grid_force_pairs(Dim width, Dim height, const PositionMap& position,
                      const Graph& g)
{ return grid_force_pairs<Dim, PositionMap>(width, height, position, g); }

template<typename Graph, typename PositionMap, typename Dim>
void
scale_graph(const Graph& g, PositionMap position,
            Dim left, Dim top, Dim right, Dim bottom)
{
  if (num_vertices(g) == 0) return;

  if (bottom > top) {
    using std::swap;
    swap(bottom, top);
  }

  typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;

  // Find min/max ranges
  Dim minX = position[*vertices(g).first].x, maxX = minX;
  Dim minY = position[*vertices(g).first].y, maxY = minY;
  vertex_iterator vi, vi_end;
  for (tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi) {
    BOOST_USING_STD_MIN();
    BOOST_USING_STD_MAX();
    minX = min BOOST_PREVENT_MACRO_SUBSTITUTION (minX, position[*vi].x);
    maxX = max BOOST_PREVENT_MACRO_SUBSTITUTION (maxX, position[*vi].x);
    minY = min BOOST_PREVENT_MACRO_SUBSTITUTION (minY, position[*vi].y);
    maxY = max BOOST_PREVENT_MACRO_SUBSTITUTION (maxY, position[*vi].y);
  }

  // Scale to bounding box provided
  for (tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi) {
    position[*vi].x = ((position[*vi].x - minX) / (maxX - minX))
                    * (right - left) + left;
    position[*vi].y = ((position[*vi].y - minY) / (maxY - minY))
                    * (top - bottom) + bottom;
  }
}

namespace detail {
  template<typename PositionMap, typename DisplacementMap,
           typename RepulsiveForce, typename Dim, typename Graph>
  struct fr_apply_force
  {
    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;

    fr_apply_force(const PositionMap& position,
                   const DisplacementMap& displacement,
                   RepulsiveForce repulsive_force, Dim k, const Graph& g)
      : position(position), displacement(displacement),
        repulsive_force(repulsive_force), k(k), g(g)
    { }

    void operator()(vertex_descriptor u, vertex_descriptor v)
    {
#ifndef BOOST_NO_STDC_NAMESPACE
      using std::sqrt;
#endif // BOOST_NO_STDC_NAMESPACE
      if (u != v) {
        Dim delta_x = position[v].x - position[u].x;
        Dim delta_y = position[v].y - position[u].y;
        Dim dist = sqrt(delta_x * delta_x + delta_y * delta_y);
        Dim fr = repulsive_force(u, v, k, dist, g);
247
248
249
250
251
252
253
254
        Dim dx = delta_x / dist * fr;
        Dim dy = delta_y / dist * fr;
        Dim& x = displacement[v].x;
        Dim& y = displacement[v].y;
        #pragma omp atomic
        x += dx;
        #pragma omp atomic
        y += dy;
Tiago Peixoto's avatar
Tiago Peixoto committed
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
      }
    }

  private:
    PositionMap position;
    DisplacementMap displacement;
    RepulsiveForce repulsive_force;
    Dim k;
    const Graph& g;
  };

} // end namespace detail

template<typename Graph, typename PositionMap, typename Dim,
         typename AttractiveForce, typename RepulsiveForce,
         typename ForcePairs, typename Cooling, typename DisplacementMap>
void
fruchterman_reingold_force_directed_layout
 (const Graph&    g,
  PositionMap     position,
  Dim             width,
  Dim             height,
  AttractiveForce attractive_force,
  RepulsiveForce  repulsive_force,
  ForcePairs      force_pairs,
  Cooling         cool,
  DisplacementMap displacement)
{
  typedef typename graph_traits<Graph>::vertex_iterator   vertex_iterator;
  typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;
  typedef typename graph_traits<Graph>::edge_iterator     edge_iterator;
286
  typedef typename graph_traits<Graph>::edge_descriptor   edge_descriptor;
Tiago Peixoto's avatar
Tiago Peixoto committed
287
288
289
290
291
292
293
294
295
296
297
298
299

#ifndef BOOST_NO_STDC_NAMESPACE
  using std::sqrt;
#endif // BOOST_NO_STDC_NAMESPACE

  Dim area = width * height;
  // assume positions are initialized randomly
  Dim k = sqrt(area / num_vertices(g));

  detail::fr_apply_force<PositionMap, DisplacementMap,
                         RepulsiveForce, Dim, Graph>
    apply_force(position, displacement, repulsive_force, k, g);

300
301
302
  std::vector<edge_descriptor> edge_list;
  edge_list.reserve(num_edges(g));
  edge_iterator e, e_end;
303
  for (tie(e, e_end) = edges(g); e != e_end; ++e)
304
305
    edge_list.push_back(*e);

Tiago Peixoto's avatar
Tiago Peixoto committed
306
307
308
  Dim temp = cool();
  if (temp) do {
    // Calculate repulsive forces
309
    int i, N = num_vertices(g);
310
    #pragma omp parallel for default(shared) private(i) schedule(dynamic)
311
312
313
314
315
316
317
    for (i = 0; i < N; ++i)
    {
      typename graph_traits<Graph>::vertex_descriptor v = vertex(i, g);
      if (v == graph_traits<Graph>::null_vertex())
          continue;
      displacement[v].x = 0;
      displacement[v].y = 0;
Tiago Peixoto's avatar
Tiago Peixoto committed
318
319
320
321
    }
    force_pairs(g, apply_force);

    // Calculate attractive forces
322
    N = edge_list.size();
323
    #pragma omp parallel for default(shared) private(i) schedule(dynamic)
324
325
326
327
328
    for (i = 0; i < N; ++i)
    {
      edge_descriptor e = edge_list[i];
      vertex_descriptor v = source(e, g);
      vertex_descriptor u = target(e, g);
Tiago Peixoto's avatar
Tiago Peixoto committed
329
330
331
      Dim delta_x = position[v].x - position[u].x;
      Dim delta_y = position[v].y - position[u].y;
      Dim dist = sqrt(delta_x * delta_x + delta_y * delta_y);
332
      Dim fa = attractive_force(e, k, dist, g);
Tiago Peixoto's avatar
Tiago Peixoto committed
333
334
335
336
337
338
339
340

      displacement[v].x -= delta_x / dist * fa;
      displacement[v].y -= delta_y / dist * fa;
      displacement[u].x += delta_x / dist * fa;
      displacement[u].y += delta_y / dist * fa;
    }

    // Update positions
341
    N = num_vertices(g);
342
    #pragma omp parallel for default(shared) private(i) schedule(dynamic)
343
344
345
346
347
348
    for (i = 0; i < N; ++i)
    {
      typename graph_traits<Graph>::vertex_descriptor v = vertex(i, g);
      if (v == graph_traits<Graph>::null_vertex())
          continue;

Tiago Peixoto's avatar
Tiago Peixoto committed
349
350
      BOOST_USING_STD_MIN();
      BOOST_USING_STD_MAX();
351
352
      Dim disp_size = sqrt(displacement[v].x * displacement[v].x
                           + displacement[v].y * displacement[v].y);
353
      position[v].x += displacement[v].x / disp_size
Tiago Peixoto's avatar
Tiago Peixoto committed
354
                     * min BOOST_PREVENT_MACRO_SUBSTITUTION (disp_size, temp);
355
      position[v].y += displacement[v].y / disp_size
Tiago Peixoto's avatar
Tiago Peixoto committed
356
                     * min BOOST_PREVENT_MACRO_SUBSTITUTION (disp_size, temp);
357
358
359
      position[v].x = min BOOST_PREVENT_MACRO_SUBSTITUTION
                         (width / 2,
                          max BOOST_PREVENT_MACRO_SUBSTITUTION(-width / 2,
360
361
                                                               position[v].x));
      position[v].y = min BOOST_PREVENT_MACRO_SUBSTITUTION
362
363
                         (height / 2,
                          max BOOST_PREVENT_MACRO_SUBSTITUTION(-height / 2,
364
                                                               position[v].y));
Tiago Peixoto's avatar
Tiago Peixoto committed
365
    }
366
   } while ( (temp = cool()) );
Tiago Peixoto's avatar
Tiago Peixoto committed
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
}

namespace detail {
  template<typename DisplacementMap>
  struct fr_force_directed_layout
  {
    template<typename Graph, typename PositionMap, typename Dim,
             typename AttractiveForce, typename RepulsiveForce,
             typename ForcePairs, typename Cooling,
             typename Param, typename Tag, typename Rest>
    static void
    run(const Graph&    g,
        PositionMap     position,
        Dim             width,
        Dim             height,
        AttractiveForce attractive_force,
        RepulsiveForce  repulsive_force,
        ForcePairs      force_pairs,
        Cooling         cool,
        DisplacementMap displacement,
        const bgl_named_params<Param, Tag, Rest>&)
    {
      fruchterman_reingold_force_directed_layout
        (g, position, width, height, attractive_force, repulsive_force,
         force_pairs, cool, displacement);
    }
  };

  template<>
  struct fr_force_directed_layout<error_property_not_found>
  {
    template<typename Graph, typename PositionMap, typename Dim,
             typename AttractiveForce, typename RepulsiveForce,
             typename ForcePairs, typename Cooling,
             typename Param, typename Tag, typename Rest>
    static void
    run(const Graph&    g,
        PositionMap     position,
        Dim             width,
        Dim             height,
        AttractiveForce attractive_force,
        RepulsiveForce  repulsive_force,
        ForcePairs      force_pairs,
        Cooling         cool,
        error_property_not_found,
        const bgl_named_params<Param, Tag, Rest>& params)
    {
414
      std::vector<simple_point<Dim> > displacements(num_vertices(g));
Tiago Peixoto's avatar
Tiago Peixoto committed
415
416
417
418
419
420
421
      fruchterman_reingold_force_directed_layout
        (g, position, width, height, attractive_force, repulsive_force,
         force_pairs, cool,
         make_iterator_property_map
         (displacements.begin(),
          choose_const_pmap(get_param(params, vertex_index), g,
                            vertex_index),
422
          simple_point<Dim>()));
Tiago Peixoto's avatar
Tiago Peixoto committed
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
    }
  };

} // end namespace detail

template<typename Graph, typename PositionMap, typename Dim, typename Param,
         typename Tag, typename Rest>
void
fruchterman_reingold_force_directed_layout
  (const Graph&    g,
   PositionMap     position,
   Dim             width,
   Dim             height,
   const bgl_named_params<Param, Tag, Rest>& params)
{
  typedef typename property_value<bgl_named_params<Param,Tag,Rest>,
                                  vertex_displacement_t>::type D;

  detail::fr_force_directed_layout<D>::run
    (g, position, width, height,
     choose_param(get_param(params, attractive_force_t()),
                  square_distance_attractive_force()),
     choose_param(get_param(params, repulsive_force_t()),
                  square_distance_repulsive_force()),
     choose_param(get_param(params, force_pairs_t()),
                  make_grid_force_pairs(width, height, position, g)),
     choose_param(get_param(params, cooling_t()),
450
                  linear_cooling<Dim>(100)),
Tiago Peixoto's avatar
Tiago Peixoto committed
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
     get_param(params, vertex_displacement_t()),
     params);
}

template<typename Graph, typename PositionMap, typename Dim>
void
fruchterman_reingold_force_directed_layout(const Graph&    g,
                                           PositionMap     position,
                                           Dim             width,
                                           Dim             height)
{
  fruchterman_reingold_force_directed_layout
    (g, position, width, height,
     attractive_force(square_distance_attractive_force()));
}

} // end namespace boost

#endif // BOOST_GRAPH_FRUCHTERMAN_REINGOLD_FORCE_DIRECTED_LAYOUT_HPP