graph_community.hh 26.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
// graph-tool -- a general graph modification and manipulation thingy
//
// 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/>.

#ifndef GRAPH_COMMUNITY_HH
#define GRAPH_COMMUNITY_HH

#include <boost/random.hpp>
#include <tr1/unordered_set>
#include <fstream>
#include <iomanip>

#include "graph_util.hh"
#include "graph_properties.hh"

namespace graph_tool
{

using namespace std;
using namespace boost;

using std::tr1::unordered_map;
using std::tr1::unordered_set;

typedef boost::mt19937 rng_t;

// computes the community structure through a spin glass system with
// simulated annealing

template <template <class G, class CommunityMap> class NNKS>
struct get_communities
{
    template <class Graph, class WeightMap, class CommunityMap>
47
    void operator()(const Graph& g, WeightMap weights, CommunityMap s,
48 49 50 51 52 53 54
                    double gamma, size_t n_iter, pair<double,double> Tinterval,
                    pair<size_t,bool> Nspins, size_t seed,
                    pair<bool,string> verbose) const
    {
        typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;
        typedef typename graph_traits<Graph>::edge_descriptor edge_t;
        typedef typename property_traits<WeightMap>::key_type weight_key_t;
55

56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
        size_t N = HardNumVertices()(&g);

        stringstream out_str;
        ofstream out_file;
        if (verbose.second != "")
        {
            out_file.open(verbose.second.c_str());
            if (!out_file.is_open())
                throw GraphException("error opening file " + verbose.second +
                                     " for writing");
            out_file.exceptions (ifstream::eofbit | ifstream::failbit |
                                 ifstream::badbit);
        }

        double Tmin = Tinterval.first;
        double Tmax = Tinterval.second;

        rng_t rng(static_cast<rng_t::result_type>(seed));
        boost::uniform_real<double> uniform_p(0.0,1.0);

        if (Nspins.first == 0)
            Nspins.first = HardNumVertices()(&g);

        unordered_map<size_t, size_t> Ns; // spin histogram
        // global energy term
        unordered_map<size_t, map<double, unordered_set<size_t> > > global_term;

        // init spins from [0,N-1] and global info
        uniform_int<size_t> sample_spin(0, Nspins.first-1);
        unordered_set<size_t> deg_set;
        typename graph_traits<Graph>::vertex_iterator v,v_end;
        for (tie(v,v_end) = vertices(g); v != v_end; ++v)
        {
            if (Nspins.second)
                s[*v] = sample_spin(rng);
            Ns[s[*v]]++;
            deg_set.insert(out_degree_no_loops(*v, g));
        }

        NNKS<Graph,CommunityMap> Nnnks(g, s); // this will retrieve the expected
                                              // number of neighbours with given
                                              // spin, in funcion of degree

        // setup global energy terms for all degrees and spins
        vector<size_t> degs;
        for (typeof(deg_set.begin()) iter = deg_set.begin();
             iter != deg_set.end(); ++iter)
            degs.push_back(*iter);
        for (size_t i = 0; i < degs.size(); ++i)
            for (size_t sp = 0; sp < Nspins.first; ++sp)
                global_term[degs[i]][gamma*Nnnks(degs[i],sp)].insert(sp);


        // define cooling rate so that temperature starts at Tmax at temp_count
        // == 0 and reaches Tmin at temp_count == n_iter - 1
        if (Tmin < numeric_limits<double>::epsilon())
            Tmin = numeric_limits<double>::epsilon();
        double cooling_rate = -(log(Tmin)-log(Tmax))/(n_iter-1);

        // start the annealing
        for (size_t temp_count = 0; temp_count < n_iter; ++temp_count)
        {
            double T = Tmax*exp(-cooling_rate*temp_count);

            bool steepest_descent = false; // flags if temperature is too low

            // calculate the cumulative probabilities of each spin energy level
            unordered_map<size_t, map<long double, pair<double, bool> > >
                cumm_prob;
            unordered_map<size_t, unordered_map<double, long double> >
                energy_to_prob;
            int i, NK = degs.size();
#ifdef USING_OPENMP
            for (i = 0; i < NK; ++i)
            {
                cumm_prob[degs[i]];
                energy_to_prob[degs[i]];
            }
#endif //USING_OPENMP
            #pragma omp parallel for default(shared) private(i)\
                schedule(dynamic)
            for (i = 0; i < NK; ++i)
            {
                long double prob = 0;
                for (typeof(global_term[degs[i]].begin()) iter =
                         global_term[degs[i]].begin();
                     iter != global_term[degs[i]].end(); ++iter)
                {
                    long double M = log(numeric_limits<long double>::max()/
                                        (Nspins.first*10));
                    long double this_prob =
                        exp((long double)(-iter->first - degs[i])/T + M)*
                        iter->second.size();

                    if (prob + this_prob != prob)
                    {
                        prob += this_prob;
                        cumm_prob[degs[i]][prob] = make_pair(iter->first, true);
                        energy_to_prob[degs[i]][iter->first] = prob;
                    }
                    else
                    {
                        energy_to_prob[degs[i]][iter->first] = 0;
                    }
                }
                if (prob == 0.0)
                {
                    #pragma omp critical
                    {
                        steepest_descent = true;
                    }
                }
            }

            // list of spins which were updated
            vector<pair<vertex_t,size_t> > spin_update;
            spin_update.reserve(N);

            // sample a new spin for every vertex
            int NV = num_vertices(g);
            #pragma omp parallel for default(shared) private(i) \
                firstprivate(global_term, cumm_prob) schedule(dynamic)
            for (i = 0; i < NV; ++i)
            {
                vertex_t v = vertex(i, g);
                if (v == graph_traits<Graph>::null_vertex())
                    continue;

                unordered_map<size_t, double> ns; // number of neighbours with
                                                  // spin 's' (weighted)

                // neighborhood spins info
                typename graph_traits<Graph>::out_edge_iterator e,e_end;
                for (tie(e,e_end) = out_edges(v,g); e != e_end; ++e)
                {
                    vertex_t t = target(*e,g);
                    if (t != v)
                        ns[s[t]] += get(weights, weight_key_t(*e));
                }

                size_t k = out_degree_no_loops(v,g);

                map<double,unordered_set<size_t> >& global_term_k =
                    global_term[k];
                map<long double,pair<double,bool> >& cumm_prob_k = cumm_prob[k];

                // update energy levels with local info
                unordered_set<double> modified_energies;
                for (typeof(ns.begin()) iter = ns.begin(); iter != ns.end();
                     ++iter)
                {
                    double old_E = gamma*Nnnks(k, iter->first);
                    double new_E = old_E - ns[iter->first];
                    global_term_k[old_E].erase(iter->first);
                    if (global_term_k[old_E].empty())
                        global_term_k.erase(old_E);
                    global_term_k[new_E].insert(iter->first);
                    modified_energies.insert(old_E);
                    modified_energies.insert(new_E);
                }

                // update probabilities
                size_t prob_mod_count = 0;
                for (typeof(modified_energies.begin()) iter =
                         modified_energies.begin();
                     iter != modified_energies.end(); ++iter)
                {
                    if (energy_to_prob[k].find(*iter) !=
                        energy_to_prob[k].end())
                        if (energy_to_prob[k][*iter] != 0.0)
                            cumm_prob_k[energy_to_prob[k][*iter]].second =
                                false;
                    if (global_term_k.find(*iter) != global_term_k.end())
                    {
                        long double M = log(numeric_limits<long double>::max()/
                                            (Nspins.first*10));
                        long double prob = exp((long double)(-*iter - k)/T + M)*
                            global_term_k[*iter].size();
                        if (cumm_prob_k.empty() ||
                            cumm_prob_k.rbegin()->first + prob !=
                            cumm_prob_k.rbegin()->first)
                        {
                            if (!cumm_prob_k.empty())
                                prob += cumm_prob_k.rbegin()->first;
                            cumm_prob_k.insert(cumm_prob_k.end(),
                                               make_pair(prob,
                                                         make_pair(*iter,
                                                                   true)));
                            prob_mod_count++;
                        }
                    }
                }

                // choose the new energy
                double E = numeric_limits<double>::max();
                if (prob_mod_count == 0 &&
                    !modified_energies.empty() ||
                    steepest_descent)
                {
                    // Temperature too low! The computer precision is not enough
                    // to calculate the probabilities correctly.  Switch to
                    // steepest descent mode....
                    steepest_descent = true;
                    E = global_term_k.begin()->first;
                }
                else
                {
                    // sample energy according to its probability
                    uniform_real<long double> prob_sample
                        (0.0, max(cumm_prob_k.rbegin()->first,
                                  numeric_limits<long double>::epsilon()));
                    bool accept = false;
                    while (!accept)
                    {
                        typeof(cumm_prob_k.begin()) upper;

                        #pragma omp critical
                        {
                            upper = cumm_prob_k.upper_bound(prob_sample(rng));
                        }

                        if (upper == cumm_prob_k.end())
                            upper--;
                        E = upper->second.first;
                        accept = upper->second.second;
                    }
                }

                //new spin (randomly chosen amongst those with equal energy)
                uniform_int<size_t> sample_spin(0,global_term_k[E].size()-1);
                typeof(global_term_k[E].begin()) iter =
                    global_term_k[E].begin();

                size_t spin_n;
                #pragma omp critical
                {
                    spin_n = sample_spin(rng);
                }
                advance(iter, spin_n);
                int a = *iter;

                // cleanup modified probabilities
                for (typeof(modified_energies.begin()) iter =
                         modified_energies.begin();
                     iter != modified_energies.end(); ++iter)
                {
                    if (energy_to_prob[k].find(*iter) !=
                        energy_to_prob[k].end())
                        if (energy_to_prob[k][*iter] != 0.0)
                            cumm_prob_k[energy_to_prob[k][*iter]].second = true;
                    if (prob_mod_count > 0)
                    {
                        cumm_prob_k.erase(cumm_prob_k.rbegin()->first);
                        prob_mod_count--;
                    }
                }

                // cleanup modified energy levels
                for (typeof(ns.begin()) iter = ns.begin(); iter != ns.end();
                     ++iter)
                {
                    double new_E = gamma*Nnnks(k, iter->first);
                    double old_E = new_E - ns[iter->first];
                    global_term_k[old_E].erase(iter->first);
                    if (global_term_k[old_E].empty())
                        global_term_k.erase(old_E);
                    global_term_k[new_E].insert(iter->first);
                }

                //update global info
                if (s[v] != a)
                {
                    #pragma omp critical
                    {
                        spin_update.push_back(make_pair(v, a));
                    }
                }
            }

            // flip spins and update Nnnks
            for (size_t u = 0; u < spin_update.size(); ++u)
            {
                vertex_t v = spin_update[u].first;
                size_t k = out_degree_no_loops(v, g);
                size_t a = spin_update[u].second;

                int i, NK = degs.size();
                #pragma omp parallel for default(shared) private(i) \
                    schedule(dynamic)
                for (i = 0; i < NK; ++i)
                {
                    size_t nk = degs[i];
                    double old_E = gamma*Nnnks(nk,s[v]);
                    double new_E = gamma*Nnnks(nk,a);
350
                    map<double,unordered_set<size_t> >& global_term_k =
351
                        global_term[nk];
352
                    unordered_set<size_t>& global_term_k_old_E =
353
                        global_term_k[old_E];
354
                    unordered_set<size_t>& global_term_k_new_E =
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
                        global_term_k[new_E];
                    global_term_k_old_E.erase(s[v]);
                    if (global_term_k_old_E.empty())
                        global_term_k.erase(old_E);
                    global_term_k_new_E.erase(a);
                    if (global_term_k_new_E.empty())
                        global_term_k.erase(new_E);
                }

                Nnnks.Update(k,s[v],a);
                Ns[s[v]]--;
                if (Ns[s[v]] == 0)
                    Ns.erase(s[v]);
                Ns[a]++;

                #pragma omp parallel for default(shared) private(i) \
                    schedule(dynamic)
                for (i = 0; i < NK; ++i)
                {
                    size_t nk = degs[i];
                    map<double,unordered_set<size_t> >& global_term_k =
                        global_term[nk];
                    double old_E = gamma*Nnnks(nk,s[v]);
                    double new_E = gamma*Nnnks(nk,a);
                    global_term_k[old_E].insert(s[v]);
                    global_term_k[new_E].insert(a);
                }

                // update spin
                s[v] = a;
            }

            if (verbose.first)
            {
                for (size_t j = 0; j < out_str.str().length(); ++j)
                    cout << "\b";
                out_str.str("");
392
                out_str << setw(lexical_cast<string>(n_iter).size())
393
                        << temp_count << " of " << n_iter
394 395 396
                        << " (" << setw(2) << (temp_count+1)*100/n_iter
                        << "%) " << "temperature: " << setw(14)
                        << setprecision(10) << T << " spins: "
397 398
                        << Ns.size() << " energy levels: ";
                size_t n_energy = 0;
399
                for (typeof(global_term.begin()) iter = global_term.begin();
400 401 402
                     iter != global_term.end(); ++iter)
                    n_energy += iter->second.size();
                out_str << setw(lexical_cast<string>
403
                                (Nspins.first*degs.size()).size())
404 405 406 407 408 409 410 411 412 413
                        << n_energy << "  ";
                if (steepest_descent)
                    out_str << " (steepest descent)";
                cout << out_str.str() << flush;
            }
            if (verbose.second != "")
            {
                try
                {
                    size_t n_energy = 0;
414 415
                    for (typeof(global_term.begin()) iter =
                             global_term.begin(); iter != global_term.end();
416 417
                         ++iter)
                        n_energy += iter->second.size();
418 419
                    out_file << temp_count << "\t" << setprecision(10)
                             << T << "\t" << Ns.size() << "\t" << n_energy
420 421 422 423
                             << endl;
                }
                catch (ifstream::failure e)
                {
424
                    throw GraphException("error writing to file " +
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
                                         verbose.second + ": " + e.what());
                }
            }
        }


        // get final energy
        double E = 0.0;
        unordered_map<size_t,vector<vertex_t> > spin_groups;
        for (tie(v,v_end) = vertices(g); v != v_end; ++v)
        {
            typename graph_traits<Graph>::out_edge_iterator e, e_end;
            for (tie(e,e_end) = out_edges(*v,g); e != e_end; ++e)
            {
                vertex_t t = target(*e,g);
                if (s[t] == s[*v])
                    E -= get(weights, weight_key_t(*e));
            }
            E += gamma*Nnnks(out_degree_no_loops(*v,g), s[*v]);
        }

        if (verbose.first)
447
            cout << " total energy: " << scientific << setprecision(20)
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
                 << E << endl;

        // rename spins, starting from zero
        unordered_map<size_t,size_t> spins;
        for (tie(v,v_end) = vertices(g); v != v_end; ++v)
        {
            if (spins.find(s[*v]) == spins.end())
                spins[s[*v]] = spins.size() - 1;
            s[*v] = spins[s[*v]];
        }

    }
};

template <class Graph, class CommunityMap>
class NNKSErdosReyni
{
public:
    NNKSErdosReyni(const Graph &g, CommunityMap s)
    {
        size_t N = 0;
        double _avg_k = 0.0;
        typename graph_traits<Graph>::vertex_iterator v,v_end;
        for (tie(v,v_end) = vertices(g); v != v_end; ++v)
        {
            size_t k = out_degree_no_loops(*v,g);
            _avg_k += k;
            N++;
            _Ns[s[*v]]++;
        }
        _p = _avg_k/(N*N);
    }

