summaryrefslogtreecommitdiff
path: root/geom_bottleneck/include/bound_match.hpp
blob: 221bd0f21abef03543292ffc6932b28e82f75136 (plain)
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
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
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
350
351
352
353
354
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
/*

Copyright (c) 2015, M. Kerber, D. Morozov, A. Nigmetov
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


You are under no obligation whatsoever to provide any bug fixes, patches, or
upgrades to the features, functionality or performance of the source code
(Enhancements) to anyone; however, if you choose to make your Enhancements
available either publicly, or directly to copyright holder,
without imposing a separate written license agreement for such Enhancements,
then you hereby grant the following license: a  non-exclusive, royalty-free
perpetual license to install, use, modify, prepare derivative works, incorporate
into other computer software, distribute, and sublicense such enhancements or
derivative works thereof, in binary and source code form.

*/

#ifndef HERA_BOUND_MATCH_HPP
#define HERA_BOUND_MATCH_HPP


#ifdef FOR_R_TDA
#undef DEBUG_BOUND_MATCH
#undef DEBUG_MATCHING
#undef VERBOSE_BOTTLENECK
#endif

#include <assert.h>
#include "def_debug_bt.h"
#include "bound_match.h"

#ifdef VERBOSE_BOTTLENECK
#include <chrono>
#endif

#ifndef FOR_R_TDA
#include <iostream>
#endif

