ADS
Algorithms and Data Structures
Loading...
Searching...
No Matches
Reoptimization.h
Go to the documentation of this file.
1/*--------------------------------------------------------------------------*/
2/*------------------------- File Reoptimization.h --------------------------*/
3/*--------------------------------------------------------------------------*/
105/*--------------------------------------------------------------------------*/
106/*----------------------------- DEFINITIONS --------------------------------*/
107/*--------------------------------------------------------------------------*/
108
109#ifndef __ADS_Reoptimization
110 #define __ADS_Reoptimization
111/* self-identification: #endif constant */
112
113/*--------------------------------------------------------------------------*/
114/*------------------------------ INCLUDES ----------------------------------*/
115/*--------------------------------------------------------------------------*/
116
117#include "ADS/Contract.h"
118#include "ADS/graph/Assignment.h"
119#include "ADS/graph/Graph.h"
120#include "ADS/graph/MaxFlow.h"
122#include "ADS/graph/Observable.h"
124#include "ADS/tree/LinkCutTree.h"
125
126#include <concepts>
127#include <cstddef>
128#include <cstdint>
129#include <optional>
130#include <set>
131#include <span>
132#include <type_traits>
133#include <unordered_map>
134#include <utility>
135#include <vector>
136
137/*--------------------------------------------------------------------------*/
138/*--------------------------- NAMESPACE ------------------------------------*/
139/*--------------------------------------------------------------------------*/
140
141namespace ADS
142{
143
144/*--------------------------------------------------------------------------*/
145/*-------------------------------- CONCEPTS --------------------------------*/
146/*--------------------------------------------------------------------------*/
147
149template< class R , class W >
151 GraphObserver< R , W > && requires( R & r , const GraphEvent< W > & e ,
152 std::span< const GraphEvent< W > > s )
153{
154 r.apply( e );
155 r.apply( s );
156 r.solve();
157 { r.outcome() } -> std::convertible_to< int >;
158 };
159
160/*--------------------------------------------------------------------------*/
161/*--------------------------- CLASS EventQueue -----------------------------*/
162/*--------------------------------------------------------------------------*/
163
189template< class W , ReoptPolicy P = RatioPolicy >
191{
192
193/*--------------------------------------------------------------------------*/
194 public:
196 using Policy = P;
197
199 [[nodiscard]] static constexpr unsigned mask( void ) {
200 return( GraphEvents::ALL );
201 }
202
204 void apply( const Event & e ) {
205 if( ! f_stale )
206 f_q.push_back( e );
207 }
208
210 void apply( std::span< const Event > s ) {
211 if( ! f_stale )
212 f_q.insert( f_q.end() , s.begin() , s.end() );
213 }
214
216 void notify( const Event & e ) { apply( e ); }
218 void notify( std::span< const Event > s ) { apply( s ); }
219
222 void on( const mod::Rebuilt & ) noexcept {
223 f_q.clear();
224 f_stale = true;
225 }
226
228 [[nodiscard]] std::size_t pending( void ) const { return( f_q.size() ); }
229
232 [[nodiscard]] int outcome( void ) const { return( f_outcome ); }
233
235 [[nodiscard]] int cause( void ) const { return( f_cause ); }
236
238 [[nodiscard]] long long count( int outcome ) const {
239 return( f_count[ outcome ] );
240 }
241
244 [[nodiscard]] long long byCause( int c ) const {
245 ADS_PRE( ( c > 0 ) && ( c < Reopt::CAUSES ) );
246 return( f_byCause[ c ] );
247 }
248
250 [[nodiscard]] P & policy( void ) { return( f_policy ); }
252 [[nodiscard]] const P & policy( void ) const { return( f_policy ); }
253
257 void setRecomputeRatio( double ratio )
258 requires requires( P & p ) { p.rho = 0.0; }
259 {
260 ADS_PRE( ratio >= 0 );
261 f_policy.rho = ratio;
262 }
263
264/*--------------------------------------------------------------------------*/
265 protected:
267 std::vector< Event > take( void ) {
268 std::vector< Event > E = coalesce< W >( std::span< const Event >( f_q ) );
269 f_q.clear();
270 return( E );
271 }
272
274 [[nodiscard]] static ReoptStats stats( std::size_t k , long long m ) {
275 ReoptStats s;
276 s.events = k;
277 s.size = std::size_t( m > 0 ? m : 0 );
278 return( s );
279 }
280
283 [[nodiscard]] bool tooMany( std::size_t k , long long m ) {
284 return( bool( f_policy.scratch( stats( k , m ) ) ) );
285 }
286
289 [[nodiscard]] bool fresh( bool ready ) {
290 if( ready && ! f_stale )
291 return( false );
292 f_q.clear();
293 f_stale = false;
294 return( true );
295 }
296
298 void tally( int cause ) {
299 f_cause = cause;
301 ++f_count[ f_outcome ];
302 ++f_byCause[ cause ];
303 }
304
307 void done( int cause , double w ) {
308 tally( cause );
309 f_policy.record( cause , w );
310 }
311
312 std::vector< Event > f_q;
314 bool f_stale = false;
317 long long f_count[ 3 ] = { 0 , 0 , 0 };
318 long long f_byCause[ Reopt::CAUSES ] = {};
319
320 }; // end( class EventQueue )
321
322/*--------------------------------------------------------------------------*/
323/*---------------------- CLASS ShortestPathsObserver -----------------------*/
324/*--------------------------------------------------------------------------*/
325
328template< Graph G , ReoptPolicy P = RatioPolicy >
329class ShortestPathsObserver : public EventQueue< typename G::Weight , P >
330{
331
332/*--------------------------------------------------------------------------*/
333 public:
334 using Weight = typename G::Weight;
335
339 ShortestPathsObserver( const G & g , int r , Frontier how = Frontier::HEAP );
340
387 void solve( void );
388
391 [[nodiscard]] const ShortestPathTree< Weight > & tree( void ) {
392 solve();
393 return( f_R );
394 }
395
397 [[nodiscard]] Weight distance( int v ) {
398 solve();
399 return( f_R.d[ v ] );
400 }
401
404 [[nodiscard]] ReoptStats reoptStats( std::size_t k ) const;
405
406/*--------------------------------------------------------------------------*/
407 private:
408 using B = EventQueue< Weight , P >;
409
411 void scratch( Frontier how );
412
413 using Event = GraphEvent< Weight >;
414
419 int repair( std::vector< int > & S , ReoptStats & s );
420
421 static constexpr int REPAIRED = 0;
422 static constexpr int CYCLE = 1;
423 static constexpr int ABANDONED = 2;
424
426 void buildTree( void );
427
429 void grow( void );
430
432 void link( int x , int p );
433
435 void unlink( int x );
436
438 void setParent( int v , int u );
439
441 void buildIn( void );
442
444 void applyIn( std::span< const Event > C );
445
447 template< class F >
448 void forEachIn( int x , F && f ) const;
449
450 const G & f_g;
451 int f_r;
452 Frontier f_how;
453 bool f_ready = false;
455 std::vector< int > f_child;
456 std::vector< int > f_next;
457 std::vector< int > f_prev;
458 std::vector< int > f_pops;
459 std::vector< char > f_inA;
460 bool f_inOk = false;
463 std::vector< std::vector< std::pair< int , Weight > > > f_in;
464
465 }; // end( class ShortestPathsObserver )
466
467/*--------------------------------------------------------------------------*/
468/*---------------------- CLASS SpanningForestObserver ----------------------*/
469/*--------------------------------------------------------------------------*/
470
473template< Graph G , ReoptPolicy P = RatioPolicy >
474class SpanningForestObserver : public EventQueue< typename G::Weight , P >
475{
476
477/*--------------------------------------------------------------------------*/
478 public:
479 using Weight = typename G::Weight;
480
484 explicit SpanningForestObserver( const G & g );
485
525 void solve( void );
526
528 [[nodiscard]] std::vector< WeightedEdge< Weight > > forest( void );
529
535 [[nodiscard]] Weight weight( void );
536
538 [[nodiscard]] bool inForest( int u , int v );
539
542 [[nodiscard]] ReoptStats reoptStats( std::size_t k ) const;
543
544/*--------------------------------------------------------------------------*/
545 private:
546 using B = EventQueue< Weight , P >;
547 using Event = GraphEvent< Weight >;
548
551 struct Rec
552 {
553 Weight w;
554 int node = NIL;
555 int at = -1;
556 bool held = false;
558 };
559
562 struct Heavy
563 {
564 bool has = false;
565 Weight w = Weight();
566 int node = NIL;
568 bool operator==( const Heavy & h ) const {
569 return( ( has == h.has ) && ( node == h.node ) );
570 }
571 };
572
574 struct Heavier
575 {
578 Heavy operator()( const Heavy & a , const Heavy & b ) const {
579 if( ! a.has )
580 return( b );
581 if( ! b.has )
582 return( a );
583 if( a.w < b.w )
584 return( b );
585 if( b.w < a.w )
586 return( a );
587 return( a.node < b.node ? b : a );
588 }
589 };
590
592 static std::uint64_t key( int u , int v ) {
593 if( v < u )
594 std::swap( u , v );
595 return( ( std::uint64_t( std::uint32_t( u ) ) << 32 ) |
596 std::uint32_t( v ) );
597 }
598
600 static std::pair< int , int > ends( std::uint64_t k ) {
601 return( std::pair< int , int >( int( k >> 32 ) , int( k & 0xffffffffu ) ) );
602 }
603
605 void scratch( bool fromGraph );
606
608 void grow( int n );
609
611 void addTree( std::uint64_t k );
612
614 void removeTree( std::uint64_t k );
615
640 bool replacement( int u , int v , std::uint64_t & best );
641
658 void join( void );
659
660 const G & f_g;
661 bool f_ready = false;
663 int f_n = 0;
664 std::unordered_map< std::uint64_t , Rec > f_E;
668 struct Inc
669 {
670 int y;
671 bool held;
672 Weight w;
673 };
674
676 Inc & inc( int a , int b );
677
678 std::vector< std::vector< Inc > > f_inc;
680 std::vector< std::vector< int > > f_adjF;
681 std::vector< std::uint64_t > f_F;
682 LinkCutTree< Heavy , Heavier > f_lct;
684 std::vector< int > f_vid;
686 std::vector< std::uint64_t > f_edgeOf;
688 std::vector< int > f_free;
690 std::vector< int > f_mark;
693 std::set< std::pair< Weight , std::uint64_t > > f_off;
695 static constexpr bool SUBTRACT = requires( Weight a , Weight b ) {
696 { a - b } -> std::convertible_to< Weight >;
697 };
698 double f_replAvg = 0;
700 double f_steps = 0;
702 NeumaierSum< Weight > f_total;
704 std::size_t f_changes = 0;
706 int f_stamp = 0;
707
710 void refreshTotal( std::size_t changes );
711
713 [[nodiscard]] bool compensated( void ) const;
714
717 [[nodiscard]] bool totalHolds( void ) const;
718
719 }; // end( class SpanningForestObserver )
720
721/*--------------------------------------------------------------------------*/
722/*------------------------- CLASS MaxFlowObserver --------------------------*/
723/*--------------------------------------------------------------------------*/
724
736template< class E >
737concept FlowEngine = std::default_initializable< E > &&
738 requires( E & x , FlowNetwork & net , int s , int t ,
739 Augment how , long long v )
740{
741 {
742 x.scratch( net , s , t , how )
743 } -> std::convertible_to< long long >;
744 {
745 x.warm( net , s , t , how , v )
746 } -> std::convertible_to< long long >;
747 };
748
752{
754 static long long scratch( FlowNetwork & net , int s , int t , Augment how ) {
755 return( net.maxFlow( s , t , how ) );
756 }
757
758 static long long warm( FlowNetwork & net , int s , int t , Augment how ,
759 long long v ) {
760 return( v + net.maxFlow( s , t , how ) );
761 }
762 };
763
767template< Graph G , ReoptPolicy P = RatioPolicy ,
768 FlowEngine E = AugmentEngine >
769 requires std::is_integral_v< typename G::Weight >
770class MaxFlowObserver : public EventQueue< typename G::Weight , P >
771{
772
773/*--------------------------------------------------------------------------*/
774 public:
775 using Weight = typename G::Weight;
776
780 MaxFlowObserver( const G & g , int s , int t , Augment how = Augment::DINIC );
781
806 void solve( void );
807
809 [[nodiscard]] long long value( void ) {
810 solve();
811 return( f_value );
812 }
813
815 [[nodiscard]] const std::vector< bool > & minCut( void ) {
816 solve();
817 return( f_S );
818 }
819
822 [[nodiscard]] ReoptStats reoptStats( std::size_t k ) const;
823
824/*--------------------------------------------------------------------------*/
825 private:
826 using B = EventQueue< Weight , P >;
827
829 static std::uint64_t key( int u , int v ) {
830 return( ( std::uint64_t( std::uint32_t( u ) ) << 32 ) |
831 std::uint32_t( v ) );
832 }
833
835 void scratch( void );
836
838 [[nodiscard]] long long cutCapacity( void ) const;
839
840 const G & f_g;
841 int f_s;
842 int f_t;
843 Augment f_how;
844 bool f_ready = false;
845 FlowNetwork f_net{ 0 };
846 E f_engine;
848 std::unordered_map< std::uint64_t , int > f_arc;
849 long long f_value = 0;
850 std::vector< bool > f_S;
851
852 }; // end( class MaxFlowObserver )
853
854/*--------------------------------------------------------------------------*/
855/*------------------------ CLASS AssignmentObserver ------------------------*/
856/*--------------------------------------------------------------------------*/
857
862template< Graph G , ReoptPolicy P = RatioPolicy >
863 requires std::is_arithmetic_v< typename G::Weight >
864class AssignmentObserver : public EventQueue< typename G::Weight , P >
865{
866
867/*--------------------------------------------------------------------------*/
868 public:
869 using Weight = typename G::Weight;
870
876 AssignmentObserver( const G & g , int k );
877
893 void solve( void );
894
896 [[nodiscard]] Assignment< Weight > & assignment( void ) {
897 solve();
898 return( f_A );
899 }
900
904 [[nodiscard]] int partner( int i ) {
905 solve();
906 const int j = f_A.column( i );
907 return( j < 0 ? -1 : f_k + j );
908 }
909
911 [[nodiscard]] Weight total( void ) {
912 solve();
913 return( f_A.total() );
914 }
915
918 [[nodiscard]] P & policy( void ) { return( f_A.policy() ); }
920 [[nodiscard]] const P & policy( void ) const { return( f_A.policy() ); }
921
924 [[nodiscard]] ReoptStats reoptStats( std::size_t k ) const;
925
926/*--------------------------------------------------------------------------*/
927 private:
928 using B = EventQueue< Weight , P >;
929
931 ADS_COLD_PATH void reload( void );
932
933 const G & f_g;
934 int f_k;
936
937 }; // end( class AssignmentObserver )
938
939/*--------------------------------------------------------------------------*/
940
941} // end( namespace ADS )
942
943/*--------------------------------------------------------------------------*/
944/*-------------------------- IMPLEMENTATION --------------------------------*/
945/*--------------------------------------------------------------------------*/
946
947#include "ADS/graph/impl/Reoptimization.tpp"
948
949/*--------------------------------------------------------------------------*/
950
951#endif /* Reoptimization.h included */
952
953/*--------------------------------------------------------------------------*/
954/*----------------------- End File Reoptimization.h ------------------------*/
955/*--------------------------------------------------------------------------*/
The assignment problem, beyond the book: given the costs of rows and columns (the workers and the ...
The contracts of ADS: the preconditions, the postconditions and the invariants of the operations,...
The link-cut trees of Sleator and Tarjan, beyond the book: a forest of rooted trees on the nodes tha...
The maximum flow of section 15.2 in a network , with integer capacities, and the minimum cut.
The minimum spanning tree of an unoriented connected graph with weights on the edges (section 14....
A GRAPH that tells its changes, beyond the book: the wrapper Observable< G , O... > routes the change...
The shortest paths of chapter 11 from a node of an oriented GRAPH whose edges have a cost [see Grap...
Weight total(void)
the total cost of the assignment
Definition Reoptimization.h:911
typename G::Weight Weight
the type of the weights
Definition Reoptimization.h:869
const P & policy(void) const
the recompute policy
Definition Reoptimization.h:920
AssignmentObserver(const G &g, int k)
the assignment of the rows of , computed at the first query; a pair with no edge is forbidden
P & policy(void)
the recompute policy, that of the Assignment, which weighs the events only through the rows and the c...
Definition Reoptimization.h:918
Assignment< Weight > & assignment(void)
the assignment, up to date
Definition Reoptimization.h:896
void solve(void)
brings the assignment up to date
int partner(int i)
the column, in , of the row , if none
Definition Reoptimization.h:904
ReoptStats reoptStats(std::size_t k) const
the statistics of a query after more events, for the policy: the events queued and the costs
an assignment of least cost of rows to columns, kept optimal after the changes of the costs,...
Definition Assignment.h:151
the queue of the events, the recompute policy P [see ReoptPolicy] and the counts that the observers s...
Definition Reoptimization.h:191
int f_outcome
Definition Reoptimization.h:315
void setRecomputeRatio(double ratio)
from scratch when the events coalesced exceed times the edges: of the policy
Definition Reoptimization.h:257
GraphEvent< W > Event
the type of the events
Definition Reoptimization.h:195
int outcome(void) const
how the last solve() with events to apply, or with no solution yet, did it [see Reopt]
Definition Reoptimization.h:232
long long byCause(int c) const
the solves of each cause so far
Definition Reoptimization.h:244
int cause(void) const
why: the cause of the last outcome [see Reopt]
Definition Reoptimization.h:235
P f_policy
Definition Reoptimization.h:313
void apply(std::span< const Event > s)
queues the events of , unless Rebuilt came
Definition Reoptimization.h:210
bool f_stale
Definition Reoptimization.h:314
void notify(const Event &e)
apply( e ), for the Observable
Definition Reoptimization.h:216
const P & policy(void) const
the recompute policy
Definition Reoptimization.h:252
void notify(std::span< const Event > s)
apply( s ), for the Observable
Definition Reoptimization.h:218
long long count(int outcome) const
the solves of each outcome so far
Definition Reoptimization.h:238
void done(int cause, double w)
the cause of a solve() counted and told to the policy with the work
Definition Reoptimization.h:307
static constexpr unsigned mask(void)
all the kinds of event
Definition Reoptimization.h:199
bool tooMany(std::size_t k, long long m)
whether the policy wants events on edges from scratch
Definition Reoptimization.h:283
std::vector< Event > take(void)
the queue coalesced, emptied
Definition Reoptimization.h:267
long long f_count[3]
Definition Reoptimization.h:317
static ReoptStats stats(std::size_t k, long long m)
the statistics of events on edges
Definition Reoptimization.h:274
void tally(int cause)
the cause of a solve() counted, not told to the policy
Definition Reoptimization.h:298
long long f_byCause[Reopt::CAUSES]
Definition Reoptimization.h:318
int f_cause
Definition Reoptimization.h:316
void on(const mod::Rebuilt &) noexcept
forgets the queue, and takes no event until the next query, which computes the solution from scratch
Definition Reoptimization.h:222
void apply(const Event &e)
queues , unless Rebuilt came since the last query
Definition Reoptimization.h:204
bool fresh(bool ready)
whether a solve from scratch is due before any event: no solution yet, or Rebuilt; the queue then emp...
Definition Reoptimization.h:289
P Policy
the type of the policy
Definition Reoptimization.h:196
std::vector< Event > f_q
Definition Reoptimization.h:312
P & policy(void)
the recompute policy
Definition Reoptimization.h:250
std::size_t pending(void) const
the events waiting for the next query
Definition Reoptimization.h:228
a network of flow with integer capacities
Definition MaxFlow.h:126
long long maxFlow(int s, int t, Augment how=Augment::DINIC, long long *paths=nullptr)
the maximum flow from to , starting from the flow there is, after the excesses and the deficits left...
void solve(void)
brings the flow up to date
const std::vector< bool > & minCut(void)
the side of of a minimum cut
Definition Reoptimization.h:815
long long value(void)
the value of the maximum flow
Definition Reoptimization.h:809
MaxFlowObserver(const G &g, int s, int t, Augment how=Augment::DINIC)
the flow from to in , computed by how at the first query
ReoptStats reoptStats(std::size_t k) const
the statistics of a query after more events, for the policy: the events queued and the edges
typename G::Weight Weight
the type of the weights
Definition Reoptimization.h:775
Weight distance(int v)
the distance of , infinity() if not reachable
Definition Reoptimization.h:397
void solve(void)
brings the tree up to date
const ShortestPathTree< Weight > & tree(void)
the tree, up to date; its order is that of the last computation from scratch
Definition Reoptimization.h:391
ReoptStats reoptStats(std::size_t k) const
the statistics of a query after more events, for the policy: the events queued and the edges
ShortestPathsObserver(const G &g, int r, Frontier how=Frontier::HEAP)
the shortest paths from in , computed by how at the first query
typename G::Weight Weight
the type of the weights
Definition Reoptimization.h:334
SpanningForestObserver(const G &g)
the forest of , computed by Kruskal at the first query; if the policy is a RatioPolicy
void solve(void)
brings the forest up to date
bool inForest(int u, int v)
whether is in the forest
Weight weight(void)
the total weight of the forest, kept as it changes when the weights subtract, after the query,...
typename G::Weight Weight
the type of the weights
Definition Reoptimization.h:479
ReoptStats reoptStats(std::size_t k) const
the statistics of a query after more events, for the policy: the events queued and the edges
std::vector< WeightedEdge< Weight > > forest(void)
the edges of the forest, up to date, in no given order
the engines of the solves of a MaxFlowObserver, objects that the observer keeps: scratch( net ,...
Definition Reoptimization.h:737
an observer of the events of weights W: the kinds that it wants, and the two ways of getting them
Definition Observable.h:298
a solution that follows the events of weights W
Definition Reoptimization.h:150
The GRAPH of chapter 9 and its realizations.
#define ADS_PRE(cond)
[check]
Definition Contract.h:121
#define ADS_COLD_PATH
a function of a rare path: never inlined, laid out away from the hot code
Definition Portable.h:107
Augment
the way of increasing the flow
Definition MaxFlow.h:113
@ DINIC
a blocking flow on the levels of a visit in breadth
Definition MaxFlow.h:116
std::variant< NodeInserted, NodeDeleted, EdgeInserted< W >, EdgeDeleted< W >, WeightChanged< W > > GraphEvent
an event, whose kind is its index in the variant, the variant of GraphModifications< W >
Definition Observable.h:237
std::vector< GraphEvent< W > > coalesce(std::span< const GraphEvent< W > > E)
the net effect of the events , i.e., the nodes inserted, the edges in the order of their first event ...
Frontier
the structure of the prototype
Definition ShortestPaths.h:135
@ HEAP
a priority queue on a binary heap: Johnson
Definition ShortestPaths.h:137
constexpr int NIL
no node
Definition Visit.h:128
Definition ADT.h:96
the engine of ADS, both solves by the augmentations how of FlowNetwork::maxFlow() [see MaxFlow....
Definition Reoptimization.h:752
static long long warm(FlowNetwork &net, int s, int t, Augment how, long long v)
the value of a maximum flow from the flow of net, of value
Definition Reoptimization.h:758
static long long scratch(FlowNetwork &net, int s, int t, Augment how)
the value of a maximum flow from the zero flow
Definition Reoptimization.h:754
static constexpr unsigned ALL
all of them
Definition Observable.h:250
what a recompute policy reads: the work is a count of elementary operations of the observer (nodes,...
Definition Modification.h:208
std::size_t events
the net events to apply
Definition Modification.h:209
std::size_t size
the size of the instance
Definition Modification.h:210
static constexpr int outcomeOf(int c)
the outcome of the cause
Definition Modification.h:199
static constexpr int SCRATCH_BY_EVENT
from scratch, Rebuilt,
Definition Modification.h:191
static constexpr int SCRATCH
from scratch
Definition Modification.h:184
static constexpr int CAUSES
the number of the causes
Definition Modification.h:196
anything may have changed: forget and recompute
Definition Modification.h:708