    void Update(size_t k, size_t old_s, size_t s)
    {
        _Ns[old_s]--;
        if (_Ns[old_s] == 0)
            _Ns.erase(old_s);
        _Ns[s]++;
    }

    double operator()(size_t k, size_t s) const
    {
        size_t ns = 0;
        typeof(_Ns.begin()) iter = _Ns.find(s);
        if (iter != _Ns.end())
            ns = iter->second;
        return _p*ns;
    }

private:
    double _p;
    unordered_map<size_t,size_t> _Ns;
};

template <class Graph, class CommunityMap>
class NNKSUncorr
{
public:
    NNKSUncorr(const Graph &g, CommunityMap s): _g(g), _K(0)
    {
        typename graph_traits<Graph>::vertex_iterator v,v_end;
        for (tie(v,v_end) = vertices(_g); v != v_end; ++v)
        {
            size_t k = out_degree_no_loops(*v, _g);
            _K += k;
            _Ks[s[*v]] += k;
        }
    }

    void Update(size_t k, size_t old_s, size_t s)
    {
        _Ks[old_s] -= k;
        if (_Ks[old_s] == 0)
            _Ks.erase(old_s);
        _Ks[s] += k;
    }

    double operator()(size_t k, size_t s) const
    {
        size_t ks = 0;
        typeof(_Ks.begin()) iter = _Ks.find(s);
        if (iter != _Ks.end())
            ks = iter->second;
        return k*ks/double(_K);
    }

private:
    const Graph& _g;
    size_t _K;
    unordered_map<size_t,size_t> _Ks;
};

template <class Graph, class CommunityMap>
class NNKSCorr
{
public:
    NNKSCorr(const Graph &g, CommunityMap s): _g(g)
    {
        unordered_set<size_t> spins;

        typename graph_traits<Graph>::vertex_iterator v,v_end;
        for (tie(v,v_end) = vertices(_g); v != v_end; ++v)
        {
            size_t k = out_degree_no_loops(*v, _g);
            _Nk[k]++;
            _Nks[k][s[*v]]++;
            spins.insert(s[*v]);
        }

        size_t E = 0;
        typename graph_traits<Graph>::edge_iterator e,e_end;
        for (tie(e,e_end) = edges(_g); e != e_end; ++e)
        {
            typename graph_traits<Graph>::vertex_descriptor s, t;

            s = source(*e,g);
            t = target(*e,g);
            if (s != t)
            {
                size_t k1 = out_degree_no_loops(s, g);
                size_t k2 = out_degree_no_loops(t, g);
                _Pkk[k1][k2]++;
                _Pkk[k2][k1]++;
                E++;
            }
        }

        for (typeof(_Pkk.begin()) iter1 = _Pkk.begin(); iter1 != _Pkk.end();
             ++iter1)
        {
            double sum = 0;
            for (typeof(iter1->second.begin()) iter2 = iter1->second.begin();
                 iter2 != iter1->second.end(); ++iter2)
                sum += iter2->second;
            for (typeof(iter1->second.begin()) iter2 = iter1->second.begin();
                 iter2 != iter1->second.end(); ++iter2)
                iter2->second /= sum;
        }

        for (typeof(_Nk.begin()) k_iter = _Nk.begin(); k_iter != _Nk.end();
             ++k_iter)
        {
            size_t k1 = k_iter->first;
            _degs.push_back(k1);
            for (typeof(spins.begin()) s_iter = spins.begin();
                 s_iter != spins.end(); ++s_iter)
                for (typeof(_Nk.begin()) k_iter2 = _Nk.begin();
                     k_iter2 != _Nk.end(); ++k_iter2)
                {
                    size_t k2 = k_iter2->first;
                    if (_Nks[k2].find(*s_iter) != _Nks[k2].end())
                        _NNks[k1][*s_iter] +=
                            k1*_Pkk[k1][k2] * _Nks[k2][*s_iter]/double(_Nk[k2]);
                }
        }
    }

