diff --git a/source/MRMesh/MRFillContourByGraphCut.cpp b/source/MRMesh/MRFillContourByGraphCut.cpp index 1d321ef26aaf..2d5748f6c9d7 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; // residual capacity of this dual edge + 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 ) {} }; @@ -49,6 +49,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: @@ -67,6 +80,21 @@ 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 + + // 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; } @@ -92,6 +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; + + // 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 ) @@ -166,7 +209,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 ) { @@ -174,26 +221,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; } @@ -213,7 +262,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 ) @@ -221,7 +270,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 ); } } } @@ -230,9 +279,23 @@ 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() ); + } + + // 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 ) + return pushRelabel_( progress, numCycles ); + auto lf = active_[Left].front(); active_[Left].pop_front(); processActive_( lf, Left ); @@ -273,7 +336,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 ) @@ -380,6 +443,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, Left ); f = parent; @@ -392,6 +456,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; @@ -409,6 +474,7 @@ void GraphCut::adapt_( int side ) { auto f = orphans_.back(); orphans_.pop_back(); + ++work_; if ( !isSide_( f, side ) ) continue; assert( !parentSlot_( f ) ); @@ -459,7 +525,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 ) @@ -498,6 +564,294 @@ 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_ = {}; + + // 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 ); + 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 = 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 = state_[f] == Left + 1 ? 0 : n_; + cur_[f] = 0; + } ); + queue_.assign( seeds_[Left].vec.begin(), seeds_[Left].vec.end() ); + 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