__init__.py 24.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#! /usr/bin/env python
# graph_tool.py -- a general graph manipulation python module
#
# Copyright (C) 2007 Tiago de Paula Peixoto <tiago@forked.de>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

19
"""
20
``graph_tool.generation`` - Random graph generation
21
---------------------------------------------------
22
23
24
25
26
27
28
29
30
31
32
33

Summary
+++++++

.. autosummary::
   :nosignatures:

   random_graph
   random_rewire
   predecessor_tree
   line_graph
   graph_union
34
   triangulation
35
36
37

Contents
++++++++
38
39
"""

Tiago Peixoto's avatar
Tiago Peixoto committed
40
41
from .. dl_import import dl_import
dl_import("import libgraph_tool_generation")
42

43
from .. core import Graph, _check_prop_scalar, _prop, _limit_args
44
import sys, numpy, numpy.random
45

Tiago Peixoto's avatar
Tiago Peixoto committed
46
__all__ = ["random_graph", "random_rewire", "predecessor_tree", "line_graph",
47
           "graph_union", "triangulation"]
48

49
50
51
def _corr_wrap(i, j, corr):
    return corr(i[1], j[1])

52
def random_graph(N, deg_sampler, deg_corr=None, directed=True,
53
                 parallel_edges=False, self_loops=False, verbose=False):