    void Update(size_t k, size_t old_s, size_t s)
    {
        int i, NK = _degs.size();
        #pragma omp parallel for default(shared) private(i) schedule(dynamic)
        for (i = 0; i < NK; ++i)
        {
            size_t k1 = _degs[i], k2 = k;
            if (_Pkk.find(k1) == _Pkk.end())
                continue;
            if (_Pkk.find(k1)->second.find(k2) == _Pkk.find(k1)->second.end())
                continue;
            unordered_map<size_t,double>& NNks_k1 = _NNks[k1];
            double Pk1k2 = _Pkk[k1][k2];
            unordered_map<size_t,size_t>& Nksk2 = _Nks[k2];
            double Nk2 = _Nk[k2];
            NNks_k1[old_s] -=  k1*Pk1k2 * Nksk2[old_s]/Nk2;
            if (NNks_k1[old_s] == 0.0)
                NNks_k1.erase(old_s);
            if (Nksk2.find(s) != Nksk2.end())
                NNks_k1[s] -=  k1*Pk1k2 * Nksk2[s]/Nk2;
            if (NNks_k1[s] == 0.0)
                NNks_k1.erase(s);
        }

        _Nks[k][old_s]--;
        if (_Nks[k][old_s] == 0)
            _Nks[k].erase(old_s);
        _Nks[k][s]++;

        #pragma omp parallel for default(shared) private(i) schedule(dynamic)
        for (i = 0; i < NK; ++i)
        {
            size_t k1 = _degs[i], k2 = k;
            if (_Pkk.find(k1) == _Pkk.end())
                continue;
            if (_Pkk.find(k1)->second.find(k2) == _Pkk.find(k1)->second.end())
                continue;
            unordered_map<size_t,double>& NNks_k1 = _NNks[k1];
            double Pk1k2 = _Pkk[k1][k2];
            unordered_map<size_t,size_t>& Nksk2 = _Nks[k2];
            double Nk2 = _Nk[k2];
            NNks_k1[old_s] +=  k1*Pk1k2 * Nksk2[old_s]/Nk2;
            if (NNks_k1[old_s] == 0.0)
                NNks_k1.erase(old_s);
            NNks_k1[s] +=  k1*Pk1k2 * Nksk2[s]/Nk2;
        }

    }

