graph_blockmodel_sample_edge.hh 10.8 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
// graph-tool -- a general graph modification and manipulation thingy
//
// Copyright (C) 2006-2018 Tiago de Paula Peixoto <tiago@skewed.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_SBM_SAMPLE_EDGE_HH
#define GRAPH_SBM_SAMPLE_EDGE_HH

#include <tuple>
#include <iostream>

#include "graph.hh"
#include "graph_filtering.hh"
#include "graph_util.hh"
#include "../../generation/sampler.hh"
#include "../../generation/urn_sampler.hh"

#include "random.hh"

namespace graph_tool
{
using namespace std;
using namespace boost;

37
template <class State>
38 39 40
class SBMEdgeSampler
{
public:
41
    SBMEdgeSampler(State& state, bool edges_only=false)
42 43
        : _state(state),
          _v_in_sampler(graph_tool::is_directed(state._g) ?
44 45
                        __v_in_sampler : _v_out_sampler),
          _edges_only(edges_only)
46
    {
47 48 49 50 51 52 53 54 55 56 57 58 59
        _N = num_vertices(state._g);

        for (auto e : edges_range(state._g))
        {
            size_t u = source(e, state._g);
            size_t v = target(e, state._g);
            _edges.push_back(get_edge(u, v));
            _edge_pos[_edges.back()] = _edges.size() - 1;
        }

        if (_edges_only)
            return;

60 61
        for (auto me : edges_range(state._bg))
        {
62 63
            auto r = source(me, state._bg);
            auto s = target(me, state._bg);
64 65 66
            size_t mrs = state._mrs[me];
            if (mrs == 0)
                continue;
67 68
            _rs_pos[me] = _rs_sampler.insert({r, s}, mrs);
            _E += mrs;
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
        for (auto v : vertices_range(state._g))
        {
            size_t r = state._b[v];
            if (r >= _v_out_sampler.size())
            {
                if (graph_tool::is_directed(state._g))
                    _v_in_sampler.resize(r+1);
                _v_out_sampler.resize(r+1);
            }

            size_t kin = 0, kout = 0;
            if (state._deg_corr)
            {
                degs_op(v, state._vweight, state._eweight, state._degs,
                        state._g,
                        [&] (size_t din, size_t dout, auto c)
                        {
                            kin += din * c;
                            kout += dout * c;
                        });
            }

            if (graph_tool::is_directed(state._g))
                _v_in_pos[v] = _v_in_sampler[r].insert(v, kin + 1);
            _v_out_pos[v] = _v_out_sampler[r].insert(v, kout + 1);
        }
97

98 99 100
        for (auto r : vertices_range(state._bg))
            if (state._wr[r] > 0)
                _groups.push_back(r);
101

102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
        auto B = _groups.size();
        _NB = B * B;
    }

    std::tuple<size_t, size_t> get_edge(size_t u, size_t v)
    {
        if (!graph_tool::is_directed(_state._g) && u > v)
            return {v, u};
        return {u, v};
    }


    template <bool add>
    void update_edge(size_t u, size_t v, size_t m)
    {
117 118 119
        if (_edges_only)
            return;

120 121 122
        if (add)
        {
            if (m == 0)
123
            {
124 125
                _edges.push_back(get_edge(u, v));
                _edge_pos[_edges.back()] = _edges.size() - 1;
126
            }
127 128 129 130
        }
        else
        {
            if (m == 1)
131
            {
132 133 134 135 136 137 138 139 140
                auto iter = _edge_pos.find(get_edge(u, v));
                size_t pos = iter->second;
                _edge_pos.erase(iter);
                if (pos < _edges.size() - 1)
                {
                    std::swap(_edges[pos], _edges.back());
                    _edge_pos[_edges[pos]] = pos;
                }
                _edges.pop_back();
141 142 143
            }
        }

144 145 146 147 148 149 150
        constexpr int delta = (add) ? 0 : -1;
        _E += (add) ? 1 : -1;
        size_t r = _state._b[u];
        size_t s = _state._b[v];

        auto me = _state._emat.get_me(r, s);
        if (me != _state._emat.get_null_edge())
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
            auto ers = _state._mrs[me] + delta;
            if (!add || ers > 1)
                _rs_sampler.remove(_rs_pos[me]);
            if (ers > 0)
                _rs_pos[me] = _rs_sampler.insert({r,s}, ers);
            else
                _rs_pos[me] = std::numeric_limits<size_t>::max();
        }

        if (_state._deg_corr)
        {
            size_t ku = 0, kv = 0;
            degs_op(u, _state._vweight, _state._eweight, _state._degs, _state._g,
                    [&] (size_t, size_t dout, auto c)
                    {
                        ku += dout * c;
                    });
            degs_op(v, _state._vweight, _state._eweight, _state._degs, _state._g,
                    [&] (size_t din, size_t dout, auto c)
                    {
                        if (graph_tool::is_directed(_state._g))
                            kv += din * c;
                        else
                            kv += dout * c;
                    });

            if (u != v || graph_tool::is_directed(_state._g))
            {
                ku += delta;
                kv += delta;
            }
            else
            {
                ku += 2 * delta;
                kv += 2 * delta;
            }

            _v_out_sampler[r].remove(_v_out_pos[u]);
            _v_out_pos[u] = _v_out_sampler[r].insert(u, ku + 1);

            if (u != v || graph_tool::is_directed(_state._g))
            {
                if (graph_tool::is_directed(_state._g))
                {
                    _v_in_sampler[s].remove(_v_in_pos[v]);
                    _v_in_pos[v] = _v_in_sampler[s].insert(v, kv + 1);
                }
                else
                {
                    _v_out_sampler[s].remove(_v_out_pos[v]);
                    _v_out_pos[v] = _v_out_sampler[s].insert(v, kv + 1);
                }
            }
205 206 207 208 209 210
        }
    }