Tiago Peixoto's avatar
Tiago Peixoto committed
54
55
56
57
58
59
60
61
62
63
64
65
66
67
    r"""
    Generate a random graph, with a given degree distribution and correlation.

    Parameters
    ----------
    N : int
        Number of vertices in the graph.
    deg_sampler : function
        A degree sampler function which is called without arguments, and returns
        a tuple of ints representing the in and out-degree of a given vertex (or
        a single int for undirected graphs, representing the out-degree). This
        function is called once per vertex, but may be called more times, if the
        degree sequence cannot be used to build a graph.
    deg_corr : function (optional, default: None)
Tiago Peixoto's avatar
Tiago Peixoto committed
68
        A function which gives the degree correlation of the graph. It should be
Tiago Peixoto's avatar
Tiago Peixoto committed
69
70
71
72
73
74
75
        callable with two parameters: the in,out-degree pair of the source
        vertex an edge, and the in,out-degree pair of the target of the same
        edge (for undirected graphs, both parameters are single values). The
        function should return a number proportional to the probability of such
        an edge existing in the generated graph.
    directed : bool (optional, default: True)
        Whether the generated graph should be directed.
76
    parallel_edges : bool (optional, default: False)
Tiago Peixoto's avatar
Tiago Peixoto committed
77
78
79
        If True, parallel edges are allowed.
    self_loops : bool (optional, default: False)
        If True, self-loops are allowed.
80
81
    verbose : bool (optional, default: False)
        If True, verbose information is displayed.
Tiago Peixoto's avatar
Tiago Peixoto committed
82
83
84

    Returns
    -------
85
    random_graph : :class:`~graph_tool.Graph`
Tiago Peixoto's avatar
Tiago Peixoto committed
86
87
88
89
90
91
92
93
94
95
96
97
98
99
        The generated graph.

    See Also
    --------
    random_rewire: in place graph shuffling

    Notes
    -----
    The algorithm maintains a list of all available source and target degree
    pairs, such that the deg_corr function is called only once with the same
    parameters.

    The uncorrelated case, the complexity is :math:`O(V+E)`. For the correlated
    case the worst-case complexity is :math:`O(V^2)`, but the typical case has
100
101
    complexity :math:`O(V + E\log N_k + N_k^2)`, where :math:`N_k < V` is the
    number of different degrees sampled (or in,out-degree pairs).
Tiago Peixoto's avatar
Tiago Peixoto committed
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

    Examples
    --------

    >>> from numpy.random import randint, random, seed, poisson
    >>> from pylab import *
    >>> seed(42)

    This is a degree sampler which uses rejection sampling to sample from the
    distribution :math:`P(k)\propto 1/k`, up to a maximum.

    >>> def sample_k(max):
    ...     accept = False
    ...     while not accept:
    ...         k = randint(1,max+1)
    ...         accept = random() < 1.0/k
    ...     return k
    ...

    The following generates a random undirected graph with degree distribution
    :math:`P(k)\propto 1/k` (with k_max=40) and an *assortative* degree
    correlation of the form:

    .. math::

        P(i,k) \propto \frac{1}{1+|i-k|}

    >>> g = gt.random_graph(1000, lambda: sample_k(40),
    ...                     lambda i,k: 1.0/(1+abs(i-k)), directed=False)
    >>> gt.scalar_assortativity(g, "out")
Tiago Peixoto's avatar
Tiago Peixoto committed
132
    (0.60296352140954257, 0.011780362691333932)
Tiago Peixoto's avatar
Tiago Peixoto committed
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

    The following samples an in,out-degree pair from the joint distribution:

    .. math::

        p(j,k) = \frac{1}{2}\frac{e^{-m_1}m_1^j}{j!}\frac{e^{-m_1}m_1^k}{k!} +
                 \frac{1}{2}\frac{e^{-m_2}m_2^j}{j!}\frac{e^{-m_2}m_2^k}{k!}

    with :math:`m_1 = 4` and :math:`m_2 = 20`.

    >>> def deg_sample():
    ...    if random() > 0.5:
    ...        return poisson(4), poisson(4)
    ...    else:
    ...        return poisson(20), poisson(20)
    ...

    The following generates a random directed graph with this distribution, and
    plots the combined degree correlation.

    >>> g = gt.random_graph(20000, deg_sample)
    >>>
    >>> hist = gt.combined_corr_hist(g, "in", "out")
    >>> imshow(hist[0], interpolation="nearest")
    <...>
    >>> colorbar()
    <...>
160
    >>> xlabel("in-degree")
Tiago Peixoto's avatar
Tiago Peixoto committed
161
    <...>
162
    >>> ylabel("out-degree")
Tiago Peixoto's avatar
Tiago Peixoto committed
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
    <...>
    >>> savefig("combined-deg-hist.png")

    .. figure:: combined-deg-hist.png
        :align: center

        Combined degree histogram.

    A correlated directed graph can be build as follows. Consider the following
    degree correlation:

    .. math::

         P(j',k'|j,k)=\frac{e^{-k}k^{j'}}{j'!}
         \frac{e^{-(20-j)}(20-j)^{k'}}{k'!}

    i.e., the in->out correlation is "disassortative", the out->in correlation
    is "assortative", and everything else is uncorrelated.
    We will use a flat degree distribution in the range [1,20).

    >>> p = scipy.stats.poisson
    >>> g = gt.random_graph(20000, lambda: (sample_k(19), sample_k(19)),
    ...                                     lambda a,b: (p.pmf(a[0],b[1])*
    ...                                                  p.pmf(a[1],20-b[0])))

    Lets plot the average degree correlations to check.

190
191
192
193
    >>> figure(figsize=(6,3))
    <...>
    >>> axes([0.1,0.15,0.63,0.8])
    <...>
Tiago Peixoto's avatar
Tiago Peixoto committed
194
    >>> corr = gt.avg_neighbour_corr(g, "in", "in")
195
196
    >>> errorbar(corr[2], corr[0], yerr=corr[1], fmt="o-",
    ...         label=r"$\left<\text{in}\right>$ vs in")
Tiago Peixoto's avatar
Tiago Peixoto committed
197
198
    (...)
    >>> corr = gt.avg_neighbour_corr(g, "in", "out")
199
200
    >>> errorbar(corr[2], corr[0], yerr=corr[1], fmt="o-",
    ...         label=r"$\left<\text{out}\right>$ vs in")
Tiago Peixoto's avatar
Tiago Peixoto committed
201
202
    (...)
    >>> corr = gt.avg_neighbour_corr(g, "out", "in")
203
204
    >>> errorbar(corr[2], corr[0], yerr=corr[1], fmt="o-",
    ...          label=r"$\left<\text{in}\right>$ vs out")
Tiago Peixoto's avatar
Tiago Peixoto committed
205
206
    (...)
    >>> corr = gt.avg_neighbour_corr(g, "out", "out")
207
208
    >>> errorbar(corr[2], corr[0], yerr=corr[1], fmt="o-",
    ...          label=r"$\left<\text{out}\right>$ vs out")
Tiago Peixoto's avatar
Tiago Peixoto committed
209
    (...)
210
    >>> legend(loc=(1.05,0.5))
Tiago Peixoto's avatar
Tiago Peixoto committed
211
212
213
214
215
216
217
218
219
220
221
222
    <...>
    >>> xlabel("source degree")
    <...>
    >>> ylabel("average target degree")
    <...>
    >>> savefig("deg-corr-dir.png")

    .. figure:: deg-corr-dir.png
        :align: center

        Average nearest neighbour correlations.
    """
