Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
Negative_Cycles.H File Reference

Enumeration of negative cycles and bounded-length most negative cycle in directed graphs. More...

#include <ah-graph-concepts.H>
#include <algorithm>
#include <bit>
#include <cfloat>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <type_traits>
#include <utility>
#include <ah-errors.H>
#include <htlist.H>
#include <shortest_path_common.H>
#include <tpl_array.H>
#include <tpl_graph.H>
Include dependency graph for Negative_Cycles.H:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Classes

struct  Aleph::Negative_Cycle_Item< GT, Cost_Type >
 One negative cycle reported by find_disjoint_negative_cycles(). More...
 
struct  Aleph::Bounded_Cycle_Result< GT, Cost_Type >
 Result of most_negative_cycle_bounded(). More...
 
struct  Aleph::Short_Cycle_Result< GT, Cost_Type >
 Exact optimum returned by most_negative_cycle_up_to_3(). More...
 
struct  Aleph::negative_cycles_detail::Arc_Rec< GT, Cost_Type >
 Snapshot of one graph arc: endpoint positions, the arc and its weight (read once from the distance accessor). More...
 
struct  Aleph::negative_cycles_detail::Indexed_Graph< GT, Cost_Type >
 Positional snapshot of a graph: nodes by position and the arcs accepted by the arc filter, in iteration order. More...
 
class  Aleph::negative_cycles_detail::Exact_Sum< T >
 Exact sum of floating-point numbers. More...
 
class  Aleph::negative_cycles_detail::Node_Index< Node >
 Map from node pointers to their positions, built once and never modified afterwards. More...
 
struct  Aleph::negative_cycles_detail::Out_Adjacency< Cost_Type >
 Out-adjacency of a snapshot in compressed form. More...
 
struct  Aleph::negative_cycles_detail::Best_Cycle< Cost_Type >
 Best simple cycle found so far by most_negative_cycle_bounded(). More...
 
struct  Aleph::negative_cycles_detail::Decomposition_Scratch
 Scratch space of offer_simple_components(), allocated once. More...
 
class  Aleph::negative_cycles_detail::Short_Cycle_Best< Cost_Type >
 Rank cycles of at most three arcs exactly, reusing scratch sums. More...
 

Namespaces

namespace  Aleph
 Main namespace for Aleph-w library functions.
 
namespace  Aleph::negative_cycles_detail
 

Typedefs

template<typename T >
using Aleph::negative_cycles_detail::exact_float_t = T
 Floating-point format in which the error-free transformations on values of T are carried out.
 

Enumerations

enum class  Aleph::Negative_Cycle_Exclusion { Aleph::Negative_Cycle_Exclusion::Min_Weight_Arc , Aleph::Negative_Cycle_Exclusion::All_Arcs }
 Which arcs of a found negative cycle are excluded before searching for the next one in find_disjoint_negative_cycles(). More...
 
enum class  Aleph::Cycle_Numeric_Quality { Aleph::Cycle_Numeric_Quality::Exact , Aleph::Cycle_Numeric_Quality::Rounded }
 How far the numbers behind the result of a cycle search can be trusted. More...
 

Functions

template<typename Cost_Type >
void Aleph::negative_cycles_detail::check_finite (const Cost_Type &value, const char *context)
 