namespace hera{
namespace bt {

#ifndef FOR_R_TDA
template<class Real>
std::ostream& operator<<(std::ostream& output, const Matching<Real>& m)
{
    output << "Matching: " << m.AToB.size() << " pairs (";
    if (!m.isPerfect()) {
        output << "not";
    }
    output << " perfect)" << std::endl;
    for(auto atob : m.AToB) {
        output << atob.first << " <-> " << atob.second << "  distance: " << distLInf(atob.first, atob.second) << std::endl;
    }
    return output;
}
#endif

template<class R>
void Matching<R>::sanityCheck() const
{
#ifdef DEBUG_MATCHING
    assert( AToB.size() == BToA.size() );
    for(auto aToBPair : AToB) {
        auto bToAPair = BToA.find(aToBPair.second);
        assert(bToAPair != BToA.end());
        assert( aToBPair.first == bToAPair->second);
    }
#endif
}

template<class R>
bool Matching<R>::isPerfect() const
{
    return AToB.size() == A.size();
}

template<class R>
void Matching<R>::matchVertices(const DgmPoint& pA, const DgmPoint& pB)
{
    assert(A.hasElement(pA));
    assert(B.hasElement(pB));
    AToB.erase(pA);
    AToB.insert( {{ pA, pB }} );
    BToA.erase(pB);
    BToA.insert( {{ pB, pA }} );
}

template<class R>
bool Matching<R>::getMatchedVertex(const DgmPoint& p, DgmPoint& result) const
{
    sanityCheck();
    auto inA = AToB.find(p);
    if (inA != AToB.end()) {
        result = inA->second;
        return true;
    } else {
        auto inB = BToA.find(p);
        if (inB != BToA.end()) {
            result = inB->second;
            return true;
        }
    }
    return false;
}


template<class R>
void Matching<R>::checkAugPath(const Path& augPath) const
{
    assert(augPath.size() % 2 == 0);
    for(size_t idx = 0; idx < augPath.size(); ++idx) {
        bool mustBeExposed  { idx == 0 or idx == augPath.size() - 1 };
        if (isExposed(augPath[idx]) != mustBeExposed) {
#ifndef FOR_R_TDA
            std::cerr << "mustBeExposed = " << mustBeExposed << ", idx = " << idx << ", point " << augPath[idx] << std::endl;
#endif
        }
        assert( isExposed(augPath[idx]) == mustBeExposed );
        DgmPoint matchedVertex {0.0, 0.0, DgmPoint::DIAG, 1};
        if ( idx % 2 == 0 ) {
            assert( A.hasElement(augPath[idx]));
            if (not mustBeExposed) {
                getMatchedVertex(augPath[idx], matchedVertex);
                assert(matchedVertex == augPath[idx - 1]);
            }
        } else {
            assert( B.hasElement(augPath[idx]));
            if (not mustBeExposed) {
                getMatchedVertex(augPath[idx], matchedVertex);
                assert(matchedVertex == augPath[idx + 1]);
            }
        }
    }
}

// use augmenting path to increase
// the size of the matching
template<class R>
void Matching<R>::increase(const Path& augPath)
{
    sanityCheck();
    // check that augPath is an augmenting path
    checkAugPath(augPath);
    for(size_t idx = 0; idx < augPath.size() - 1; idx += 2) {
        matchVertices( augPath[idx], augPath[idx + 1]);
    }
    sanityCheck();
}

template<class R>
DiagramPointSet<R> Matching<R>::getExposedVertices(bool forA) const
{
    sanityCheck();
    DgmPointSet result;
    const DgmPointSet* setToSearch { forA ? &A : &B };
    const std::unordered_map<DgmPoint, DgmPoint, DgmPointHash>* mapToSearch { forA ? &AToB : &BToA };
    for(auto it = setToSearch->cbegin(); it != setToSearch->cend(); ++it) {
        if (mapToSearch->find((*it)) == mapToSearch->cend()) {
            result.insert((*it));
        }
    }
    return result;
}

template<class R>
void Matching<R>::getAllAdjacentVertices(const DgmPointSet& setIn,
                                      DgmPointSet& setOut,
                                      bool forA) const
{
    sanityCheck();
    //bool isDebug {false};
    setOut.clear();
    const std::unordered_map<DgmPoint, DgmPoint, DgmPointHash>* m;
    m = ( forA ) ? &BToA : &AToB;
    for(auto pit = setIn.cbegin(); pit != setIn.cend(); ++pit) {
        auto findRes = m->find(*pit);
        if (findRes != m->cend()) {
            setOut.insert((*findRes).second);
        }
    }
    sanityCheck();
}

template<class R>
bool Matching<R>::isExposed(const DgmPoint& p) const
{
    return ( AToB.find(p) == AToB.end() ) && ( BToA.find(p) == BToA.end() );
}

// remove all edges whose length is > newThreshold
template<class R>
void Matching<R>::trimMatching(const R newThreshold)
{
    //bool isDebug { false };
    sanityCheck();
    for(auto aToBIter = AToB.begin(); aToBIter != AToB.end(); ) {
        if ( distLInf(aToBIter->first, aToBIter->second) > newThreshold ) {
            // remove edge from AToB and BToA
            BToA.erase(aToBIter->second);
            aToBIter = AToB.erase(aToBIter);
        } else {
            aToBIter++;
        }
    }
    sanityCheck();
}

// ------- BoundMatchOracle --------------

template<class R, class NO>
BoundMatchOracle<R, NO>::BoundMatchOracle(DgmPointSet psA, DgmPointSet psB,
        Real dEps, bool useRS) :
    A(psA), B(psB), M(A, B), distEpsilon(dEps), useRangeSearch(useRS), prevQueryValue(0.0)
{
    neighbOracle = std::unique_ptr<NeighbOracle>(new NeighbOracle(psB, 0, distEpsilon));
}

template<class R, class NO>
bool BoundMatchOracle<R, NO>::isMatchLess(Real r)
{
#ifdef VERBOSE_BOTTLENECK
    std::chrono::high_resolution_clock hrClock;
    std::chrono::time_point<std::chrono::high_resolution_clock> startMoment;
    startMoment = hrClock.now();
#endif
    bool result = buildMatchingForThreshold(r);
#ifdef VERBOSE_BOTTLENECK
    auto endMoment = hrClock.now();
    std::chrono::duration<double, std::milli> iterTime = endMoment - startMoment;
    std::cout << "isMatchLess for r = " << r << " finished in " << std::chrono::duration<double, std::milli>(iterTime).count() << " ms." << std::endl;
#endif
    return result;

}


template<class R, class NO>
void BoundMatchOracle<R, NO>::removeFromLayer(const DgmPoint& p, const int layerIdx) {
    //bool isDebug {false};
    layerGraph[layerIdx].erase(p);
    if (layerOracles[layerIdx]) {
        layerOracles[layerIdx]->deletePoint(p);
    }
}

// return true, if there exists an augmenting path from startVertex
// in this case the path is returned in result.
// startVertex must be an exposed vertex from L_1 (layer[0])
template<class R, class NO>
bool BoundMatchOracle<R, NO>::buildAugmentingPath(const DgmPoint startVertex, Path& result)
{
    //bool isDebug {false};
    DgmPoint prevVertexA = startVertex;
    result.clear();
    result.push_back(startVertex);
    size_t evenLayerIdx {1};
    while ( evenLayerIdx < layerGraph.size() ) {
    //for(size_t evenLayerIdx = 1; evenLayerIdx < layerGraph.size(); evenLayerIdx += 2) {
        DgmPoint nextVertexB{0.0, 0.0, DgmPoint::DIAG, 1}; // next vertex from even layer
        bool neighbFound = layerOracles[evenLayerIdx]->getNeighbour(prevVertexA, nextVertexB);
        if (neighbFound) {
           result.push_back(nextVertexB);
           if ( layerGraph.size() == evenLayerIdx + 1) {
                break;
            } else {
                 // nextVertexB must be matched with some vertex from the next odd
                 // layer
                DgmPoint nextVertexA {0.0, 0.0, DgmPoint::DIAG, 1};
                if (!M.getMatchedVertex(nextVertexB, nextVertexA)) {
#ifndef FOR_R_TDA
                    std::cerr << "Vertices in even layers must be matched! Unmatched: ";
                    std::cerr << nextVertexB << std::endl;
                    std::cerr << evenLayerIdx << "; " << layerGraph.size() << std::endl;
#endif
                    throw std::runtime_error("Unmatched vertex in even layer");
                } else {
                    assert( ! (nextVertexA.getRealX() == 0 and nextVertexA.getRealY() == 0) );
                    result.push_back(nextVertexA);
                    prevVertexA = nextVertexA;
                    evenLayerIdx += 2;
                    continue;
                }
            }
        } else {
            // prevVertexA has no neighbours in the next layer,
            // backtrack
            if (evenLayerIdx == 1) {
                // startVertex is not connected to any vertices
                // in the next layer, augm. path doesn't exist
                removeFromLayer(startVertex, 0);
                return false;
            } else {
                assert(evenLayerIdx >= 3);
                assert(result.size() % 2 == 1);
                result.pop_back();
                DgmPoint prevVertexB = result.back();
                result.pop_back();
                removeFromLayer(prevVertexA, evenLayerIdx-1);
                removeFromLayer(prevVertexB, evenLayerIdx-2);
                // we should proceed from the previous odd layer
                assert(result.size() >= 1);
                prevVertexA = result.back();
                evenLayerIdx -= 2;
                continue;
            }
        }
    } // finished iterating over all layers
    // remove all vertices in the augmenting paths
    // the corresponding layers
    for(size_t layerIdx = 0; layerIdx < result.size(); ++layerIdx) {
        removeFromLayer(result[layerIdx], layerIdx);
    }
    return true;
}




template<class R, class NO>
bool BoundMatchOracle<R, NO>::buildMatchingForThreshold(const Real r)
{
    //bool isDebug {false};
    if (prevQueryValue > r) {
        M.trimMatching(r);
    }
    prevQueryValue = r;
    while(true) {
        buildLayerGraph(r);
        if (augPathExist) {
            std::vector<Path> augmentingPaths;
            DgmPointSet copyLG0;
            for(DgmPoint p : layerGraph[0]) {
                copyLG0.insert(p);
            }
            for(DgmPoint exposedVertex : copyLG0) {
                Path augPath;
                if (buildAugmentingPath(exposedVertex, augPath)) {
                    augmentingPaths.push_back(augPath);
                }
            }
            if (augmentingPaths.empty()) {
#ifndef FOR_R_TDA
                std::cerr << "augmenting paths must exist, but were not found!" << std::endl;
#endif
                throw std::runtime_error("bad epsilon?");
            }
            // swap all augmenting paths with matching to increase it
            for(auto& augPath : augmentingPaths ) {
                M.increase(augPath);
            }
        } else {
            return M.isPerfect();
        }
    }
}

template<class R, class NO>
void BoundMatchOracle<R, NO>::printLayerGraph(void)
{
#ifdef DEBUG_BOUND_MATCH
    for(auto& layer : layerGraph) {
        std::cout << "{ ";
        for(auto& p : layer) {
            std::cout << p << "; ";
        }
        std::cout << "\b\b }" << std::endl;
    }
#endif
}

template<class R, class NO>
void BoundMatchOracle<R, NO>::buildLayerGraph(Real r)
{
#ifdef VERBOSE_BOTTLENECK
    std::cout << "Entered buildLayerGraph, r = " << r << std::endl;
#endif
    layerGraph.clear();
    DgmPointSet L1 = M.getExposedVertices();
    layerGraph.push_back(L1);
    neighbOracle->rebuild(B, r);
    size_t k = 0;
    DgmPointSet layerNextEven;
    DgmPointSet layerNextOdd;
    bool exposedVerticesFound {false};
    while(true) {
        layerNextEven.clear();
        for( auto p : layerGraph[k]) {
            bool neighbFound;
            DgmPoint neighbour {0.0, 0.0, DgmPoint::DIAG, 1};
            if (useRangeSearch) {
                std::vector<DgmPoint> neighbVec;
                neighbOracle->getAllNeighbours(p, neighbVec);
                neighbFound = !neighbVec.empty();
                for(auto& neighbPt : neighbVec) {
                    layerNextEven.insert(neighbPt);
                    if (!exposedVerticesFound and M.isExposed(neighbPt))
                        exposedVerticesFound = true;
                }
            } else {
                while(true) {
                    neighbFound = neighbOracle->getNeighbour(p, neighbour);
                    if (neighbFound) {
                        layerNextEven.insert(neighbour);
                        neighbOracle->deletePoint(neighbour);
                        if ((!exposedVerticesFound) && M.isExposed(neighbour)) {
                            exposedVerticesFound = true;
                        }
                    } else {
                        break;
                    }
                }
            } // without range search
        } // all vertices from previous odd layer processed
        if (layerNextEven.empty()) {
            augPathExist = false;
            break;
        }
        if (exposedVerticesFound) {
            for(auto it = layerNextEven.cbegin(); it != layerNextEven.cend(); ) {
                if ( ! M.isExposed(*it) ) {
                    layerNextEven.erase(it++);
                } else {
                    ++it;
                }

            }
            layerGraph.push_back(layerNextEven);
            augPathExist = true;
            break;
        }
        layerGraph.push_back(layerNextEven);
        M.getAllAdjacentVertices(layerNextEven, layerNextOdd);
        layerGraph.push_back(layerNextOdd);
        k += 2;
    }
    buildLayerOracles(r);
    printLayerGraph();
 }

// create geometric oracles for each even layer
// odd layers have NULL in layerOracles
template<class R, class NO>
void BoundMatchOracle<R, NO>::buildLayerOracles(Real r)
{
    //bool isDebug {false};
    // free previously constructed oracles
    layerOracles.clear();
    for(size_t layerIdx = 0; layerIdx < layerGraph.size(); ++layerIdx) {
        if (layerIdx % 2 == 1) {
            // even layer, build actual oracle
            layerOracles.emplace_back(new NeighbOracle(layerGraph[layerIdx], r, distEpsilon));
        } else {
            // odd layer
            layerOracles.emplace_back(nullptr);
        }
    }
}

} // end namespace bt
} // end namespace hera
#endif // HERA_BOUND_MATCH_HPP