223
    seed = numpy.random.randint(0, sys.maxint)
224
225
226
227
228
    g = Graph()
    if deg_corr == None:
        uncorrelated = True
    else:
        uncorrelated = False
229
230
    libgraph_tool_generation.gen_random_graph(g._Graph__graph, N, deg_sampler,
                                              uncorrelated, not parallel_edges,
231
232
233
                                              not self_loops, not directed,
                                              seed, verbose)
    g.set_directed(directed)
234
235
236
237
238
239
    random_rewire(g, parallel_edges = parallel_edges, self_loops = self_loops,
                  verbose = verbose)
    if deg_corr != None:
        random_rewire(g, strat = "probabilistic",
                      parallel_edges = parallel_edges, deg_corr = deg_corr,
                      self_loops = self_loops, verbose = verbose)
240
    return g
241

242
@_limit_args({"strat":["erdos", "correlated", "uncorrelated", "probabilistic"]})
243
def random_rewire(g, strat= "uncorrelated", parallel_edges = False,
244
                  self_loops = False, deg_corr = None, verbose = False):
245
    r"""
246
247
    Shuffle the graph in-place. If `strat` != "erdos", the degrees (either in or
    out) of each vertex are always the same, but otherwise the edges are
248
    randomly placed. If `strat` = "correlated", the degree correlations are
249
    also maintained: The new source and target of each edge both have the same
Tiago Peixoto's avatar
Tiago Peixoto committed
250
251
    in and out-degree. If `strat` = "probabilistic", than edges are rewired
    according to the degree correlation given by the parameter `deg_corr`.
252
253
254

    Parameters
    ----------
255
    g : :class:`~graph_tool.Graph`
256
257
        Graph to be shuffled. The graph will be modified.
    strat : string (optional, default: "uncorrelated")
258
259
260
261
        If `strat` == "erdos", the resulting graph will be entirely random. If
        `strat` == "uncorrelated" only the degrees of the vertices will be
        maintained, nothing else. If `strat` == "correlated", additionally the
        new source and target of each edge both have the same in and out-degree.
262
263
        If `strat` == "probabilistic", than edges are rewired according to the
        degree correlation given by the parameter `deg_corr`.
264
265
266
267
    parallel : bool (optional, default: False)
        If True, parallel edges are allowed.
    self_loops : bool (optional, default: False)
        If True, self-loops are allowed.
268
269
270
271
272
273
274
275
276
277
    deg_corr : function (optional, default: None)
        A function which gives the degree correlation of the graph. It should be
        callable with two parameters: the in,out-degree pair of the source
        vertex an edge, and the in,out-degree pair of the target of the same
        edge (for undirected graphs, both parameters are single values). The
        function should return a number proportional to the probability of such
        an edge existing in the generated graph. This parameter is ignored,
        unless `strat` = "probabilistic".
    verbose : bool (optional, default: False)
        If True, verbose information is displayed.
278
279
280
281
282
283
284

    See Also
    --------
    random_graph: random graph generation

    Notes
    -----
Tiago Peixoto's avatar
Tiago Peixoto committed
285
286
287
288
289
290
291
292
293
    This algorithm iterates through all the edges in the network and tries to
    swap its target our edge with another edge.

    .. note::
        If `parallel_edges` = False, parallel edges are not placed during
        rewiring. In this case, for some special graphs it may be necessary to
        call the function more than once to obtain a graph which corresponds to
        a uniform sample from the ensemble. But typically, if the graph is
        sufficiently large, a single call should be enough.
294
295

    Each edge gets swapped at least once, so the overall complexity is
Tiago Peixoto's avatar
Tiago Peixoto committed
296
297
298
299
    :math:`O(E)`. If `strat` = "probabilistic" the complexity is
    :math:`O(E\log N_k)`,  where :math:`N_k < V` is the number of different
    degrees (or in,out-degree pairs).

300
301
302
303
304
305

    Examples
    --------

    Some small graphs for visualization.

306
    >>> from numpy.random import random, seed
307
308
    >>> from pylab import *
    >>> seed(42)
309
    >>> g, pos = gt.triangulation(random((1000,2)))
310
    >>> gt.graph_draw(g, layout="arf", output="rewire_orig.png", size=(6,6))
311
    <...>
312
    >>> gt.random_rewire(g, "correlated")
313
    >>> gt.graph_draw(g, layout="arf", output="rewire_corr.png", size=(6,6))
314
    <...>
315
    >>> gt.random_rewire(g)
316
    >>> gt.graph_draw(g, layout="arf", output="rewire_uncorr.png", size=(6,6))
317
    <...>
318
319
320
    >>> gt.random_rewire(g, "erdos")
    >>> gt.graph_draw(g, layout="arf", output="rewire_erdos.png", size=(6,6))
    <...>
321

322
    Some `ridiculograms <http://www.youtube.com/watch?v=YS-asmU3p_4>`_ :
323

324
325
326
    .. image:: rewire_orig.png
    .. image:: rewire_corr.png
    .. image:: rewire_uncorr.png
327
    .. image:: rewire_erdos.png
328

329
330
331
    *From left to right:* Original graph; Shuffled graph, with degree
    correlations; Shuffled graph, without degree correlations; Shuffled graph,
    with random degrees.
332
333
334

    We can try some larger graphs to get better statistics.

335
336
    >>> figure()
    <...>
337
    >>> g = gt.random_graph(30000, lambda: sample_k(20),
338
339
    ...                     lambda i,j: exp(abs(i-j)), directed=False)
    >>> corr = gt.avg_neighbour_corr(g, "out", "out")
340
    >>> errorbar(corr[2], corr[0], yerr=corr[1], fmt="o-", label="original")
341
342
343
    (...)
    >>> gt.random_rewire(g, "correlated")
    >>> corr = gt.avg_neighbour_corr(g, "out", "out")
344
    >>> errorbar(corr[2], corr[0], yerr=corr[1], fmt="*", label="correlated")
345
346
347
    (...)
    >>> gt.random_rewire(g)
    >>> corr = gt.avg_neighbour_corr(g, "out", "out")
348
    >>> errorbar(corr[2], corr[0], yerr=corr[1], fmt="o-", label="uncorrelated")
349
    (...)
350
351
352
353
    >>> gt.random_rewire(g, "erdos")
    >>> corr = gt.avg_neighbour_corr(g, "out", "out")
    >>> errorbar(corr[2], corr[0], yerr=corr[1], fmt="o-", label="Erdos")
    (...)
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
    >>> xlabel("$k$")
    <...>
    >>> ylabel(r"$\left<k_{nn}\right>$")
    <...>
    >>> legend(loc="best")
    <...>
    >>> savefig("shuffled-stats.png")

    .. figure:: shuffled-stats.png
        :align: center

        Average degree correlations for the different shuffled and non-shuffled
        graphs. The shuffled graph with correlations displays exactly the same
        correlation as the original graph.

    Now let's do it for a directed graph. See
    :func:`~graph_tool.generation.random_graph` for more details.

    >>> p = scipy.stats.poisson
    >>> g = gt.random_graph(20000, lambda: (sample_k(19), sample_k(19)),
Tiago Peixoto's avatar
Tiago Peixoto committed
374
    ...                     lambda a,b: (p.pmf(a[0],b[1])*p.pmf(a[1],20-b[0])))
375
376
377
378
    >>> figure(figsize=(6,3))
    <...>
    >>> axes([0.1,0.15,0.6,0.8])
    <...>
379
    >>> corr = gt.avg_neighbour_corr(g, "in", "out")
380
381
    >>> errorbar(corr[2], corr[0], yerr=corr[1], fmt="o-",
    ...          label=r"$\left<\text{o}\right>$ vs i")
382
383
    (...)
    >>> corr = gt.avg_neighbour_corr(g, "out", "in")
384
385
    >>> errorbar(corr[2], corr[0], yerr=corr[1], fmt="o-",
    ...          label=r"$\left<\text{i}\right>$ vs o")
386
387
388
389
    (...)
    >>> gt.random_rewire(g, "correlated")
    >>> corr = gt.avg_neighbour_corr(g, "in", "out")
    >>> errorbar(corr[2], corr[0], yerr=corr[1], fmt="o-",
390
    ...          label=r"$\left<\text{o}\right>$ vs i, corr.")
391
392
393
    (...)
    >>> corr = gt.avg_neighbour_corr(g, "out", "in")
    >>> errorbar(corr[2], corr[0], yerr=corr[1], fmt="o-",
394
    ...          label=r"$\left<\text{i}\right>$ vs o, corr.")
395
396
397
398
    (...)
    >>> gt.random_rewire(g, "uncorrelated")
    >>> corr = gt.avg_neighbour_corr(g, "in", "out")
    >>> errorbar(corr[2], corr[0], yerr=corr[1], fmt="o-",
399
    ...          label=r"$\left<\text{o}\right>$ vs i, uncorr.")
400
401
402
    (...)
    >>> corr = gt.avg_neighbour_corr(g, "out", "in")
    >>> errorbar(corr[2], corr[0], yerr=corr[1], fmt="o-",
403
    ...          label=r"$\left<\text{i}\right>$ vs o, uncorr.")
404
    (...)
405
    >>> legend(loc=(1.05,0.45))
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
    <...>
    >>> xlabel("source degree")
    <...>
    >>> ylabel("average target degree")
    <...>
    >>> savefig("shuffled-deg-corr-dir.png")

    .. figure:: shuffled-deg-corr-dir.png
        :align: center

        Average degree correlations for the different shuffled and non-shuffled
        directed graphs. The shuffled graph with correlations displays exactly
        the same correlation as the original graph.
    """