    double operator()(size_t k, size_t s) const
    {
        const typeof(_NNks[k])& nnks = _NNks.find(k)->second;
        const typeof(nnks.begin()) iter = nnks.find(s);
        if (iter != nnks.end())
            return iter->second;
        return 0.0;
    }

private:
    const Graph& _g;
    vector<size_t> _degs;
    unordered_map<size_t,size_t> _Nk;
    unordered_map<size_t,unordered_map<size_t,double> > _Pkk;
    unordered_map<size_t,unordered_map<size_t,size_t> > _Nks;
    unordered_map<size_t,unordered_map<size_t,double> > _NNks;
};

673 674 675 676 677 678
enum comm_corr_t
{
    ERDOS_REYNI,
    UNCORRELATED,
    CORRELATED
};
679 680 681

struct get_communities_selector
{
682 683
    get_communities_selector(comm_corr_t corr):_corr(corr) {}
    comm_corr_t _corr;
684 685 686 687 688 689 690 691 692 693 694

    template <class Graph, class WeightMap, class CommunityMap>
    void operator()(const Graph* gp, WeightMap weights, CommunityMap s, double gamma,
                    size_t n_iter, pair<double,double> Tinterval,
                    pair<size_t,bool> Nspins, size_t seed,
                    pair<bool,string> verbose) const
    {
        const Graph& g = *gp;

        switch (_corr)
        {
695
        case ERDOS_REYNI:
696 697 698
            get_communities<NNKSErdosReyni>()(g, weights, s, gamma, n_iter,
                                              Tinterval, Nspins, seed, verbose);
            break;
699
        case UNCORRELATED:
700 701 702
            get_communities<NNKSUncorr>()(g, weights, s, gamma, n_iter,
                                          Tinterval, Nspins, seed, verbose);
            break;
703
        case CORRELATED:
704 705 706 707 708 709 710 711 712 713 714
            get_communities<NNKSCorr>()(g, weights, s, gamma, n_iter,
                                        Tinterval, Nspins, seed, verbose);
            break;
        }
    }
};

// get Newman's modularity of a given community partition
struct get_modularity
{
    template <class Graph, class WeightMap, class CommunityMap>
715
    void operator()(const Graph* gp, WeightMap weights, CommunityMap s,
716 717 718 719 720
                    double& modularity) const
    {
        typedef typename property_traits<WeightMap>::key_type weight_key_t;
        const Graph& g = *gp;

721
        modularity = 0.0;
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
        size_t E = 0;
        double W = 0;

        typename graph_traits<Graph>::edge_iterator e, e_end;
        for (tie(e,e_end) = edges(g); e != e_end; ++e)
            if (target(*e,g) != source(*e,g))
            {
                W += get(weights, *e);
                E++;
                if (get(s, target(*e,g)) == get(s, source(*e,g)))
                    modularity += 2*get(weights, weight_key_t(*e));
            }

        unordered_map<size_t, size_t> Ks;

        typename graph_traits<Graph>::vertex_iterator v, v_end;
        for (tie(v,v_end) = vertices(g); v != v_end; ++v)
            Ks[get(s, *v)] += out_degree_no_loops(*v, g);
740

741 742 743 744 745 746 747 748 749 750
        for (typeof(Ks.begin()) iter = Ks.begin(); iter != Ks.end(); ++iter)
            modularity -= (iter->second*iter->second)/double(2*E);

        modularity /= 2*W;
    }
};

} // graph_tool namespace

#endif //GRAPH_COMMUNITY_HH