From 9c169ddbec51dec00f3ef7aa30dff3a65a9993bc Mon Sep 17 00:00:00 2001 From: Fedor Chelnokov Date: Fri, 4 Dec 2026 18:25:37 +0300 Subject: [PATCH 1/6] GraphCut: push-relabel when augmenting paths get long Augmenting paths between two trees run first. If they take more than 16 orphans and path steps per face, or more than 500 per augmentation, highest-label push-relabel with global relabeling and gap heuristic continues from the same flow, releasing sink capacity in 16 stages. 4.5-15x faster for seeds far apart, the same minimal cut. Co-Authored-By: Claude Fable 5.2 --- source/MRMesh/MRFillContourByGraphCut.cpp | 373 +++++++++++++++++- .../MRTest/MRFillContourByGraphCutTests.cpp | 58 ++- 2 files changed, 419 insertions(+), 12 deletions(-) diff --git a/source/MRMesh/MRFillContourByGraphCut.cpp b/source/MRMesh/MRFillContourByGraphCut.cpp index 84fd6535d4c8..11d3a4a5335c 100644 --- a/source/MRMesh/MRFillContourByGraphCut.cpp +++ b/source/MRMesh/MRFillContourByGraphCut.cpp @@ -33,7 +33,7 @@ struct Slot { FaceId nei; // the face to the right of the primal edge, invalid for boundary edges SlotId back; // the slot of the opposite dual edge from nei to this face - float cap = 0; // residual capacity of this dual edge + float cap = 0; // residual capacity of this dual edge (of the opposite dual edge during push-relabel) }; static_assert( sizeof( Slot ) == 12 ); @@ -47,6 +47,19 @@ struct CachePath }; static_assert( sizeof( CachePath ) == 8 ); +// push-relabel data of a face +struct Node +{ + int label = 0; // lower bound of the distance to a source face in the residual graph + float excess = 0; // the flow that entered the face and has not left it yet + FaceId next, prev; // the neighbors in the list of faces with the same label +}; +static_assert( sizeof( Node ) == 16 ); + +/// finds the minimal cut between source (Left) and sink (Right) faces: +/// starts by augmenting paths between two search trees, which is the fastest while the paths are short, +/// and if that takes too much work, continues from the same flow by push-relabel method +/// with the highest label selection, global relabeling and gap heuristics class GraphCut { public: @@ -65,6 +78,22 @@ class GraphCut Vector cachePath_; std::deque> active_[2]; Vector orphans_; + Vector seeds_[2]; + Vector contourSlots_; + size_t work_ = 0; // the number of orphans and path steps processed + size_t augmentations_ = 0; + + // push-relabel pushes the flow backward from sink faces to source faces, so in the end the faces that can reach a source face + // are exactly the faces reachable from source faces in the residual graph, same as Left tree of augmenting paths + Vector nodes_; + Vector cur_; // local index of the first slot of the face not yet found inadmissible + Vector activeHead_, inactiveHead_; // per label: the lists of faces with and without excess + Vector queue_; + Vector sinkSlots_; // not saturated dual edges from sink faces + int n_ = 0; // the label of faces that cannot reach source faces + int aMax_ = 0; // no active faces have larger label + int dMax_ = 0; // no listed faces have larger label + size_t relabels_ = 0; // after the last global relabeling // returns true if face f is on given side bool isSide_( FaceId f, int side ) const { return ( state_[f] & 3 ) == side + 1; } @@ -90,6 +119,21 @@ class GraphCut bool isGrandparent_( FaceId child, FaceId grand ) const; // checks that there is not saturated path from f to a root bool checkNotSaturatedPath_( FaceId f, int side ) const; + + // completes the flow by push-relabel method, returns the faces on the left side of the minimal cut + FaceBitSet pushRelabel_( const ProgressCallback& progress, size_t numCycles ); + void addActive_( FaceId f, int label ); + void addInactive_( FaceId f, int label ); + void removeInactive_( FaceId f, int label ); + // pushes the excess of f to its neighbors with relabeling of f as necessary + void discharge_( FaceId f ); + // layer g became empty, so all faces with larger labels cannot reach source faces + void gap_( int g ); + // sets exact distances to source faces in the residual graph as labels + void globalRelabel_(); + // pushes 1/parts of remaining capacities of the edges from sink faces; + // all capacities at once would make much more excess than the maximal flow, and it takes long to find that it cannot reach sources + void release_( int parts ); }; GraphCut::GraphCut( const MeshTopology & topology, const EdgeMetric & metric ) : topology_( topology ) @@ -168,7 +212,11 @@ void GraphCut::addContour( const EdgePath & contour ) for ( auto e : contour ) if ( topology_.left( e ) ) - slots_[slotOf_( e )].cap = ContourEdge; + { + const auto s = slotOf_( e ); + slots_[s].cap = ContourEdge; + contourSlots_.push_back( s ); + } for ( auto e : contour ) { @@ -176,26 +224,28 @@ void GraphCut::addContour( const EdgePath & contour ) auto r = topology_.right( e ); if ( r ) { - auto & backCap = slots_[slotOf_( e.sym() )].cap; + const auto bs = slotOf_( e.sym() ); + auto & backCap = slots_[bs].cap; if ( backCap == ContourEdge ) continue; backCap = ContourEdge; + contourSlots_.push_back( bs ); } if ( l && !( state_[l] & 1 ) ) { state_[l] |= 1; - active_[Left].push_back( l ); + seeds_[Left].push_back( l ); } if ( r && !( state_[r] & 2 ) ) { state_[r] |= 2; - active_[Right].push_back( r ); + seeds_[Right].push_back( r ); } } // faces on both sides belong to none for ( int side : { Left, Right } ) - for ( auto f : active_[side] ) + for ( auto f : seeds_[side] ) if ( state_[f] == 3 ) state_[f] = 0; } @@ -215,7 +265,7 @@ void GraphCut::addFaces( FaceBitSet source, FaceBitSet sink ) if ( isFree_( f ) ) { state_[f] = Left + 1; - active_[Left].push_back( f ); + seeds_[Left].push_back( f ); } } for ( auto f : sink ) @@ -223,7 +273,7 @@ void GraphCut::addFaces( FaceBitSet source, FaceBitSet sink ) if ( isFree_( f ) ) { state_[f] = Right + 1; - active_[Right].push_back( f ); + seeds_[Right].push_back( f ); } } } @@ -232,9 +282,24 @@ FaceBitSet GraphCut::fillLeft( const ProgressCallback& progress ) { MR_TIMER; + // the flow does not pass through contour edges + for ( auto s : contourSlots_ ) + slots_[s].cap = 0; + for ( int side : { Left, Right } ) + { + std::erase_if( seeds_[side].vec, [&]( FaceId f ) { return state_[f] != side + 1; } ); + active_[side].assign( seeds_[side].vec.begin(), seeds_[side].vec.end() ); + } + + // long paths and many orphans per augmentation, or too much work in total: push-relabel is faster + const size_t maxWork = 16 * state_.size(); + const size_t maxWorkPerAugmentation = 500; size_t numCycles = 0; while ( !active_[Left].empty() ) { + if ( work_ > maxWork || ( augmentations_ >= 64 && work_ > maxWorkPerAugmentation * augmentations_ ) ) + return pushRelabel_( progress, numCycles ); + auto lf = active_[Left].front(); active_[Left].pop_front(); processActive_( lf, Left ); @@ -275,7 +340,7 @@ void GraphCut::processActive_( FaceId f, int side ) for ( auto s = firstSlot_[f]; s < firstSlot_[f + 1]; ++s ) { const auto & slot = slots_[s]; - if ( s == parent || slot.cap == ContourEdge ) + if ( s == parent ) continue; const auto r = slot.nei; if ( !r ) @@ -376,12 +441,14 @@ void GraphCut::augment_( FaceId l, SlotId s ) leftCapacity -= minResidualCapacity; rightCapacity -= minResidualCapacity; + ++augmentations_; assert( orphans_.empty() ); for ( auto f = l;; ) { const auto parent = cachePath_[f].parent; if ( !parent ) break; + ++work_; if ( ( cachePath_[f].capacityToParent -= minResidualCapacity ) == 0 ) addOrphan_( f, Left ); f = parent; @@ -394,6 +461,7 @@ void GraphCut::augment_( FaceId l, SlotId s ) const auto parent = cachePath_[f].parent; if ( !parent ) break; + ++work_; if ( ( cachePath_[f].capacityToParent -= minResidualCapacity ) == 0 ) addOrphan_( f, Right ); f = parent; @@ -411,6 +479,7 @@ void GraphCut::adapt_( int side ) { auto f = orphans_.back(); orphans_.pop_back(); + ++work_; if ( !isSide_( f, side ) ) continue; assert( !parentSlot_( f ) ); @@ -461,7 +530,7 @@ void GraphCut::adapt_( int side ) assert( isSide_( r, side ) ); addOrphan_( r, side ); } - if ( !otherSideParent && isSide_( r, 1 - side ) && slot.cap != ContourEdge && treeCapacity_( s, 1 - side ) > 0 ) + if ( !otherSideParent && isSide_( r, 1 - side ) && treeCapacity_( s, 1 - side ) > 0 ) otherSideParent = s; } if ( otherSideParent ) @@ -500,6 +569,290 @@ bool GraphCut::checkNotSaturatedPath_( FaceId f, [[maybe_unused]] int side ) con } } +FaceBitSet GraphCut::pushRelabel_( const ProgressCallback& progress, size_t numCycles ) +{ + MR_TIMER; + + const auto szF = state_.size(); + // return the capacities of tree edges in slots_ (each edge is written from its child face only), and leave only seed faces in state_ + ParallelFor( state_, [&]( FaceId f ) + { + if ( const auto s = parentSlot_( f ) ) + { + const int side = isSide_( f, Left ) ? Left : Right; + const auto bs = slots_[s].back; + auto & treeCapacity = slots_[side == Left ? bs : s].cap; + auto & backCapacity = slots_[side == Left ? s : bs].cap; + const auto cached = cachePath_[f].capacityToParent; + backCapacity += treeCapacity - cached; + treeCapacity = cached; + } + state_[f] = 0; + } ); + // exchange the capacities of opposite dual edges to continue with the same flow in backward direction + ParallelFor( state_, [&]( FaceId f ) + { + for ( auto s = firstSlot_[f]; s < firstSlot_[f + 1]; ++s ) + if ( const auto bs = slots_[s].back; s < bs ) + std::swap( slots_[s].cap, slots_[bs].cap ); + } ); + for ( int side : { Left, Right } ) + { + for ( auto f : seeds_[side] ) + state_[f] = std::uint8_t( side + 1 ); + active_[side] = {}; + } + cachePath_ = {}; + + n_ = int( szF ); + nodes_.resize( szF ); + cur_.resize( szF ); + activeHead_.resize( szF + 1 ); + inactiveHead_.resize( szF + 1 ); + queue_.reserve( szF ); + + for ( auto f : seeds_[Right] ) + { + for ( auto s = firstSlot_[f]; s < firstSlot_[f + 1]; ++s ) + { + auto & slot = slots_[s]; + if ( slot.cap <= 0 || state_[slot.nei] == Right + 1 ) + continue; + if ( state_[slot.nei] == 0 ) + sinkSlots_.push_back( s ); + else + { + // saturate the edge from sink to source + slots_[slot.back].cap += slot.cap; + slot.cap = 0; + } + } + } + globalRelabel_(); + int stagesLeft = 16; + release_( stagesLeft-- ); + + const size_t relabelsBetweenGlobal = 4 * szF; + for ( ;; ) + { + if ( aMax_ <= 0 ) + { + if ( stagesLeft <= 0 ) + break; + release_( stagesLeft-- ); + continue; + } + const auto f = activeHead_[aMax_]; + if ( !f ) + { + --aMax_; + continue; + } + activeHead_[aMax_] = nodes_[f].next; + discharge_( f ); + if ( relabels_ >= relabelsBetweenGlobal ) + globalRelabel_(); + + ++numCycles; + if ( !reportProgress( progress, + [numCycles]() { return std::erf( numCycles * 1e-7f ); }, + numCycles, 65536 ) ) + break; + } + + globalRelabel_(); + FaceBitSet res( szF ); + BitSetParallelForAll( res, [&]( FaceId f ) + { + if ( nodes_[f].label < n_ ) + res.set( f ); + } ); + return res; +} + +inline void GraphCut::addActive_( FaceId f, int label ) +{ + nodes_[f].next = activeHead_[label]; + activeHead_[label] = f; + if ( label > aMax_ ) + aMax_ = label; +} + +inline void GraphCut::addInactive_( FaceId f, int label ) +{ + auto & n = nodes_[f]; + auto & head = inactiveHead_[label]; + n.next = head; + n.prev = FaceId{}; + if ( head ) + nodes_[head].prev = f; + head = f; +} + +inline void GraphCut::removeInactive_( FaceId f, int label ) +{ + const auto & n = nodes_[f]; + if ( n.next ) + nodes_[n.next].prev = n.prev; + if ( n.prev ) + nodes_[n.prev].next = n.next; + else + inactiveHead_[label] = n.next; +} + +void GraphCut::discharge_( FaceId f ) +{ + auto & nf = nodes_[f]; + assert( nf.excess > 0 ); + const auto s0 = firstSlot_[f], s1 = firstSlot_[f + 1]; + for ( ;; ) + { + const int label = nf.label; + assert( label > 0 && label < n_ ); + auto s = s0 + cur_[f]; + for ( ; s < s1; ++s ) + { + auto & slot = slots_[s]; + if ( slot.cap <= 0 ) + continue; + const auto r = slot.nei; + auto & nr = nodes_[r]; + if ( nr.label != label - 1 ) + continue; + const auto d = std::min( nf.excess, slot.cap ); + slot.cap -= d; + slots_[slot.back].cap += d; + nf.excess -= d; + if ( label > 1 ) // otherwise r is a source face + { + if ( nr.excess == 0 ) + { + removeInactive_( r, label - 1 ); + addActive_( r, label - 1 ); + } + nr.excess += d; + } + if ( nf.excess == 0 ) + break; + } + if ( s < s1 ) + { + cur_[f] = std::uint8_t( s - s0 ); + addInactive_( f, label ); + return; + } + + // relabel + ++relabels_; + int minLabel = n_; + auto minSlot = s0; + for ( s = s0; s < s1; ++s ) + { + const auto & slot = slots_[s]; + if ( slot.cap <= 0 ) + continue; + const auto l = nodes_[slot.nei].label; + if ( l < minLabel ) + { + minLabel = l; + minSlot = s; + } + } + if ( !activeHead_[label] && !inactiveHead_[label] ) + { + nf.label = n_; + gap_( label ); + return; + } + if ( minLabel + 1 >= n_ ) + { + nf.label = n_; + return; + } + nf.label = minLabel + 1; + cur_[f] = std::uint8_t( minSlot - s0 ); + if ( nf.label > dMax_ ) + dMax_ = nf.label; + } +} + +void GraphCut::release_( int parts ) +{ + for ( auto s : sinkSlots_ ) + { + auto & slot = slots_[s]; + auto & n = nodes_[slot.nei]; + if ( n.label >= n_ || slot.cap <= 0 ) + continue; + const auto d = parts > 1 ? slot.cap / parts : slot.cap; + if ( d <= 0 ) + continue; + if ( n.excess == 0 ) + { + removeInactive_( slot.nei, n.label ); + addActive_( slot.nei, n.label ); + } + n.excess += d; + slot.cap -= d; + slots_[slot.back].cap += d; + } +} + +void GraphCut::gap_( int g ) +{ + for ( int l = g + 1; l <= dMax_; ++l ) + { + assert( !activeHead_[l] ); + for ( auto f = inactiveHead_[l]; f; f = nodes_[f].next ) + { + nodes_[f].label = n_; + } + inactiveHead_[l] = FaceId{}; + } + dMax_ = aMax_ = g - 1; +} + +void GraphCut::globalRelabel_() +{ + relabels_ = 0; + std::fill( activeHead_.vec.begin(), activeHead_.vec.begin() + dMax_ + 1, FaceId{} ); + std::fill( inactiveHead_.vec.begin(), inactiveHead_.vec.begin() + dMax_ + 1, FaceId{} ); + ParallelFor( nodes_, [&]( FaceId f ) + { + nodes_[f].label = n_; + cur_[f] = 0; + } ); + queue_.clear(); + for ( auto f : seeds_[Left] ) + { + nodes_[f].label = 0; + queue_.push_back( f ); + } + aMax_ = dMax_ = 0; + for ( size_t i = 0; i < queue_.size(); ++i ) + { + const auto f = queue_[i]; + const int label = nodes_[f].label + 1; + for ( auto s = firstSlot_[f]; s < firstSlot_[f + 1]; ++s ) + { + const auto & slot = slots_[s]; + const auto r = slot.nei; + if ( !r ) + continue; + auto & nr = nodes_[r]; + if ( nr.label != n_ || slots_[slot.back].cap <= 0 || state_[r] != 0 ) + continue; + nr.label = label; + queue_.push_back( r ); + if ( nr.excess > 0 ) + addActive_( r, label ); + else + addInactive_( r, label ); + dMax_ = label; + } + } +} + FaceBitSet fillContourLeftByGraphCut( const MeshTopology & topology, const EdgePath & contour, const EdgeMetric & metric, const ProgressCallback& progress ) { MR_TIMER; diff --git a/source/MRTest/MRFillContourByGraphCutTests.cpp b/source/MRTest/MRFillContourByGraphCutTests.cpp index 6acfeb88d5af..2d675ac7c503 100644 --- a/source/MRTest/MRFillContourByGraphCutTests.cpp +++ b/source/MRTest/MRFillContourByGraphCutTests.cpp @@ -3,15 +3,15 @@ #include #include #include +#include #include namespace MR { // open tube with radius 0.5 + |z|, so its narrowest ring is at z = 0; optionally without the triangles of the last column -static Mesh makeNeckTube( int numSegments, bool gap ) +static Mesh makeNeckTube( int numSegments, bool gap, int numRings = 9 ) { - constexpr int numRings = 9; VertCoords points; Triangulation t; for ( int k = 0; k < numRings; ++k ) @@ -85,4 +85,58 @@ TEST( MRMesh, FindMinCutBetweenRegionBoundaries ) EXPECT_EQ( cubeCut.count(), 0 ); } +TEST( MRMesh, SegmentByGraphCutLongPaths ) +{ + // long tube with the seeds on its ends, where augmenting paths are long + constexpr int numSegments = 32; + const auto mesh = makeNeckTube( numSegments, false, 301 ); + const auto& topology = mesh.topology; + FaceBitSet lo( topology.faceSize() ), hi( topology.faceSize() ); + for ( auto f : topology.getValidFaces() ) + { + const auto z = mesh.triCenter( f ).z; + lo.set( f, z < -0.98f ); + hi.set( f, z > 0.98f ); + } + // edge lengths with pseudo-random factors in [1,2) + const EdgeMetric metric = [&] ( EdgeId e ) + { + const auto ue = e.undirected(); + return mesh.edgeLength( ue ) * ( 1 + ( ( unsigned( ue ) * 2654435761u ) >> 16 ) % 16 / 16.0f ); + }; + auto cutCost = [&] ( const FaceBitSet& fs ) + { + double res = 0; + for ( auto ue : undirectedEdges( topology ) ) + { + const auto l = topology.left( ue ), r = topology.right( ue ); + if ( l && r && fs.test( l ) != fs.test( r ) ) + res += metric( ue ); + } + return res; + }; + + const auto fromLo = segmentByGraphCut( topology, lo, hi, metric ); + EXPECT_TRUE( lo.is_subset_of( fromLo ) ); + EXPECT_FALSE( hi.intersects( fromLo ) ); + // minimal cut has the same cost in the opposite direction + const auto fromHi = segmentByGraphCut( topology, hi, lo, metric ); + EXPECT_TRUE( hi.is_subset_of( fromHi ) ); + EXPECT_FALSE( lo.intersects( fromHi ) ); + const auto cost = cutCost( fromLo ); + EXPECT_NEAR( cost, cutCost( fromHi ), 1e-4 * cost ); + + // and not larger cost than of any cut along one ring + double minRingCost = DBL_MAX; + for ( float z = -0.9f; z < 0.95f; z += 0.1f ) + { + FaceBitSet below( topology.faceSize() ); + for ( auto f : topology.getValidFaces() ) + below.set( f, mesh.triCenter( f ).z < z ); + minRingCost = std::min( minRingCost, cutCost( below ) ); + } + EXPECT_LE( cost, minRingCost * ( 1 + 1e-4 ) ); + EXPECT_GT( cost, 0.5 * minRingCost ); +} + } //namespace MR From 0da2cc8ddddef7559fe986da3d815ae5445de709 Mon Sep 17 00:00:00 2001 From: Fedor Chelnokov Date: Sat, 5 Dec 2026 00:25:08 +0300 Subject: [PATCH 2/6] GraphCut: no switch to push-relabel before 4 work units per face The work-per-augmentation rule fired after 0.2 units per face in findOuterLayer on a thick shell of 2M faces, where the trees were about to finish: 2.4x slower than before. Co-Authored-By: Claude Fable 5.2 --- source/MRMesh/MRFillContourByGraphCut.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/source/MRMesh/MRFillContourByGraphCut.cpp b/source/MRMesh/MRFillContourByGraphCut.cpp index 11d3a4a5335c..113b96cd28f4 100644 --- a/source/MRMesh/MRFillContourByGraphCut.cpp +++ b/source/MRMesh/MRFillContourByGraphCut.cpp @@ -291,13 +291,14 @@ FaceBitSet GraphCut::fillLeft( const ProgressCallback& progress ) active_[side].assign( seeds_[side].vec.begin(), seeds_[side].vec.end() ); } - // long paths and many orphans per augmentation, or too much work in total: push-relabel is faster + // too much work in total, or some work with long paths and many orphans per augmentation: push-relabel is faster const size_t maxWork = 16 * state_.size(); + const size_t minWork = 4 * state_.size(); const size_t maxWorkPerAugmentation = 500; size_t numCycles = 0; while ( !active_[Left].empty() ) { - if ( work_ > maxWork || ( augmentations_ >= 64 && work_ > maxWorkPerAugmentation * augmentations_ ) ) + if ( work_ > maxWork || ( work_ > minWork && work_ > maxWorkPerAugmentation * augmentations_ ) ) return pushRelabel_( progress, numCycles ); auto lf = active_[Left].front(); From e6de78b626fd7a84cd7b3910bfb7fdfa6b6e81f9 Mon Sep 17 00:00:00 2001 From: Fedor Chelnokov Date: Sat, 5 Dec 2026 09:48:08 +0300 Subject: [PATCH 3/6] GraphCut: build slots in one pass without temporary edge array The constructor took 28 ms on 1M faces, now about 20 ms. Co-Authored-By: Claude Fable 5.2 --- source/MRMesh/MRFillContourByGraphCut.cpp | 34 +++++++++++------------ 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/source/MRMesh/MRFillContourByGraphCut.cpp b/source/MRMesh/MRFillContourByGraphCut.cpp index 113b96cd28f4..670a51051d0d 100644 --- a/source/MRMesh/MRFillContourByGraphCut.cpp +++ b/source/MRMesh/MRFillContourByGraphCut.cpp @@ -33,7 +33,9 @@ struct Slot { FaceId nei; // the face to the right of the primal edge, invalid for boundary edges SlotId back; // the slot of the opposite dual edge from nei to this face - float cap = 0; // residual capacity of this dual edge (of the opposite dual edge during push-relabel) + float cap; // residual capacity of this dual edge (of the opposite dual edge during push-relabel) + Slot() : cap( 0 ) {} + Slot( NoInit ) : nei( noInit ), back( noInit ) {} }; static_assert( sizeof( Slot ) == 12 ); @@ -157,8 +159,7 @@ GraphCut::GraphCut( const MeshTopology & topology, const EdgeMetric & metric ) : firstSlot_[f + 1] += firstSlot_[f]; const auto n = firstSlot_[FaceId( szF )]; - slots_.resize( n ); - Vector slotEdge( n ); + slots_.resizeNoInit( n ); ParallelFor( 0_f, FaceId( szF ), [&]( FaceId f ) { if ( !topology.hasFace( f ) ) @@ -166,28 +167,25 @@ GraphCut::GraphCut( const MeshTopology & topology, const EdgeMetric & metric ) : auto s = firstSlot_[f]; for ( EdgeId e : leftRing( topology, f ) ) { - slots_[s].nei = topology.right( e ); - slotEdge[s] = e; - ++s; - } - assert( s == firstSlot_[f + 1] ); - } ); - ParallelFor( 0_f, FaceId( szF ), [&]( FaceId f ) - { - for ( auto s = firstSlot_[f]; s < firstSlot_[f + 1]; ++s ) - { - const auto r = slots_[s].nei; + auto & slot = slots_[s++]; + const auto r = slot.nei = topology.right( e ); if ( !r ) + { + slot.back = SlotId{}; + slot.cap = 0; continue; - const auto e = slotEdge[s]; + } + // the position of e.sym() among the edges of r auto bs = firstSlot_[r]; - while ( slotEdge[bs] != e.sym() ) + for ( auto x = topology.edgeWithLeft( r ); x != e.sym(); x = topology.prev( x.sym() ) ) ++bs; assert( bs < firstSlot_[r + 1] ); - slots_[s].back = bs; + slot.back = bs; + // both capacities of an edge are written by one thread if ( e.even() ) - slots_[s].cap = slots_[bs].cap = metric( e ); + slot.cap = slots_[bs].cap = metric( e ); } + assert( s == firstSlot_[f + 1] ); } ); } From c04ac36bf8869bdb0a657788fe7495a25bfa4d7e Mon Sep 17 00:00:00 2001 From: Fedor Chelnokov Date: Sat, 5 Dec 2026 10:54:41 +0300 Subject: [PATCH 4/6] GraphCut: global relabeling from boundary source faces, every n relabels Shells in findOuterLayer with thickness 1.5-1.7% of the box diagonal were slower than with trees only, now they are faster. Co-Authored-By: Claude Fable 5.2 --- source/MRMesh/MRFillContourByGraphCut.cpp | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/source/MRMesh/MRFillContourByGraphCut.cpp b/source/MRMesh/MRFillContourByGraphCut.cpp index 670a51051d0d..e6405f201901 100644 --- a/source/MRMesh/MRFillContourByGraphCut.cpp +++ b/source/MRMesh/MRFillContourByGraphCut.cpp @@ -603,6 +603,15 @@ FaceBitSet GraphCut::pushRelabel_( const ProgressCallback& progress, size_t numC } cachePath_ = {}; + // global relabeling starts only from the source faces having other neighbors + std::erase_if( seeds_[Left].vec, [&]( FaceId f ) + { + for ( auto s = firstSlot_[f]; s < firstSlot_[f + 1]; ++s ) + if ( const auto r = slots_[s].nei; r && state_[r] != Left + 1 ) + return false; + return true; + } ); + n_ = int( szF ); nodes_.resize( szF ); cur_.resize( szF ); @@ -631,7 +640,7 @@ FaceBitSet GraphCut::pushRelabel_( const ProgressCallback& progress, size_t numC int stagesLeft = 16; release_( stagesLeft-- ); - const size_t relabelsBetweenGlobal = 4 * szF; + const size_t relabelsBetweenGlobal = szF; for ( ;; ) { if ( aMax_ <= 0 ) @@ -818,15 +827,10 @@ void GraphCut::globalRelabel_() std::fill( inactiveHead_.vec.begin(), inactiveHead_.vec.begin() + dMax_ + 1, FaceId{} ); ParallelFor( nodes_, [&]( FaceId f ) { - nodes_[f].label = n_; + nodes_[f].label = state_[f] == Left + 1 ? 0 : n_; cur_[f] = 0; } ); - queue_.clear(); - for ( auto f : seeds_[Left] ) - { - nodes_[f].label = 0; - queue_.push_back( f ); - } + queue_.assign( seeds_[Left].vec.begin(), seeds_[Left].vec.end() ); aMax_ = dMax_ = 0; for ( size_t i = 0; i < queue_.size(); ++i ) { From 603f00140ee30173124523f148fe159505a02c82 Mon Sep 17 00:00:00 2001 From: Fedor Chelnokov Date: Sat, 5 Dec 2026 15:39:45 +0300 Subject: [PATCH 5/6] GraphCut: race push-relabel against further path augmentation Push-relabel works on a copy of the residual graph while path augmentation continues in a task, the first to finish gives the result. Shells in findOuterLayer with thickness 1.1-1.3% of the box diagonal were up to 1.46x slower than with trees only, now within 8%. Co-Authored-By: Claude Fable 5.2 --- source/MRMesh/MRFillContourByGraphCut.cpp | 229 ++++++++++++++-------- 1 file changed, 151 insertions(+), 78 deletions(-) diff --git a/source/MRMesh/MRFillContourByGraphCut.cpp b/source/MRMesh/MRFillContourByGraphCut.cpp index e6405f201901..320afef13f54 100644 --- a/source/MRMesh/MRFillContourByGraphCut.cpp +++ b/source/MRMesh/MRFillContourByGraphCut.cpp @@ -12,7 +12,9 @@ #include "MRBitSetParallelFor.h" #include "MRParallelFor.h" #include "MRTimer.h" +#include "MRPch/MRTBB.h" #include +#include #include #include @@ -58,10 +60,51 @@ struct Node }; static_assert( sizeof( Node ) == 16 ); +/// completes the maximal flow by push-relabel method with the highest label selection, global relabeling and gap heuristics; +/// it pushes the flow backward from sink faces to source faces, so in the end the faces that can reach a source face +/// are exactly the faces reachable from source faces in the residual graph, same as Left tree of augmenting paths +class PushRelabel +{ +public: + /// \param slots with residual capacities exchanged in every pair of opposite dual edges + /// \param state Left + 1 for source faces, Right + 1 for sink faces, 0 for other faces + PushRelabel( const Vector & firstSlot, Vector slots, Vector state, + Vector sources, const Vector & sinks ); + /// returns the faces on the left side of the minimal cut, or nothing if stopped from outside + FaceBitSet run( const ProgressCallback& progress, size_t numCycles, const std::atomic & stop ); + +private: + const Vector & firstSlot_; + Vector slots_; + Vector state_; + Vector sources_; // only the source faces having other neighbors, where global relabeling starts + Vector nodes_; + Vector cur_; // local index of the first slot of the face not yet found inadmissible + Vector activeHead_, inactiveHead_; // per label: the lists of faces with and without excess + Vector queue_; + Vector sinkSlots_; // not saturated dual edges from sink faces + int n_ = 0; // the label of faces that cannot reach source faces + int aMax_ = 0; // no active faces have larger label + int dMax_ = 0; // no listed faces have larger label + size_t relabels_ = 0; // after the last global relabeling + + void addActive_( FaceId f, int label ); + void addInactive_( FaceId f, int label ); + void removeInactive_( FaceId f, int label ); + // pushes the excess of f to its neighbors with relabeling of f as necessary + void discharge_( FaceId f ); + // layer g became empty, so all faces with larger labels cannot reach source faces + void gap_( int g ); + // sets exact distances to source faces in the residual graph as labels + void globalRelabel_(); + // pushes 1/parts of remaining capacities of the edges from sink faces; + // all capacities at once would make much more excess than the maximal flow, and it takes long to find that it cannot reach sources + void release_( int parts ); +}; + /// finds the minimal cut between source (Left) and sink (Right) faces: /// starts by augmenting paths between two search trees, which is the fastest while the paths are short, -/// and if that takes too much work, continues from the same flow by push-relabel method -/// with the highest label selection, global relabeling and gap heuristics +/// and if that takes too much work, push-relabel method starts from the same flow in parallel, and the first to finish gives the result class GraphCut { public: @@ -85,18 +128,6 @@ class GraphCut size_t work_ = 0; // the number of orphans and path steps processed size_t augmentations_ = 0; - // push-relabel pushes the flow backward from sink faces to source faces, so in the end the faces that can reach a source face - // are exactly the faces reachable from source faces in the residual graph, same as Left tree of augmenting paths - Vector nodes_; - Vector cur_; // local index of the first slot of the face not yet found inadmissible - Vector activeHead_, inactiveHead_; // per label: the lists of faces with and without excess - Vector queue_; - Vector sinkSlots_; // not saturated dual edges from sink faces - int n_ = 0; // the label of faces that cannot reach source faces - int aMax_ = 0; // no active faces have larger label - int dMax_ = 0; // no listed faces have larger label - size_t relabels_ = 0; // after the last global relabeling - // returns true if face f is on given side bool isSide_( FaceId f, int side ) const { return ( state_[f] & 3 ) == side + 1; } // returns true if face f is on no side @@ -107,6 +138,10 @@ class GraphCut SlotId slotOf_( EdgeId e ) const; // residual capacity of the dual edge in given slot from the side of the tree root float treeCapacity_( SlotId s, int side ) const { return side == Left ? slots_[slots_[s].back].cap : slots_[s].cap; } + // process one active face from each side + void step_(); + // returns the faces on the left side + FaceBitSet leftFaces_() const; // process given active face which should belong to given side (left or right) void processActive_( FaceId f, int side ); // augment the path joined at the dual edge going from a left face l in slot s @@ -121,21 +156,8 @@ class GraphCut bool isGrandparent_( FaceId child, FaceId grand ) const; // checks that there is not saturated path from f to a root bool checkNotSaturatedPath_( FaceId f, int side ) const; - - // completes the flow by push-relabel method, returns the faces on the left side of the minimal cut - FaceBitSet pushRelabel_( const ProgressCallback& progress, size_t numCycles ); - void addActive_( FaceId f, int label ); - void addInactive_( FaceId f, int label ); - void removeInactive_( FaceId f, int label ); - // pushes the excess of f to its neighbors with relabeling of f as necessary - void discharge_( FaceId f ); - // layer g became empty, so all faces with larger labels cannot reach source faces - void gap_( int g ); - // sets exact distances to source faces in the residual graph as labels - void globalRelabel_(); - // pushes 1/parts of remaining capacities of the edges from sink faces; - // all capacities at once would make much more excess than the maximal flow, and it takes long to find that it cannot reach sources - void release_( int parts ); + // races push-relabel method against further path augmentation, returns the faces on the left side of the minimal cut + FaceBitSet race_( const ProgressCallback& progress, size_t numCycles ); }; GraphCut::GraphCut( const MeshTopology & topology, const EdgeMetric & metric ) : topology_( topology ) @@ -289,7 +311,7 @@ FaceBitSet GraphCut::fillLeft( const ProgressCallback& progress ) active_[side].assign( seeds_[side].vec.begin(), seeds_[side].vec.end() ); } - // too much work in total, or some work with long paths and many orphans per augmentation: push-relabel is faster + // too much work in total, or some work with long paths and many orphans per augmentation: push-relabel is typically faster const size_t maxWork = 16 * state_.size(); const size_t minWork = 4 * state_.size(); const size_t maxWorkPerAugmentation = 500; @@ -297,19 +319,9 @@ FaceBitSet GraphCut::fillLeft( const ProgressCallback& progress ) while ( !active_[Left].empty() ) { if ( work_ > maxWork || ( work_ > minWork && work_ > maxWorkPerAugmentation * augmentations_ ) ) - return pushRelabel_( progress, numCycles ); - - auto lf = active_[Left].front(); - active_[Left].pop_front(); - processActive_( lf, Left ); - - if ( !active_[Right].empty() ) - { - auto rf = active_[Right].front(); - active_[Right].pop_front(); - processActive_( rf, Right ); - } + return race_( progress, numCycles ); + step_(); ++numCycles; if ( !reportProgress( progress, [numCycles]() { return std::erf( numCycles * 1e-7f ); }, // report 84% for numCycles == 10'000'000 @@ -321,6 +333,25 @@ FaceBitSet GraphCut::fillLeft( const ProgressCallback& progress ) // if ( active_[Right].empty() ) // return topology_.getValidFaces() - (faces on Right side); + return leftFaces_(); +} + +inline void GraphCut::step_() +{ + auto lf = active_[Left].front(); + active_[Left].pop_front(); + processActive_( lf, Left ); + + if ( !active_[Right].empty() ) + { + auto rf = active_[Right].front(); + active_[Right].pop_front(); + processActive_( rf, Right ); + } +} + +FaceBitSet GraphCut::leftFaces_() const +{ FaceBitSet res( state_.size() ); BitSetParallelForAll( res, [&]( FaceId f ) { @@ -568,43 +599,76 @@ bool GraphCut::checkNotSaturatedPath_( FaceId f, [[maybe_unused]] int side ) con } } -FaceBitSet GraphCut::pushRelabel_( const ProgressCallback& progress, size_t numCycles ) +FaceBitSet GraphCut::race_( const ProgressCallback& progress, size_t numCycles ) { MR_TIMER; - const auto szF = state_.size(); - // return the capacities of tree edges in slots_ (each edge is written from its child face only), and leave only seed faces in state_ + // push-relabel gets a copy of the residual graph with the capacities of opposite dual edges exchanged, + // to continue with the same flow in backward direction + Vector slots; + slots.resizeNoInit( slots_.size() ); ParallelFor( state_, [&]( FaceId f ) { - if ( const auto s = parentSlot_( f ) ) + const auto parent = parentSlot_( f ); + for ( auto s = firstSlot_[f]; s < firstSlot_[f + 1]; ++s ) { - const int side = isSide_( f, Left ) ? Left : Right; - const auto bs = slots_[s].back; - auto & treeCapacity = slots_[side == Left ? bs : s].cap; - auto & backCapacity = slots_[side == Left ? s : bs].cap; - const auto cached = cachePath_[f].capacityToParent; - backCapacity += treeCapacity - cached; - treeCapacity = cached; + const auto & slot = slots_[s]; + auto & res = slots[s]; + res.nei = slot.nei; + res.back = slot.back; + res.cap = 0; + const auto r = slot.nei; + if ( !r ) + continue; + res.cap = slots_[slot.back].cap; + // actual capacity of a tree edge from the side of the root is in the cache of the child face + if ( s == parent ) + { + const auto cached = cachePath_[f].capacityToParent; + res.cap = isSide_( f, Left ) ? cached : res.cap + ( slot.cap - cached ); + } + else if ( slot.back == parentSlot_( r ) ) + { + const auto cached = cachePath_[r].capacityToParent; + res.cap = isSide_( r, Left ) ? res.cap + ( slot.cap - cached ) : cached; + } } - state_[f] = 0; } ); - // exchange the capacities of opposite dual edges to continue with the same flow in backward direction - ParallelFor( state_, [&]( FaceId f ) + // path augmentation continues in another thread: it can be near the end, where push-relabel takes longer + std::atomic stop{ false }; + bool augmented = false; + tbb::task_group group; + group.run( [&] { - for ( auto s = firstSlot_[f]; s < firstSlot_[f + 1]; ++s ) - if ( const auto bs = slots_[s].back; s < bs ) - std::swap( slots_[s].cap, slots_[bs].cap ); + while ( !active_[Left].empty() ) + { + if ( stop.load( std::memory_order_relaxed ) ) + return; + step_(); + } + augmented = true; + stop = true; } ); - for ( int side : { Left, Right } ) + // isolation prevents this thread from taking the above task while it waits for parallel loops + auto res = tbb::this_task_arena::isolate( [&] { - for ( auto f : seeds_[side] ) - state_[f] = std::uint8_t( side + 1 ); - active_[side] = {}; - } - cachePath_ = {}; + Vector state( state_.size() ); + for ( int side : { Left, Right } ) + for ( auto f : seeds_[side] ) + state[f] = std::uint8_t( side + 1 ); + PushRelabel pr( firstSlot_, std::move( slots ), std::move( state ), std::move( seeds_[Left] ), seeds_[Right] ); + return pr.run( progress, numCycles, stop ); + } ); + stop = true; + group.wait(); + return augmented ? leftFaces_() : res; +} - // global relabeling starts only from the source faces having other neighbors - std::erase_if( seeds_[Left].vec, [&]( FaceId f ) +PushRelabel::PushRelabel( const Vector & firstSlot, Vector slots, Vector state, + Vector sources, const Vector & sinks ) + : firstSlot_( firstSlot ), slots_( std::move( slots ) ), state_( std::move( state ) ), sources_( std::move( sources ) ) +{ + std::erase_if( sources_.vec, [&]( FaceId f ) { for ( auto s = firstSlot_[f]; s < firstSlot_[f + 1]; ++s ) if ( const auto r = slots_[s].nei; r && state_[r] != Left + 1 ) @@ -612,6 +676,7 @@ FaceBitSet GraphCut::pushRelabel_( const ProgressCallback& progress, size_t numC return true; } ); + const auto szF = state_.size(); n_ = int( szF ); nodes_.resize( szF ); cur_.resize( szF ); @@ -619,7 +684,7 @@ FaceBitSet GraphCut::pushRelabel_( const ProgressCallback& progress, size_t numC inactiveHead_.resize( szF + 1 ); queue_.reserve( szF ); - for ( auto f : seeds_[Right] ) + for ( auto f : sinks ) { for ( auto s = firstSlot_[f]; s < firstSlot_[f + 1]; ++s ) { @@ -636,13 +701,21 @@ FaceBitSet GraphCut::pushRelabel_( const ProgressCallback& progress, size_t numC } } } +} + +FaceBitSet PushRelabel::run( const ProgressCallback& progress, size_t numCycles, const std::atomic & stop ) +{ + MR_TIMER; + globalRelabel_(); int stagesLeft = 16; release_( stagesLeft-- ); - const size_t relabelsBetweenGlobal = szF; + const size_t relabelsBetweenGlobal = state_.size(); for ( ;; ) { + if ( stop.load( std::memory_order_relaxed ) ) + return {}; if ( aMax_ <= 0 ) { if ( stagesLeft <= 0 ) @@ -669,7 +742,7 @@ FaceBitSet GraphCut::pushRelabel_( const ProgressCallback& progress, size_t numC } globalRelabel_(); - FaceBitSet res( szF ); + FaceBitSet res( state_.size() ); BitSetParallelForAll( res, [&]( FaceId f ) { if ( nodes_[f].label < n_ ) @@ -678,7 +751,7 @@ FaceBitSet GraphCut::pushRelabel_( const ProgressCallback& progress, size_t numC return res; } -inline void GraphCut::addActive_( FaceId f, int label ) +inline void PushRelabel::addActive_( FaceId f, int label ) { nodes_[f].next = activeHead_[label]; activeHead_[label] = f; @@ -686,7 +759,7 @@ inline void GraphCut::addActive_( FaceId f, int label ) aMax_ = label; } -inline void GraphCut::addInactive_( FaceId f, int label ) +inline void PushRelabel::addInactive_( FaceId f, int label ) { auto & n = nodes_[f]; auto & head = inactiveHead_[label]; @@ -697,7 +770,7 @@ inline void GraphCut::addInactive_( FaceId f, int label ) head = f; } -inline void GraphCut::removeInactive_( FaceId f, int label ) +inline void PushRelabel::removeInactive_( FaceId f, int label ) { const auto & n = nodes_[f]; if ( n.next ) @@ -708,7 +781,7 @@ inline void GraphCut::removeInactive_( FaceId f, int label ) inactiveHead_[label] = n.next; } -void GraphCut::discharge_( FaceId f ) +void PushRelabel::discharge_( FaceId f ) { auto & nf = nodes_[f]; assert( nf.excess > 0 ); @@ -784,7 +857,7 @@ void GraphCut::discharge_( FaceId f ) } } -void GraphCut::release_( int parts ) +void PushRelabel::release_( int parts ) { for ( auto s : sinkSlots_ ) { @@ -806,7 +879,7 @@ void GraphCut::release_( int parts ) } } -void GraphCut::gap_( int g ) +void PushRelabel::gap_( int g ) { for ( int l = g + 1; l <= dMax_; ++l ) { @@ -820,7 +893,7 @@ void GraphCut::gap_( int g ) dMax_ = aMax_ = g - 1; } -void GraphCut::globalRelabel_() +void PushRelabel::globalRelabel_() { relabels_ = 0; std::fill( activeHead_.vec.begin(), activeHead_.vec.begin() + dMax_ + 1, FaceId{} ); @@ -830,7 +903,7 @@ void GraphCut::globalRelabel_() nodes_[f].label = state_[f] == Left + 1 ? 0 : n_; cur_[f] = 0; } ); - queue_.assign( seeds_[Left].vec.begin(), seeds_[Left].vec.end() ); + queue_.assign( sources_.vec.begin(), sources_.vec.end() ); aMax_ = dMax_ = 0; for ( size_t i = 0; i < queue_.size(); ++i ) { From 18466bfd3ddcaab40cdcb123182c87aa1690a36c Mon Sep 17 00:00:00 2001 From: Fedor Chelnokov Date: Sat, 5 Dec 2026 17:50:52 +0300 Subject: [PATCH 6/6] GraphCut: switch to push-relabel after 32 work units per face, no race An earlier switch was up to 1.5x slower than trees only on shells in findOuterLayer with thickness 1.1-1.3% of the box diagonal, and racing the two methods helped only with a free thread. With the later switch no sampled thickness is slower. Co-Authored-By: Claude Fable 5.2 --- source/MRMesh/MRFillContourByGraphCut.cpp | 237 ++++++++-------------- 1 file changed, 80 insertions(+), 157 deletions(-) diff --git a/source/MRMesh/MRFillContourByGraphCut.cpp b/source/MRMesh/MRFillContourByGraphCut.cpp index 320afef13f54..2d5748f6c9d7 100644 --- a/source/MRMesh/MRFillContourByGraphCut.cpp +++ b/source/MRMesh/MRFillContourByGraphCut.cpp @@ -12,9 +12,7 @@ #include "MRBitSetParallelFor.h" #include "MRParallelFor.h" #include "MRTimer.h" -#include "MRPch/MRTBB.h" #include -#include #include #include @@ -60,51 +58,10 @@ struct Node }; static_assert( sizeof( Node ) == 16 ); -/// completes the maximal flow by push-relabel method with the highest label selection, global relabeling and gap heuristics; -/// it pushes the flow backward from sink faces to source faces, so in the end the faces that can reach a source face -/// are exactly the faces reachable from source faces in the residual graph, same as Left tree of augmenting paths -class PushRelabel -{ -public: - /// \param slots with residual capacities exchanged in every pair of opposite dual edges - /// \param state Left + 1 for source faces, Right + 1 for sink faces, 0 for other faces - PushRelabel( const Vector & firstSlot, Vector slots, Vector state, - Vector sources, const Vector & sinks ); - /// returns the faces on the left side of the minimal cut, or nothing if stopped from outside - FaceBitSet run( const ProgressCallback& progress, size_t numCycles, const std::atomic & stop ); - -private: - const Vector & firstSlot_; - Vector slots_; - Vector state_; - Vector sources_; // only the source faces having other neighbors, where global relabeling starts - Vector nodes_; - Vector cur_; // local index of the first slot of the face not yet found inadmissible - Vector activeHead_, inactiveHead_; // per label: the lists of faces with and without excess - Vector queue_; - Vector sinkSlots_; // not saturated dual edges from sink faces - int n_ = 0; // the label of faces that cannot reach source faces - int aMax_ = 0; // no active faces have larger label - int dMax_ = 0; // no listed faces have larger label - size_t relabels_ = 0; // after the last global relabeling - - void addActive_( FaceId f, int label ); - void addInactive_( FaceId f, int label ); - void removeInactive_( FaceId f, int label ); - // pushes the excess of f to its neighbors with relabeling of f as necessary - void discharge_( FaceId f ); - // layer g became empty, so all faces with larger labels cannot reach source faces - void gap_( int g ); - // sets exact distances to source faces in the residual graph as labels - void globalRelabel_(); - // pushes 1/parts of remaining capacities of the edges from sink faces; - // all capacities at once would make much more excess than the maximal flow, and it takes long to find that it cannot reach sources - void release_( int parts ); -}; - /// finds the minimal cut between source (Left) and sink (Right) faces: /// starts by augmenting paths between two search trees, which is the fastest while the paths are short, -/// and if that takes too much work, push-relabel method starts from the same flow in parallel, and the first to finish gives the result +/// and if that takes too much work, continues from the same flow by push-relabel method +/// with the highest label selection, global relabeling and gap heuristics class GraphCut { public: @@ -126,7 +83,18 @@ class GraphCut Vector seeds_[2]; Vector contourSlots_; size_t work_ = 0; // the number of orphans and path steps processed - size_t augmentations_ = 0; + + // push-relabel pushes the flow backward from sink faces to source faces, so in the end the faces that can reach a source face + // are exactly the faces reachable from source faces in the residual graph, same as Left tree of augmenting paths + Vector nodes_; + Vector cur_; // local index of the first slot of the face not yet found inadmissible + Vector activeHead_, inactiveHead_; // per label: the lists of faces with and without excess + Vector queue_; + Vector sinkSlots_; // not saturated dual edges from sink faces + int n_ = 0; // the label of faces that cannot reach source faces + int aMax_ = 0; // no active faces have larger label + int dMax_ = 0; // no listed faces have larger label + size_t relabels_ = 0; // after the last global relabeling // returns true if face f is on given side bool isSide_( FaceId f, int side ) const { return ( state_[f] & 3 ) == side + 1; } @@ -138,10 +106,6 @@ class GraphCut SlotId slotOf_( EdgeId e ) const; // residual capacity of the dual edge in given slot from the side of the tree root float treeCapacity_( SlotId s, int side ) const { return side == Left ? slots_[slots_[s].back].cap : slots_[s].cap; } - // process one active face from each side - void step_(); - // returns the faces on the left side - FaceBitSet leftFaces_() const; // process given active face which should belong to given side (left or right) void processActive_( FaceId f, int side ); // augment the path joined at the dual edge going from a left face l in slot s @@ -156,8 +120,21 @@ class GraphCut bool isGrandparent_( FaceId child, FaceId grand ) const; // checks that there is not saturated path from f to a root bool checkNotSaturatedPath_( FaceId f, int side ) const; - // races push-relabel method against further path augmentation, returns the faces on the left side of the minimal cut - FaceBitSet race_( const ProgressCallback& progress, size_t numCycles ); + + // completes the flow by push-relabel method, returns the faces on the left side of the minimal cut + FaceBitSet pushRelabel_( const ProgressCallback& progress, size_t numCycles ); + void addActive_( FaceId f, int label ); + void addInactive_( FaceId f, int label ); + void removeInactive_( FaceId f, int label ); + // pushes the excess of f to its neighbors with relabeling of f as necessary + void discharge_( FaceId f ); + // layer g became empty, so all faces with larger labels cannot reach source faces + void gap_( int g ); + // sets exact distances to source faces in the residual graph as labels + void globalRelabel_(); + // pushes 1/parts of remaining capacities of the edges from sink faces; + // all capacities at once would make much more excess than the maximal flow, and it takes long to find that it cannot reach sources + void release_( int parts ); }; GraphCut::GraphCut( const MeshTopology & topology, const EdgeMetric & metric ) : topology_( topology ) @@ -311,17 +288,25 @@ FaceBitSet GraphCut::fillLeft( const ProgressCallback& progress ) active_[side].assign( seeds_[side].vec.begin(), seeds_[side].vec.end() ); } - // too much work in total, or some work with long paths and many orphans per augmentation: push-relabel is typically faster - const size_t maxWork = 16 * state_.size(); - const size_t minWork = 4 * state_.size(); - const size_t maxWorkPerAugmentation = 500; + // after that much work, push-relabel is faster; with an earlier switch it loses where the paths are about to finish + const size_t maxWork = 32 * state_.size(); size_t numCycles = 0; while ( !active_[Left].empty() ) { - if ( work_ > maxWork || ( work_ > minWork && work_ > maxWorkPerAugmentation * augmentations_ ) ) - return race_( progress, numCycles ); + if ( work_ > maxWork ) + return pushRelabel_( progress, numCycles ); + + auto lf = active_[Left].front(); + active_[Left].pop_front(); + processActive_( lf, Left ); + + if ( !active_[Right].empty() ) + { + auto rf = active_[Right].front(); + active_[Right].pop_front(); + processActive_( rf, Right ); + } - step_(); ++numCycles; if ( !reportProgress( progress, [numCycles]() { return std::erf( numCycles * 1e-7f ); }, // report 84% for numCycles == 10'000'000 @@ -333,25 +318,6 @@ FaceBitSet GraphCut::fillLeft( const ProgressCallback& progress ) // if ( active_[Right].empty() ) // return topology_.getValidFaces() - (faces on Right side); - return leftFaces_(); -} - -inline void GraphCut::step_() -{ - auto lf = active_[Left].front(); - active_[Left].pop_front(); - processActive_( lf, Left ); - - if ( !active_[Right].empty() ) - { - auto rf = active_[Right].front(); - active_[Right].pop_front(); - processActive_( rf, Right ); - } -} - -FaceBitSet GraphCut::leftFaces_() const -{ FaceBitSet res( state_.size() ); BitSetParallelForAll( res, [&]( FaceId f ) { @@ -471,7 +437,6 @@ void GraphCut::augment_( FaceId l, SlotId s ) leftCapacity -= minResidualCapacity; rightCapacity -= minResidualCapacity; - ++augmentations_; assert( orphans_.empty() ); for ( auto f = l;; ) { @@ -599,76 +564,43 @@ bool GraphCut::checkNotSaturatedPath_( FaceId f, [[maybe_unused]] int side ) con } } -FaceBitSet GraphCut::race_( const ProgressCallback& progress, size_t numCycles ) +FaceBitSet GraphCut::pushRelabel_( const ProgressCallback& progress, size_t numCycles ) { MR_TIMER; - // push-relabel gets a copy of the residual graph with the capacities of opposite dual edges exchanged, - // to continue with the same flow in backward direction - Vector slots; - slots.resizeNoInit( slots_.size() ); + const auto szF = state_.size(); + // return the capacities of tree edges in slots_ (each edge is written from its child face only), and leave only seed faces in state_ ParallelFor( state_, [&]( FaceId f ) { - const auto parent = parentSlot_( f ); - for ( auto s = firstSlot_[f]; s < firstSlot_[f + 1]; ++s ) + if ( const auto s = parentSlot_( f ) ) { - const auto & slot = slots_[s]; - auto & res = slots[s]; - res.nei = slot.nei; - res.back = slot.back; - res.cap = 0; - const auto r = slot.nei; - if ( !r ) - continue; - res.cap = slots_[slot.back].cap; - // actual capacity of a tree edge from the side of the root is in the cache of the child face - if ( s == parent ) - { - const auto cached = cachePath_[f].capacityToParent; - res.cap = isSide_( f, Left ) ? cached : res.cap + ( slot.cap - cached ); - } - else if ( slot.back == parentSlot_( r ) ) - { - const auto cached = cachePath_[r].capacityToParent; - res.cap = isSide_( r, Left ) ? res.cap + ( slot.cap - cached ) : cached; - } + const int side = isSide_( f, Left ) ? Left : Right; + const auto bs = slots_[s].back; + auto & treeCapacity = slots_[side == Left ? bs : s].cap; + auto & backCapacity = slots_[side == Left ? s : bs].cap; + const auto cached = cachePath_[f].capacityToParent; + backCapacity += treeCapacity - cached; + treeCapacity = cached; } + state_[f] = 0; } ); - // path augmentation continues in another thread: it can be near the end, where push-relabel takes longer - std::atomic stop{ false }; - bool augmented = false; - tbb::task_group group; - group.run( [&] + // exchange the capacities of opposite dual edges to continue with the same flow in backward direction + ParallelFor( state_, [&]( FaceId f ) { - while ( !active_[Left].empty() ) - { - if ( stop.load( std::memory_order_relaxed ) ) - return; - step_(); - } - augmented = true; - stop = true; + for ( auto s = firstSlot_[f]; s < firstSlot_[f + 1]; ++s ) + if ( const auto bs = slots_[s].back; s < bs ) + std::swap( slots_[s].cap, slots_[bs].cap ); } ); - // isolation prevents this thread from taking the above task while it waits for parallel loops - auto res = tbb::this_task_arena::isolate( [&] + for ( int side : { Left, Right } ) { - Vector state( state_.size() ); - for ( int side : { Left, Right } ) - for ( auto f : seeds_[side] ) - state[f] = std::uint8_t( side + 1 ); - PushRelabel pr( firstSlot_, std::move( slots ), std::move( state ), std::move( seeds_[Left] ), seeds_[Right] ); - return pr.run( progress, numCycles, stop ); - } ); - stop = true; - group.wait(); - return augmented ? leftFaces_() : res; -} + for ( auto f : seeds_[side] ) + state_[f] = std::uint8_t( side + 1 ); + active_[side] = {}; + } + cachePath_ = {}; -PushRelabel::PushRelabel( const Vector & firstSlot, Vector slots, Vector state, - Vector sources, const Vector & sinks ) - : firstSlot_( firstSlot ), slots_( std::move( slots ) ), state_( std::move( state ) ), sources_( std::move( sources ) ) -{ - std::erase_if( sources_.vec, [&]( FaceId f ) + // global relabeling starts only from the source faces having other neighbors + std::erase_if( seeds_[Left].vec, [&]( FaceId f ) { for ( auto s = firstSlot_[f]; s < firstSlot_[f + 1]; ++s ) if ( const auto r = slots_[s].nei; r && state_[r] != Left + 1 ) @@ -676,7 +608,6 @@ PushRelabel::PushRelabel( const Vector & firstSlot, Vector & firstSlot, Vector & firstSlot, Vector & stop ) -{ - MR_TIMER; - globalRelabel_(); int stagesLeft = 16; release_( stagesLeft-- ); - const size_t relabelsBetweenGlobal = state_.size(); + const size_t relabelsBetweenGlobal = szF; for ( ;; ) { - if ( stop.load( std::memory_order_relaxed ) ) - return {}; if ( aMax_ <= 0 ) { if ( stagesLeft <= 0 ) @@ -742,7 +665,7 @@ FaceBitSet PushRelabel::run( const ProgressCallback& progress, size_t numCycles, } globalRelabel_(); - FaceBitSet res( state_.size() ); + FaceBitSet res( szF ); BitSetParallelForAll( res, [&]( FaceId f ) { if ( nodes_[f].label < n_ ) @@ -751,7 +674,7 @@ FaceBitSet PushRelabel::run( const ProgressCallback& progress, size_t numCycles, return res; } -inline void PushRelabel::addActive_( FaceId f, int label ) +inline void GraphCut::addActive_( FaceId f, int label ) { nodes_[f].next = activeHead_[label]; activeHead_[label] = f; @@ -759,7 +682,7 @@ inline void PushRelabel::addActive_( FaceId f, int label ) aMax_ = label; } -inline void PushRelabel::addInactive_( FaceId f, int label ) +inline void GraphCut::addInactive_( FaceId f, int label ) { auto & n = nodes_[f]; auto & head = inactiveHead_[label]; @@ -770,7 +693,7 @@ inline void PushRelabel::addInactive_( FaceId f, int label ) head = f; } -inline void PushRelabel::removeInactive_( FaceId f, int label ) +inline void GraphCut::removeInactive_( FaceId f, int label ) { const auto & n = nodes_[f]; if ( n.next ) @@ -781,7 +704,7 @@ inline void PushRelabel::removeInactive_( FaceId f, int label ) inactiveHead_[label] = n.next; } -void PushRelabel::discharge_( FaceId f ) +void GraphCut::discharge_( FaceId f ) { auto & nf = nodes_[f]; assert( nf.excess > 0 ); @@ -857,7 +780,7 @@ void PushRelabel::discharge_( FaceId f ) } } -void PushRelabel::release_( int parts ) +void GraphCut::release_( int parts ) { for ( auto s : sinkSlots_ ) { @@ -879,7 +802,7 @@ void PushRelabel::release_( int parts ) } } -void PushRelabel::gap_( int g ) +void GraphCut::gap_( int g ) { for ( int l = g + 1; l <= dMax_; ++l ) { @@ -893,7 +816,7 @@ void PushRelabel::gap_( int g ) dMax_ = aMax_ = g - 1; } -void PushRelabel::globalRelabel_() +void GraphCut::globalRelabel_() { relabels_ = 0; std::fill( activeHead_.vec.begin(), activeHead_.vec.begin() + dMax_ + 1, FaceId{} ); @@ -903,7 +826,7 @@ void PushRelabel::globalRelabel_() nodes_[f].label = state_[f] == Left + 1 ? 0 : n_; cur_[f] = 0; } ); - queue_.assign( sources_.vec.begin(), sources_.vec.end() ); + queue_.assign( seeds_[Left].vec.begin(), seeds_[Left].vec.end() ); aMax_ = dMax_ = 0; for ( size_t i = 0; i < queue_.size(); ++i ) {