421
    seed = numpy.random.randint(0, sys.maxint)
422

423
424
425
426
427
    if not g.is_directed() and deg_corr != None:
        corr = lambda i,j: _corr_wrap(i, j, deg_corr)
    else:
        corr = deg_corr

428
    g.stash_filter(reversed=True)
429
430
    try:
        libgraph_tool_generation.random_rewire(g._Graph__graph, strat,
431
432
                                               self_loops, parallel_edges,
                                               corr, seed, verbose)
433
434
    finally:
        g.pop_filter(reversed=True)
Tiago Peixoto's avatar
Tiago Peixoto committed
435
436
437
438
439
440
441
442
443
444
445

def predecessor_tree(g, pred_map):
    """Return a graph from a list of predecessors given by
    the 'pred_map' vertex property."""

    _check_prop_scalar(pred_map, "pred_map")
    pg = Graph()
    libgraph_tool_generation.predecessor_graph(g._Graph__graph,
                                               pg._Graph__graph,
                                               _prop("v", g, pred_map))
    return pg
446
447

def line_graph(g):
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
    """Return the line graph of the given graph `g`.

    Notes
    -----
    Given an undirected graph G, its line graph L(G) is a graph such that

        * each vertex of L(G) represents an edge of G; and
        * two vertices of L(G) are adjacent if and only if their corresponding
          edges share a common endpoint ("are adjacent") in G.

    For a directed graph, the second criterion becomes:

       * Two vertices representing directed edges from u to v and from w to x in
         G are connected by an edge from uv to wx in the line digraph when v =
         w.

    References
    ----------
    .. [line-wiki] http://en.wikipedia.org/wiki/Line_graph
    """