    template <class RNG>
    std::tuple<size_t, size_t> sample(RNG& rng)
    {
211 212 213
        // std::uniform_int_distribution<size_t> sample(0, _N-1);
        // return {sample(rng), sample(rng)};

214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
        if (_edges_only)
        {
            std::bernoulli_distribution coin(_edges.size() /
                                             double(_edges.size() + _N));
            if (coin(rng))
            {
                return uniform_sample(_edges, rng);
            }
            else
            {
                std::uniform_int_distribution<size_t> vsample(0, _N-1);
                auto v = vsample(rng);
                return {v, v};
            }
        }

230 231 232 233 234 235
        if (!_edges.empty())
        {
            std::bernoulli_distribution coin(.5);
            if (coin(rng))
                return uniform_sample(_edges, rng);
        }
236

237 238 239 240
        std::tuple<size_t, size_t> rs;
        auto E = graph_tool::is_directed(_state._g) ? _E : 2 * _E;
        std::bernoulli_distribution random(_NB/double(E + _NB));
        if (random(rng))
241 242 243 244
        {
            get<0>(rs) = uniform_sample(_groups, rng);
            get<1>(rs) = uniform_sample(_groups, rng);
        }
245 246 247 248
        else
        {
            rs = _rs_sampler.sample(rng);
        }
249 250 251 252 253 254 255

        auto& r_sampler = _v_out_sampler[get<0>(rs)];
        auto& s_sampler = _v_in_sampler[get<1>(rs)];
        return std::make_tuple(r_sampler.sample(rng),
                               s_sampler.sample(rng));
    }

256 257
    double log_prob(size_t u, size_t v, size_t m, int delta)
    {
258 259
        if (_edges_only)
            return 0;
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

        auto& g = _state._g;
        size_t r = _state._b[u];
        size_t s = _state._b[v];

        size_t ku = 0, kv = 0;
        if (_state._deg_corr)
        {
            degs_op(u, _state._vweight, _state._eweight, _state._degs, g,
                    [&] (size_t, size_t dout, auto c)
                    {
                        ku += dout * c;
                    });
            degs_op(v, _state._vweight, _state._eweight, _state._degs, g,
                    [&] (size_t din, size_t dout, auto c)
                    {
                        if (graph_tool::is_directed(g))
                            kv += din * c;
                        else
                            kv += dout * c;
                    });
        }

        auto&& me = _state._emat.get_me(r, s);
        size_t ers = (me == _state._emat.get_null_edge()) ? 0 : _state._mrs[me];
        ers += delta;

        if (!graph_tool::is_directed(g) && r == s)
            ers *= 2;

        size_t nr = _state._wr[r];
        size_t ns = _state._wr[s];
        size_t er = _state._mrp[r];
        size_t es = graph_tool::is_directed(g) ? _state._mrm[s] : _state._mrp[s];

        if (_state._deg_corr)
        {
            if (r != s || graph_tool::is_directed(g))
            {
                er += delta;
                es += delta;
            }
            else
            {
                er += 2 * delta;
                es += 2 * delta;
            }

            if (u != v || graph_tool::is_directed(g))
            {
                ku += delta;
                kv += delta;
            }
            else
            {
                ku += 2 * delta;
                kv += 2 * delta;
            }
        }
        else
        {
            er = es = 0;
        }

        auto E = graph_tool::is_directed(g) ? (_E + delta) : 2 * (_E + delta);

        double lp = (log(ers + 1) - log(E + _NB) +
                     log(ku + 1) - log(er + nr) +
                     log(kv + 1) - log(es + ns));

        if (!graph_tool::is_directed(g) && u != v)
            lp += log(2);

        if (m > 0)
        {
            double rp;
            if (m == 1 && delta == 1)
                rp = -log(_edges.size() + delta);
            else
                rp = -log(_edges.size());
            double x = std::max(rp, lp);
            double y = std::min(rp, lp);
            return x + log1p(exp(y - x)) - log(2);
        }
        else
        {
            return lp;
        }
    }

350
private:
351 352 353
    State& _state;

    typedef DynamicSampler<std::tuple<size_t, size_t>> rs_sampler_t;
354
    rs_sampler_t _rs_sampler;
355
    eprop_map_t<size_t>::type _rs_pos;
356

357
    typedef DynamicSampler<size_t> vsampler_t;
358 359 360
    vector<vsampler_t> __v_in_sampler, _v_out_sampler;
    vector<vsampler_t>& _v_in_sampler;

361 362 363
    vprop_map_t<size_t>::type _v_in_pos;
    vprop_map_t<size_t>::type _v_out_pos;

364
    std::vector<size_t> _groups;
365

366 367 368 369 370
    std::vector<std::tuple<size_t, size_t>> _edges;
    gt_hash_map<std::tuple<size_t, size_t>, size_t> _edge_pos;

    size_t _NB = 0;
    size_t _E = 0;
371
    size_t _N = 0;
372 373

    bool _edges_only;
374 375 376 377 378 379
};


} // graph_tool namespace

#endif // GRAPH_SBM_SAMPLE_EDGE_HH