template<typename F >
void Aleph::negative_cycles_detail::two_sum (const F a, const F b, F &s, F &e) noexcept
 Error-free sum (Knuth's TwoSum): s = fl(a + b) and s + e == a + b exactly.
 
template<typename T >
void Aleph::negative_cycles_detail::bit_span (const T x, int &low, int &high) noexcept
 Exponents of the lowest and of the highest set bit of a nonzero finite x: |x| is an odd integer times 2^low, and 2^high <= |x| < 2^(high + 1).
 
template<typename T >
std::uint64_t Aleph::negative_cycles_detail::odd_significand (const T x) noexcept
 The odd integer |x| / 2^low, with low the exponent of the lowest set bit of the nonzero finite x (see bit_span()).
 
template<AlephGraph GT, typename Cost_Type >
Cost_Type Aleph::negative_cycles_detail::cycle_cost (const Indexed_Graph< GT, Cost_Type > &ig, const Array< size_t > &arcs, const char *context)
 Total cost of the arcs arcs (indices into ig.arcs).
 
template<AlephGraph GT, typename Cost_Type >
bool Aleph::negative_cycles_detail::short_sums_are_exact (const Indexed_Graph< GT, Cost_Type > &ig, const size_t L, Cost_Type &error_bound)
 Rounding behaviour of the sums of at most L weights of ig, added left to right in a floating-point Cost_Type.
 
template<AlephGraph GT, ArcDistance< GT > Distance, ArcFilter< GT > SA>
Indexed_Graph< GT, typename Distance::Distance_Type > Aleph::negative_cycles_detail::index_graph (const GT &g, Distance &distance, SA &sa, const char *fn)
 Snapshot the graph: index its nodes and the arcs accepted by sa, reading each weight once.
 
template<AlephGraph GT, typename Cost_Type >
long Aleph::negative_cycles_detail::find_predecessor_cycle (const Indexed_Graph< GT, Cost_Type > &ig, const Array< long > &pred, Array< long > &mark)
 Scan the predecessor graph for a cycle.
 
template<AlephGraph GT, typename Cost_Type >
Out_Adjacency< Cost_Type > Aleph::negative_cycles_detail::build_out_adjacency (const Indexed_Graph< GT, Cost_Type > &ig)
 Build the out-adjacency of ig by a counting sort, O(V + E).
 
template<AlephGraph GT, typename Cost_Type >
bool Aleph::negative_cycles_detail::cyclic_core (const Indexed_Graph< GT, Cost_Type > &ig, const Out_Adjacency< Cost_Type > &adj, Indexed_Graph< GT, Cost_Type > &core)
 Cyclic core of a snapshot: the nodes and arcs that lie inside a strongly connected component with at least one arc.
 
template<AlephGraph GT, ArcDistance< GT > Distance = Dft_Dist<GT>, ArcFilter< GT > SA = Dft_Show_Arc<GT>>
DynList< Negative_Cycle_Item< GT, typename Distance::Distance_Type > > Aleph::find_disjoint_negative_cycles (const GT &g, const size_t max_cycles, const Negative_Cycle_Exclusion exclusion=Negative_Cycle_Exclusion::Min_Weight_Arc, Distance distance=Distance(), SA sa=SA())
 Find up to max_cycles negative cycles, excluding arcs of each cycle found before searching for the next one.
 
template<AlephGraph GT, typename Cost_Type >
void Aleph::negative_cycles_detail::offer_simple_components (const Indexed_Graph< GT, Cost_Type > &ig, const Array< size_t > &walk, Array< long > &pos, Decomposition_Scratch &scratch, Best_Cycle< Cost_Type > &best)
 Decompose the closed walk walk (arc indices, in order, starting and ending at the same node) into simple cycles and offer each one to best.
 
template<AlephGraph GT, ArcDistance< GT > Distance = Dft_Dist<GT>, ArcFilter< GT > SA = Dft_Show_Arc<GT>>
Bounded_Cycle_Result< GT, typename Distance::Distance_Type > Aleph::most_negative_cycle_bounded (const GT &g, const size_t max_length, Distance distance=Distance(), SA sa=SA())
 Most negative simple cycle of at most max_length arcs, ranked by total cost (not by mean cost as Karp's algorithm does).
 
template<AlephGraph GT, typename Cost_Type >
Out_Adjacency< Cost_Type > Aleph::negative_cycles_detail::cheapest_parallel_arcs (const Indexed_Graph< GT, Cost_Type > &ig, const Out_Adjacency< Cost_Type > &adj)
 Keep the cheapest parallel arc of each ordered pair.
 
template<AlephGraph GT, ArcDistance< GT > Distance = Dft_Dist<GT>, ArcFilter< GT > SA = Dft_Show_Arc<GT>>
Short_Cycle_Result< GT, typename Distance::Distance_Type > Aleph::most_negative_cycle_up_to_3 (const GT &g, const size_t max_length=3, Distance distance=Distance(), SA sa=SA())
 Minimum-total-cost simple cycle with at most one, two or three arcs.
 

Detailed Description

Enumeration of negative cycles and bounded-length most negative cycle in directed graphs.

Algorithms aimed at applications, such as currency or crypto arbitrage detection, where a negative cycle in a graph weighted with -log(rate) is an opportunity, and where one negative cycle is not enough: a trading engine wants several disjoint opportunities at once, ranked by the total profit of executing each one once, and only up to a small number of hops.

  • find_disjoint_negative_cycles(): repeatedly runs Bellman-Ford from a virtual source (every node at distance zero), scanning the predecessor graph for a cycle after every pass (any such cycle is negative), so a certificate is usually found after a few passes; it then extracts the cycle, excludes some of its arcs and runs again, until max_cycles cycles are found or no negative cycle is left.
  • most_negative_cycle_bounded(): for every node as origin, runs a relaxation bounded to max_length steps to find the closed walks of minimum total cost, decomposes them into simple cycles and returns the most negative simple cycle of at most max_length arcs. It runs only on the nodes and arcs that lie inside a strongly connected component.
  • most_negative_cycle_up_to_3(): independently enumerates self-loops, opposite arc pairs and directed triangles, returning the exact minimum total cost within a bound in [0, 3], with the shortest cycle on ties.

Unlike Bellman_Ford (Bellman_Ford.H), none modifies the graph (no dummy node, no cookies, no bits) and all take a const GT &; they keep their state in private arrays indexed by node/arc position. The graph is snapshotted once (arcs, endpoints and weights), so the distance accessor is called exactly once per accepted arc.

Complexity

The functions first snapshot the graph in expected O(V + E) time (nodes are mapped to positions with an open-addressing hash table at most half full, mixing the pointers so that allocation patterns cannot cluster; only a degenerate hash could make a lookup cost more than O(1)), then work on arrays. E counts every arc the arc iterator visits, which includes the arcs rejected by the filter. Working space excludes the cycles that are returned (up to O(K · V) for K of them). The number of memory allocations does not depend on E, on the bound L or on the length of the walks examined: only the cycles that are returned allocate per cycle.

Function Time Working space
find_disjoint_negative_cycles O(V + E + R · V · (V + E)) O(V + E)
most_negative_cycle_bounded O(V + E + V_c · L · (V_c + E_c) + V_c · L²) O(L · V_c + V + E)
most_negative_cycle_up_to_3 O(V + E + sum_v d_in(v) · d_out(v)) O(V + E)

For the short-cycle search, degrees count distinct neighbours in the cyclic core; the degree-product term is absent for bounds 1 and 2.

R is the number of searches (rounds) the enumeration runs: at most max_cycles + 1 unless floating-point candidates are discarded without being reported, and never more than E + 1. L = min(max_length, V). V_c and E_c are the nodes and arcs of the cyclic core: those inside a strongly connected component that has an arc (V_c <= V, E_c <= E). A graph without cycles costs just the snapshot and an O(V + E) scan. The V_c · L² term is the reconstruction of the closed walks: it disappears into the previous one when L <= V_c + E_c, but L is bounded by the nodes of the whole graph, not of the core, so a small core searched with a large bound pays it (see most_negative_cycle_bounded()). The usual O(V · L · E) form holds when E_c >= V_c and L <= E_c.

Numeric model

The searches accumulate costs with the + and < of Distance::Distance_Type, in the order the algorithm happens to add them. For integer costs that is exact arithmetic (an overflow throws std::overflow_error), and every statement below about "negative", "minimum" and is_exact is a mathematical one. For floating-point costs the searches round, and the results say how far they can be trusted, for the weights exactly as given (as binary fractions):

  • The cost reported for a cycle is the exact sum of its weights, rounded within one ulp (see negative_cycles_detail::Exact_Sum, an expansion in the sense of Shewchuk, 1997). Its sign is exact, so a cycle is reported as negative only if it is, and a cycle whose exact total is zero (such as 2^100, 1, 2^-100, -1, -2^100, -2^-100) costs zero.
  • The exact sums hold any finite weights while the values stay in the range of the type: a cycle whose total, or a partial sum in cycle order, leaves it throws std::domain_error (most_negative_cycle_up_to_3() orders its three terms so that only the total matters, and skips candidates above the range). A value within one unit in the last place of the largest finite number may count as out of range too; none is ever computed wrongly.
  • find_disjoint_negative_cycles() reports only cycles whose exact total is negative. Its search, though, can miss one: a huge partial distance can absorb a small negative weight (-1e16 + (-1) rounds to -1e16) and hide the cycle, so with floating-point costs an empty result means that no negative cycle was detected, not that none exists.
  • most_negative_cycle_bounded() ranks the candidate cycles by their exact costs, and publishes optimality_gap: a rigorous bound of how much cheaper than the reported cycle the best one can be, which covers the rounding of every sum the search made. is_exact holds exactly when that bound is zero, for instance when the range of the weights makes every sum of the search exact (numeric_quality is Exact).
  • most_negative_cycle_up_to_3() always selects the exact optimum among simple cycles within its bound. It enumerates all candidates after collapsing parallel arcs to their cheapest representative, and uses exact expansions whenever a rigorous rounding filter cannot order them.
  • howard_minimum_mean_cycle() (Howard_Min_Mean_Cycle.H) checks its rounded result with exact arithmetic when it can; its numeric_quality says whether it could.

Applications that need a safety margin should fold it into the distance accessor (for instance by adding a minimum profit to every weight): it is a business decision, separate from these numeric guarantees. The exact arithmetic needs IEEE round-to-nearest evaluated as written: no -ffast-math or other reassociation of floating-point sums.

Lifetime and concurrency

The returned paths and node/arc lists hold pointers into the graph g: they are valid only while those nodes and arcs are. Several threads may run these functions on the same graph if nobody modifies it meanwhile and the distance accessor and the arc filter are safe to call concurrently; taking const GT & does not make a concurrent modification safe.

See also
Bellman_Ford.H One negative cycle, with the SPFA variant.
Min_Mean_Cycle.H Cycle of minimum mean weight (Karp).
Author
Leandro Rabindranath León

Definition in file Negative_Cycles.H.