468
469
470
471
472
473
474
475
    lg = Graph(directed=g.is_directed())

    vertex_map = lg.new_vertex_property("int64_t")

    libgraph_tool_generation.line_graph(g._Graph__graph,
                                        lg._Graph__graph,
                                        _prop("v", lg, vertex_map))
    return lg, vertex_map
Tiago Peixoto's avatar
Tiago Peixoto committed
476
477

def graph_union(g1, g2, props=[], include=False):
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
    """Return the union of graphs g1 and g2, composed of all edges and vertices
    of g1 and g2, without overlap.

    Parameters
    ----------
    g1 : :class:`~graph_tool.Graph`
       First graph in the union.
    g2 : :class:`~graph_tool.Graph`
       Second graph in the union.
    props : list of tuples of :class:`~graph_tool.PropertyMap` (optional, default: [])
       Each element in this list must be a tuple of two PropertyMap objects. The
       first element must be a property of `g1`, and the second of `g2`. The
       values of the property maps are propagated into the union graph, and
       returned.
    include : bool (optional, default: False)
       If true, graph `g2` is inserted into `g1` which is modified. If false, a
       new graph is created, and both graphs remain unmodified.

    Returns
    -------
    ug : :class:`~graph_tool.Graph`
        The union graph
    props : list of :class:`~graph_tool.PropertyMap` objects
        List of propagated properties.  This is only returned if `props` is not
        empty.
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522

    Examples
    --------

    >>> from numpy.random import random, seed
    >>> seed(42)
    >>> g = gt.triangulation(random((300,2)))[0]
    >>> ug = gt.graph_union(g, g)
    >>> uug = gt.graph_union(g, ug)
    >>> gt.graph_draw(g, layout="arf", size=(8,8), output="graph_original.png")
    <...>
    >>> gt.graph_draw(ug, layout="arf", size=(8,8), output="graph_union.png")
    <...>
    >>> gt.graph_draw(uug, layout="arf", size=(8,8), output="graph_union2.png")
    <...>

    .. image:: graph_original.png
    .. image:: graph_union.png
    .. image:: graph_union2.png

523
    """
Tiago Peixoto's avatar
Tiago Peixoto committed
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
    if not include:
        g1 = Graph(g1)
    g1.stash_filter(directed=True)
    g1.set_directed(True)
    g2.stash_filter(directed=True)
    g2.set_directed(True)
    n_props = []

    try:
        vmap, emap = libgraph_tool_generation.graph_union(g1._Graph__graph,
                                                          g2._Graph__graph)
        for p in props:
            p1, p2 = p
            if not include:
                p1 = g1.copy_property(p1)
            if p2.value_type() != p1.value_type():
                p2 = g2.copy_property(p2, value_type=p1.value_type())
            if p1.key_type() == 'v':
                libgraph_tool_generation.\
                      vertex_property_union(g1._Graph__graph, g2._Graph__graph,
                                            vmap, emap,
                                            _prop(p1.key_type(), g1, p1),
                                            _prop(p2.key_type(), g2, p2))
            else:
                libgraph_tool_generation.\
                      edge_property_union(g1._Graph__graph, g2._Graph__graph,
                                          vmap, emap,
                                          _prop(p1.key_type(), g1, p1),
                                          _prop(p2.key_type(), g2, p2))
            n_props.append(p1)
    finally:
        g1.pop_filter(directed=True)
        g2.pop_filter(directed=True)

    if len(n_props) > 0:
        return g1, n_props
    else:
        return g1
562
563

@_limit_args({"type":["simple", "delaunay"]})
564
def triangulation(points, type="simple", periodic=False):
565
566
567
568
569
570
571
572
573
574
    r"""
    Generate a 2D or 3D triangulation graph from a given point set.

    Parameters
    ----------
    points : :class:`~numpy.ndarray`
        Point set for the triangulation. It may be either a N x d array, where N
        is the number of points, and d is the space dimension (either 2 or 3).
    type : string (optional, default: 'simple')
        Type of triangulation. May be either 'simple' or 'delaunay'.
575
576
577
    periodic : bool (optional, default: False)
        If True, periodic boundary conditions will be used. This is parameter is
        valid only for type="delaunay", and is otherwise ignored.
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592

    Returns
    -------
    triangulation_graph : :class:`~graph_tool.Graph`
        The generated graph.
    pos : :class:`~graph_tool.PropertyMap`
        Vertex property map with the Cartesian coordinates.

    See Also
    --------
    random_graph: random graph generation

    Notes
    -----

Tiago Peixoto's avatar
Tiago Peixoto committed
593
    A triangulation [cgal-triang]_ is a division of the convex hull of a point
594
    set into triangles, using only that set as triangle vertices.
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613

    In simple triangulations (`type="simple"`), the insertion of a point is done
    by locating a face that contains the point, and splitting this face into
    three new faces (the order of insertion is therefore important). If the
    point falls outside the convex hull, the triangulation is restored by
    flips. Apart from the location, insertion takes a time O(1). This bound is
    only an amortized bound for points located outside the convex hull.

    Delaunay triangulations (`type="delaunay"`) have the specific empty sphere
    property, that is, the circumscribing sphere of each cell of such a
    triangulation does not contain any other vertex of the triangulation in its
    interior. These triangulations are uniquely defined except in degenerate
    cases where five points are co-spherical. Note however that the CGAL
    implementation computes a unique triangulation even in these cases.

    Examples
    --------
    >>> from numpy.random import seed, random
    >>> seed(42)
614
    >>> points = random((500,2))*4
615
    >>> g, pos = gt.triangulation(points)
616
617
618
619
620
621
622
623
624
    >>> weight = g.new_edge_property("double") # Edge weights corresponding to
    ...                                        # Euclidean distances
    >>> for e in g.edges():
    ...    weight[e] = sqrt(sum((array(pos[e.source()]) -
    ...                          array(pos[e.target()]))**2))
    >>> b = gt.betweenness(g, weight=weight)
    >>> b[1].a *= 100
    >>> gt.graph_draw(g, pos=pos, pin=True, size=(8,8), vsize=0.07, vcolor=b[0],
    ...               eprops={"penwidth":b[1]}, output="triang.png")
625
626
    <...>
    >>> g, pos = gt.triangulation(points, type="delaunay")
627
628
629
630
631
632
633
634
    >>> weight = g.new_edge_property("double")
    >>> for e in g.edges():
    ...    weight[e] = sqrt(sum((array(pos[e.source()]) -
    ...                          array(pos[e.target()]))**2))
    >>> b = gt.betweenness(g, weight=weight)
    >>> b[1].a *= 120
    >>> gt.graph_draw(g, pos=pos, pin=True, size=(8,8), vsize=0.07, vcolor=b[0],
    ...               eprops={"penwidth":b[1]}, output="triang-delaunay.png")
635
636
637
638
639
640
641
    <...>

    2D triangulation of random points:

    .. image:: triang.png
    .. image:: triang-delaunay.png

642
643
644
    *Left:* Simple triangulation. *Right:* Delaunay triangulation. The vertex
    colors and the edge thickness correspond to the weighted betweenness
    centrality.
645
646
647

    References
    ----------
Tiago Peixoto's avatar
Tiago Peixoto committed
648
    .. [cgal-triang] http://www.cgal.org/Manual/last/doc_html/cgal_manual/Triangulation_3/Chapter_main.html
649
650
651
652
653
654
655
656
657
658
659
660
661
662

    """

    if points.shape[1] not in [2,3]:
        raise ValueError("points array must have shape N x d, with d either 2 or 3.")
    # copy points to ensure continuity and correct data type
    points = numpy.array(points, dtype='float64')
    if points.shape[1] == 2:
        npoints = numpy.zeros((points.shape[0], 3))
        npoints[:,:2] = points
        points = npoints
    g = Graph(directed=False)
    pos = g.new_vertex_property("vector<double>")
    libgraph_tool_generation.triangulation(g._Graph__graph, points,
663
                                           _prop("v", g, pos), type, periodic)
664
665
    return g, pos