Upload
others
View
4
Download
0
Embed Size (px)
Citation preview
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 1/48
The Boost Graph LibraryGeneric Library Design
Werner Trobin<[email protected]>
Introduction
The Boost Graph Library
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 2/48
Outline
n Introduction to Boostn The Boost Graph Libraryn Demon References
Introductionl Introducing Boostl Licensel Available Librariesl Available Libraries (2)l Supported Compilersl Design and Programmingl Implementation Variationl Test Policies
The Boost Graph Library
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 3/48
Introducing Boost
n Collection of portable C++ source libraries[1]n Quality assurance by peer-reviewingn Designed to work well with the C++ Standard Libraryn Wide spectrum of different libraries, not targeting a single
domainn Free
n Goalsu Establish “existing practice”u Provide reference implementations suitable for
standardization
Introductionl Introducing Boostl Licensel Available Librariesl Available Libraries (2)l Supported Compilersl Design and Programmingl Implementation Variationl Test Policies
The Boost Graph Library
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 3/48
Introducing Boost
n Collection of portable C++ source libraries[1]n Quality assurance by peer-reviewingn Designed to work well with the C++ Standard Libraryn Wide spectrum of different libraries, not targeting a single
domainn Freen Goals
u Establish “existing practice”u Provide reference implementations suitable for
standardization
Introductionl Introducing Boostl Licensel Available Librariesl Available Libraries (2)l Supported Compilersl Design and Programmingl Implementation Variationl Test Policies
The Boost Graph Library
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 4/48
License
n License Requirementsu Must be simple to read and understand.u Must grant permission without fee to copy, use and modify
the software for any use (commercial andnon-commercial).
u Must require that the license appear with all copies[including redistributions] of the software source code.
u Must not require that the license appear with executablesor other binary uses of the library.
u Must not require that the source code be available forexecution or other binary uses of the library.
n Boost Software License[2] similar to BSD license
Introductionl Introducing Boostl Licensel Available Librariesl Available Libraries (2)l Supported Compilersl Design and Programmingl Implementation Variationl Test Policies
The Boost Graph Library
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 4/48
License
n License Requirementsu Must be simple to read and understand.u Must grant permission without fee to copy, use and modify
the software for any use (commercial andnon-commercial).
u Must require that the license appear with all copies[including redistributions] of the software source code.
u Must not require that the license appear with executablesor other binary uses of the library.
u Must not require that the source code be available forexecution or other binary uses of the library.
n Boost Software License[2] similar to BSD license
Introductionl Introducing Boostl Licensel Available Librariesl Available Libraries (2)l Supported Compilersl Design and Programmingl Implementation Variationl Test Policies
The Boost Graph Library
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 5/48
Available Libraries
n String and text processing:conversion/lexical_cast, format, regex, spirit, tokenizer
n Containers:array, dynamic_bitset, graph, multi_array, propertymap, variant
n Iterators:graph, iterators, operators, tokenizer
n Algorithms:graph, utility
n Function objects andhigher-order programming:bind and mem_fn, function, functional, lambda, ref,signals
n Generic Programming:call_traits, concept check, enable_if, operators,property map, static_assert, type_traits
n Template Metaprogramming:mpl, static_assert, type_traits
n PreprocessorMetaprogramming:preprocessor
n Concurrent Programming:thread
n Math and numerics:math, conversion/numeric_cast, integer, interval,math/common_factor, math/octonion, math/quaterion,math/special_functions, multi_array, operators,random, rational, uBLAS
n Correctness and testing:concept check, static_assert, test
Introductionl Introducing Boostl Licensel Available Librariesl Available Libraries (2)l Supported Compilersl Design and Programmingl Implementation Variationl Test Policies
The Boost Graph Library
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 6/48
Available Libraries (2)
n Data structures:any, compressed_pair, tuple, variant
n Input/Output:format, io state savers
n Inter-language support:python
n Memory:pool, smart_ptr, utility
n Parsing:spirit
n Miscellaneous:base-from-member, compressed_pair, conversion, crc,date_time, filesystem, optional, timer, utility,value_initialized
n Broken compiler workarounds:compatibility, config
Introductionl Introducing Boostl Licensel Available Librariesl Available Libraries (2)l Supported Compilersl Design and Programmingl Implementation Variationl Test Policies
The Boost Graph Library
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 7/48
Supported Compilers
n IBM VisualAge C++ (80%)n GNU GCC 3.x (96-99%)n GNU GCC 2.95.x (62-87%)n SGI MIPSpro (92%)n HP-UX acc (26%)n Intel C++ (86-99%)n Sun C++ (44-56%)n Borland (60-79%)n Metrowerks Codewarrior (83-99%)n Microsoft Visual C++ (62-100%)n Comeau C++ (78-86%)
The percentage of passed regression tests is updated regularly andcan be found on the compiler status summary page[3].
Introductionl Introducing Boostl Licensel Available Librariesl Available Libraries (2)l Supported Compilersl Design and Programmingl Implementation Variationl Test Policies
The Boost Graph Library
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 8/48
Design and Programming
n Guidelinesu Aim for clarity and correctnessu Aim for ISO Standard C++u Follow quality programming practices (Effective C++,...)u Choose meaningful namesu Use exceptions where appropriateu Avoid exception specificationsu Provide sample programs and regression testsu Document your library
n Policiesu Adhere to the naming policies (also for filenames)u Don’t use external librariesu Use fixed-width fonts, don’t use tabs,...u Add copyright statements, license information,...
Introductionl Introducing Boostl Licensel Available Librariesl Available Libraries (2)l Supported Compilersl Design and Programmingl Implementation Variationl Test Policies
The Boost Graph Library
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 9/48
Implementation Variation
n Separation of interface/implementation
n Interface is important, implementation just a detailn Boost Policy: provide a single, general purpose
implementationn Reasons for implementation variation
u Platform dependencies (compiler, file system, threadmechanism,...)
u Performance trade-offs (time vs. space)n Techniques for implementation variation
u Template-based approaches (policy classes, type traits,specializations, tag dispatching)
u Separate files (selected on build time)u Separate components (e.g. scoped_ptr, smart_ptr,...)u Macros (for small compile time variations, not for evil
hacks!)
Introductionl Introducing Boostl Licensel Available Librariesl Available Libraries (2)l Supported Compilersl Design and Programmingl Implementation Variationl Test Policies
The Boost Graph Library
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 9/48
Implementation Variation
n Separation of interface/implementationn Interface is important, implementation just a detail
n Boost Policy: provide a single, general purposeimplementation
n Reasons for implementation variationu Platform dependencies (compiler, file system, thread
mechanism,...)u Performance trade-offs (time vs. space)
n Techniques for implementation variationu Template-based approaches (policy classes, type traits,
specializations, tag dispatching)u Separate files (selected on build time)u Separate components (e.g. scoped_ptr, smart_ptr,...)u Macros (for small compile time variations, not for evil
hacks!)
Introductionl Introducing Boostl Licensel Available Librariesl Available Libraries (2)l Supported Compilersl Design and Programmingl Implementation Variationl Test Policies
The Boost Graph Library
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 9/48
Implementation Variation
n Separation of interface/implementationn Interface is important, implementation just a detailn Boost Policy: provide a single, general purpose
implementation
n Reasons for implementation variationu Platform dependencies (compiler, file system, thread
mechanism,...)u Performance trade-offs (time vs. space)
n Techniques for implementation variationu Template-based approaches (policy classes, type traits,
specializations, tag dispatching)u Separate files (selected on build time)u Separate components (e.g. scoped_ptr, smart_ptr,...)u Macros (for small compile time variations, not for evil
hacks!)
Introductionl Introducing Boostl Licensel Available Librariesl Available Libraries (2)l Supported Compilersl Design and Programmingl Implementation Variationl Test Policies
The Boost Graph Library
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 9/48
Implementation Variation
n Separation of interface/implementationn Interface is important, implementation just a detailn Boost Policy: provide a single, general purpose
implementationn Reasons for implementation variation
u Platform dependencies (compiler, file system, threadmechanism,...)
u Performance trade-offs (time vs. space)
n Techniques for implementation variationu Template-based approaches (policy classes, type traits,
specializations, tag dispatching)u Separate files (selected on build time)u Separate components (e.g. scoped_ptr, smart_ptr,...)u Macros (for small compile time variations, not for evil
hacks!)
Introductionl Introducing Boostl Licensel Available Librariesl Available Libraries (2)l Supported Compilersl Design and Programmingl Implementation Variationl Test Policies
The Boost Graph Library
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 9/48
Implementation Variation
n Separation of interface/implementationn Interface is important, implementation just a detailn Boost Policy: provide a single, general purpose
implementationn Reasons for implementation variation
u Platform dependencies (compiler, file system, threadmechanism,...)
u Performance trade-offs (time vs. space)n Techniques for implementation variation
u Template-based approaches (policy classes, type traits,specializations, tag dispatching)
u Separate files (selected on build time)u Separate components (e.g. scoped_ptr, smart_ptr,...)u Macros (for small compile time variations, not for evil
hacks!)
Introductionl Introducing Boostl Licensel Available Librariesl Available Libraries (2)l Supported Compilersl Design and Programmingl Implementation Variationl Test Policies
The Boost Graph Library
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 10/48
Test Policies
n Libraries are intended to be reliable and portablen Requires an automatic regression test suiten Test policy
u Requiredn One or more automatic regression testsn Compile-only and compile-and-link tests are okay, toon The output should be briefn Error reporting via non-zero return valuesn Tests have to compile, link, and run quickly
u Optional (highly recommended)n Usage of Test Tools (Boost.Test)n Usage of Unit Test Framework (for more complex tests)
Introduction
The Boost Graph Libraryl Historyl Goalsl Design Issuesl BGL Solutionsl Generic Programming in C++l The GP Processl C++ Conceptl Example: InputIteratorl Tag Dispatchingl Concept Checkingl Concept Checking (2)l Concept Coveringl Concept Covering (2)l Named Function Parametersl Graph Traversal Conceptsl Graph Traversal: Iteratorsl Property Mapsl Property Maps (2)l Graph Modification Conceptsl Algorithmsl Algorithmic Visitorsl Graph Adaptors
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 11/48
The Boost Graph Library
Introduction
The Boost Graph Libraryl Historyl Goalsl Design Issuesl BGL Solutionsl Generic Programming in C++l The GP Processl C++ Conceptl Example: InputIteratorl Tag Dispatchingl Concept Checkingl Concept Checking (2)l Concept Coveringl Concept Covering (2)l Named Function Parametersl Graph Traversal Conceptsl Graph Traversal: Iteratorsl Property Mapsl Property Maps (2)l Graph Modification Conceptsl Algorithmsl Algorithmic Visitorsl Graph Adaptors
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 12/48
History
n Started as GGCL (Generic Graph Component Library) at theUniversity of Notre Dame in 1998
n Was initially created to support the MTL (Matrix TemplateLibrary, [4]) in sparse matrix calculations
n Based on earlier work in that area by Alexander Stepanovand Dietmar Kühl[5]
n In September 2000 the GGCL passed the Boost formalreview and became the Boost Graph Library (BGL)
n A book has been published about this library as part of thewell known C++ In-Depth series in 2001[6]
Introduction
The Boost Graph Libraryl Historyl Goalsl Design Issuesl BGL Solutionsl Generic Programming in C++l The GP Processl C++ Conceptl Example: InputIteratorl Tag Dispatchingl Concept Checkingl Concept Checking (2)l Concept Coveringl Concept Covering (2)l Named Function Parametersl Graph Traversal Conceptsl Graph Traversal: Iteratorsl Property Mapsl Property Maps (2)l Graph Modification Conceptsl Algorithmsl Algorithmic Visitorsl Graph Adaptors
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 13/48
Goals
n Provide an “open” standardized generic interface fortraversing graphs
n Implement a number of useful graph algorithms and datastructures
n Allow efficient implementations of custom algorithms anddata structures
n Provide adaptors to use BGL algorithms with data structuresform other algorithm libraries (e.g. LEDA[9] and StanfordGraphBase[10])
n Flexibility (sometimes at the cost of ease of use)
Introduction
The Boost Graph Libraryl Historyl Goalsl Design Issuesl BGL Solutionsl Generic Programming in C++l The GP Processl C++ Conceptl Example: InputIteratorl Tag Dispatchingl Concept Checkingl Concept Checking (2)l Concept Coveringl Concept Covering (2)l Named Function Parametersl Graph Traversal Conceptsl Graph Traversal: Iteratorsl Property Mapsl Property Maps (2)l Graph Modification Conceptsl Algorithmsl Algorithmic Visitorsl Graph Adaptors
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 14/48
Design Issues
n Algorithm uses different data structure than the applicationu Solution 1: Convert data back and forth??u Solution 2: Provide a set of common data structures (like
in LEDA)?u Isn’t there any better solution?
n Algorithmic functionality should be extensible/modifiableu How to exchange primitive graph algorithms in more
complex ones (e.g. path searching in a maximum-flowalgorithm)?
u How use LEDA DFS to build a DFS-tree?u How to implement heuristic speed-up techniques?
n Efficiency, flexibility
Introduction
The Boost Graph Libraryl Historyl Goalsl Design Issuesl BGL Solutionsl Generic Programming in C++l The GP Processl C++ Conceptl Example: InputIteratorl Tag Dispatchingl Concept Checkingl Concept Checking (2)l Concept Coveringl Concept Covering (2)l Named Function Parametersl Graph Traversal Conceptsl Graph Traversal: Iteratorsl Property Mapsl Property Maps (2)l Graph Modification Conceptsl Algorithmsl Algorithmic Visitorsl Graph Adaptors
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 14/48
Design Issues
n Algorithm uses different data structure than the applicationu Solution 1: Convert data back and forth??u Solution 2: Provide a set of common data structures (like
in LEDA)?u Isn’t there any better solution?
n Algorithmic functionality should be extensible/modifiableu How to exchange primitive graph algorithms in more
complex ones (e.g. path searching in a maximum-flowalgorithm)?
u How use LEDA DFS to build a DFS-tree?u How to implement heuristic speed-up techniques?
n Efficiency, flexibility
Introduction
The Boost Graph Libraryl Historyl Goalsl Design Issuesl BGL Solutionsl Generic Programming in C++l The GP Processl C++ Conceptl Example: InputIteratorl Tag Dispatchingl Concept Checkingl Concept Checking (2)l Concept Coveringl Concept Covering (2)l Named Function Parametersl Graph Traversal Conceptsl Graph Traversal: Iteratorsl Property Mapsl Property Maps (2)l Graph Modification Conceptsl Algorithmsl Algorithmic Visitorsl Graph Adaptors
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 14/48
Design Issues
n Algorithm uses different data structure than the applicationu Solution 1: Convert data back and forth??u Solution 2: Provide a set of common data structures (like
in LEDA)?u Isn’t there any better solution?
n Algorithmic functionality should be extensible/modifiableu How to exchange primitive graph algorithms in more
complex ones (e.g. path searching in a maximum-flowalgorithm)?
u How use LEDA DFS to build a DFS-tree?u How to implement heuristic speed-up techniques?
n Efficiency, flexibility
Introduction
The Boost Graph Libraryl Historyl Goalsl Design Issuesl BGL Solutionsl Generic Programming in C++l The GP Processl C++ Conceptl Example: InputIteratorl Tag Dispatchingl Concept Checkingl Concept Checking (2)l Concept Coveringl Concept Covering (2)l Named Function Parametersl Graph Traversal Conceptsl Graph Traversal: Iteratorsl Property Mapsl Property Maps (2)l Graph Modification Conceptsl Algorithmsl Algorithmic Visitorsl Graph Adaptors
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 15/48
BGL Solutions
n Genericity (static polymorphism)u Algorithm/Data structure interoperability
n Iterators (edges, vertices, along adjacency structure)n Visitors (not GoF Visitors! Functors on steroids)n Vertex/Edge Property Multi-Parameterization (associate
values to vertices/edges)u Concept checking, concept coverageu Traits and tag dispatchingu Adaptors to map LEDA,... data structures
n Subtype polymorphism (as found in earlier versions) wasdropped
Introduction
The Boost Graph Libraryl Historyl Goalsl Design Issuesl BGL Solutionsl Generic Programming in C++l The GP Processl C++ Conceptl Example: InputIteratorl Tag Dispatchingl Concept Checkingl Concept Checking (2)l Concept Coveringl Concept Covering (2)l Named Function Parametersl Graph Traversal Conceptsl Graph Traversal: Iteratorsl Property Mapsl Property Maps (2)l Graph Modification Conceptsl Algorithmsl Algorithmic Visitorsl Graph Adaptors
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 16/48
Generic Programming in C++
n Allows to separate data structures and algorithmsn GP characterized by use of parametric polymorphism
(templates)n Uses abstract requirement specifications (e.g.
LessThanComparable, Assignable)u Similar Abstract Data Type (ADT) (type, operations,
axioms, preconditions)u Taken a step further: family of types having the same
interface and semantics (concept)n OOP realizes polymorphism via virtual methods/inheritance
(subtype polymorphism)u Interface requirements→ methods of a base classu Calls are dispatched at runtime (using virtual function
tables)
Introduction
The Boost Graph Libraryl Historyl Goalsl Design Issuesl BGL Solutionsl Generic Programming in C++l The GP Processl C++ Conceptl Example: InputIteratorl Tag Dispatchingl Concept Checkingl Concept Checking (2)l Concept Coveringl Concept Covering (2)l Named Function Parametersl Graph Traversal Conceptsl Graph Traversal: Iteratorsl Property Mapsl Property Maps (2)l Graph Modification Conceptsl Algorithmsl Algorithmic Visitorsl Graph Adaptors
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 17/48
The Generic Programming Process
As outlined by Musser and Stepanov[11]:
1. Identify useful and efficient algorithms2. Find their generic representation (i.e., parameterize each
algorithm such that it makes the fewest possiblerequirements of the data on which it operates)
3. Derive a set of (minimal) requirements that allow thesealgorithms to run efficiently
4. Construct a framework based on classifications ofrequirements
Reflected in the structure and organization of the STLcomponents.
Introduction
The Boost Graph Libraryl Historyl Goalsl Design Issuesl BGL Solutionsl Generic Programming in C++l The GP Processl C++ Conceptl Example: InputIteratorl Tag Dispatchingl Concept Checkingl Concept Checking (2)l Concept Coveringl Concept Covering (2)l Named Function Parametersl Graph Traversal Conceptsl Graph Traversal: Iteratorsl Property Mapsl Property Maps (2)l Graph Modification Conceptsl Algorithmsl Algorithmic Visitorsl Graph Adaptors
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 18/48
C++ Concept
n Set of Requirementsu Valid expressionsu Associated Types (often via a traits class)u Invariantsu Complexity guarantees
n A type that meets those requirements models the conceptn Requirements of another concept can be extended
(refinement)
Introduction
The Boost Graph Libraryl Historyl Goalsl Design Issuesl BGL Solutionsl Generic Programming in C++l The GP Processl C++ Conceptl Example: InputIteratorl Tag Dispatchingl Concept Checkingl Concept Checking (2)l Concept Coveringl Concept Covering (2)l Named Function Parametersl Graph Traversal Conceptsl Graph Traversal: Iteratorsl Property Mapsl Property Maps (2)l Graph Modification Conceptsl Algorithmsl Algorithmic Visitorsl Graph Adaptors
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 19/48
Concept Example: InputIterator
n Refinement of TrivialIterator (which in turn refines Assignableand EqualityComparable)
n InputIterator adds pre- and post-incrementn Valid expressions:
1 i = j ; / / assignment ( from Assignable )
2 T i ( j ) ; / / copy ( from Assignable )
3 i == j ; / / e q u a l i t y t e s t ( from Equal i tyComparable )
4 i != j ; / / i n e q u a l i t y t e s t ( from Equal i tyComparable )
5 ∗ i ; / / dereference ( from T r i v i a l I t e r a t o r )
6 ++ i ; / / pre−increment operator
7 i ++; / / post−increment operator
n std::iterator_traits provides access to associatedtypes (value_type, reference, pointer,difference_type, iterator_category)
n InputIterator guarantees that all operations take constanttime
Introduction
The Boost Graph Libraryl Historyl Goalsl Design Issuesl BGL Solutionsl Generic Programming in C++l The GP Processl C++ Conceptl Example: InputIteratorl Tag Dispatchingl Concept Checkingl Concept Checking (2)l Concept Coveringl Concept Covering (2)l Named Function Parametersl Graph Traversal Conceptsl Graph Traversal: Iteratorsl Property Mapsl Property Maps (2)l Graph Modification Conceptsl Algorithmsl Algorithmic Visitorsl Graph Adaptors
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 20/48
Tag Dispatching
n Using function overloading to dispatch based on propertiesof a type:
1 struct i n p u t _ i t e r a t o r _ t a g { } ; struct o u t p u t _ i t e r a t o r _ t a g { } ;
2 struct f o r w a r d _ i t e r a t o r _ t a g : public i n p u t _ i t e r a t o r _ t a g { } ;
3 struct b i d i r e c t i o n a l _ i t e r a t o r _ t a g : public i n p u t _ i t e r a t o r _ t a g { } ;
4 struct random_i tera tor_ tag : public b i d i r e c t i o n a l _ i t e r a t o r _ t a g { } ;
5 template <typename I n p u t I t e r a t o r , typename Distance >
6 void advance_dispatch ( I n p u t I t e r a t o r & i , Distance n , i n p u t _ i t e r a t o r _ t a g )
7 { while ( n−− ) ++ i ; }
8 template <typename B i d i r e c t i o n a l I t e r a t o r , typename Distance >
9 void advance_dispatch ( B i d i r e c t i o n a l I t e r a t o r & i , Distance n , b i d i r e c t i o n a l _ i t e r a t o r _ t a g ) {
10 i f ( n >= 0 ) while ( n−− ) ++ i ;
11 else while ( n++ ) −−i ;
12 }
13 template <typename RandomAccessIterator , typename Distance >
14 void advance_dispatch ( RandomAccessIterator& i , Distance n , random_access_i terator_tag )
15 { i += n ; }
16 template <typename I n p u t I t e r a t o r , typename Distance >
17 void advance ( I n p u t I t e r a t o r & i , Distance n ) {
18 typedef typename i t e r a t o r _ t r a i t s < I n p u t I t e r a t o r > : : i t e r a t o r _ c a t e g o r y Cat ;
19 advance_dispatch ( i , n , Cat ( ) ) ;
20 }
Introduction
The Boost Graph Libraryl Historyl Goalsl Design Issuesl BGL Solutionsl Generic Programming in C++l The GP Processl C++ Conceptl Example: InputIteratorl Tag Dispatchingl Concept Checkingl Concept Checking (2)l Concept Coveringl Concept Covering (2)l Named Function Parametersl Graph Traversal Conceptsl Graph Traversal: Iteratorsl Property Mapsl Property Maps (2)l Graph Modification Conceptsl Algorithmsl Algorithmic Visitorsl Graph Adaptors
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 21/48
Concept Checking
n Types used with some algorithm have to model its conceptsn Using improper classes results in error messages, that might
be hard to deciphern Typical example:
1 # inc lude <algor i thm >
2 class Foo { } ;
3
4 i n t main ( int , char∗∗)
5 {
6 Foo ar ray_o f_ foo [ 1 0 ] ;
7 std : : s o r t ( ar ray_of_ foo , a r ray_o f_ foo + 1 0 ) ;
8 return 0 ;
9 }
n Foo fails to define operator<() (LessThanComparableconcept)
n Results in an error message of 70 lines with gcc 3.3n None of those messages refers to std::sort or user code
Introduction
The Boost Graph Libraryl Historyl Goalsl Design Issuesl BGL Solutionsl Generic Programming in C++l The GP Processl C++ Conceptl Example: InputIteratorl Tag Dispatchingl Concept Checkingl Concept Checking (2)l Concept Coveringl Concept Covering (2)l Named Function Parametersl Graph Traversal Conceptsl Graph Traversal: Iteratorsl Property Mapsl Property Maps (2)l Graph Modification Conceptsl Algorithmsl Algorithmic Visitorsl Graph Adaptors
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 22/48
Concept Checking (2)
Solution: concept checking1 template <typename T>
2 struct LessThanComparableConcept {
3 void c o n s t r a i n t s ( ) {
4 ( bool ) ( a < b ) ;
5 }
6 T a , b ;
7 } ;
Instantiated using BCCL (Boost Concept Check Library):1 #include <boost / concept_check . hpp>
2
3 template <typename I t e r a t o r >
4 void sa fe_sor t ( I t e r a t o r f i r s t , I t e r a t o r l a s t )
5 {
6 typedef typename std : : i t e r a t o r _ t r a i t s < I t e r a t o r > : : value_type T ;
7 f unc t ion_requ i res < LessThanComparable<T> > ( ) ;
8 / / o ther requirements . . .
9 std : : s o r t ( f i r s t , l a s t ) ;
10 }
The error message is shorter, the point of error is indicated.
Introduction
The Boost Graph Libraryl Historyl Goalsl Design Issuesl BGL Solutionsl Generic Programming in C++l The GP Processl C++ Conceptl Example: InputIteratorl Tag Dispatchingl Concept Checkingl Concept Checking (2)l Concept Coveringl Concept Covering (2)l Named Function Parametersl Graph Traversal Conceptsl Graph Traversal: Iteratorsl Property Mapsl Property Maps (2)l Graph Modification Conceptsl Algorithmsl Algorithmic Visitorsl Graph Adaptors
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 23/48
Concept Covering
n Complementary problem to concept checking: do thedocumented requirements cover the algorithm’simplementation?
n Manual inspection is error prone, should be automatedn The BCCL provides archetype classes for common conceptsn Archetype classes provide a minimal implementation of a
concept1 # inc lude <algor i thm >
2 # inc lude <boost / concept_archetype . hpp>
3 i n t main ( int , char∗∗)
4 {
5 using namespace boost ;
6 typedef less_than_comparable_archetype <> T ;
7 random_access_i terator_archetype <T> r i ;
8 std : : s o r t ( r i , r i ) ;
9 }
n The example won’t compile, sort also needs Assignable
Introduction
The Boost Graph Libraryl Historyl Goalsl Design Issuesl BGL Solutionsl Generic Programming in C++l The GP Processl C++ Conceptl Example: InputIteratorl Tag Dispatchingl Concept Checkingl Concept Checking (2)l Concept Coveringl Concept Covering (2)l Named Function Parametersl Graph Traversal Conceptsl Graph Traversal: Iteratorsl Property Mapsl Property Maps (2)l Graph Modification Conceptsl Algorithmsl Algorithmic Visitorsl Graph Adaptors
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 24/48
Concept Covering (2)
n Example: implementation of Assignable archetype1 template <typename Base = nul l_archetype <> >
2 class assignable_archetype : public Base
3 {
4 typedef assignable_archetype s e l f ;
5 public :
6 assignable_archetype ( const s e l f &) { }
7 s e l f& operator =( const s e l f &) { return ∗th is ; }
8 } ;
n BGL includes one archetype class for every graph conceptn Can be verified using the tests in libs/graph/test/
Introduction
The Boost Graph Libraryl Historyl Goalsl Design Issuesl BGL Solutionsl Generic Programming in C++l The GP Processl C++ Conceptl Example: InputIteratorl Tag Dispatchingl Concept Checkingl Concept Checking (2)l Concept Coveringl Concept Covering (2)l Named Function Parametersl Graph Traversal Conceptsl Graph Traversal: Iteratorsl Property Mapsl Property Maps (2)l Graph Modification Conceptsl Algorithmsl Algorithmic Visitorsl Graph Adaptors
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 25/48
Named Function Parameters
n Flexibility often causes long parameter listsn C++ default parameters are not always sufficientn Named parameters aren’t supported in C++n BGL approximates this behavior using bgl_named_params
n Example:1 bool r = boost : : be l lman_ford_shor tes t_paths ( g , N,
2 boost : : weight_map ( weight ) .
3 distance_map ( &dis tance [ 0 ] ) .
4 predecessor_map ( &parent [ 0 ] ) ) ;
n The order doesn’t mattern Note that a dot “separates” the arguments
Introduction
The Boost Graph Libraryl Historyl Goalsl Design Issuesl BGL Solutionsl Generic Programming in C++l The GP Processl C++ Conceptl Example: InputIteratorl Tag Dispatchingl Concept Checkingl Concept Checking (2)l Concept Coveringl Concept Covering (2)l Named Function Parametersl Graph Traversal Conceptsl Graph Traversal: Iteratorsl Property Mapsl Property Maps (2)l Graph Modification Conceptsl Algorithmsl Algorithmic Visitorsl Graph Adaptors
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 26/48
Graph Traversal Concepts
The dijkstra_shortest_paths algorithm requires thegraph to model VertexListGraph and IncidenceGraph.
Introduction
The Boost Graph Libraryl Historyl Goalsl Design Issuesl BGL Solutionsl Generic Programming in C++l The GP Processl C++ Conceptl Example: InputIteratorl Tag Dispatchingl Concept Checkingl Concept Checking (2)l Concept Coveringl Concept Covering (2)l Named Function Parametersl Graph Traversal Conceptsl Graph Traversal: Iteratorsl Property Mapsl Property Maps (2)l Graph Modification Conceptsl Algorithmsl Algorithmic Visitorsl Graph Adaptors
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 27/48
Graph Traversal: Iterators
n Typesu Vertex iterator (traverses all vertices, value type is
vertex_descriptor)u Edge iterator (traverses all edges, value type is
edge_descriptor)u Out-edges iterator (traverse all out-edges of a vertex,
value type is edge_descriptor)u In-edges iterator (traverses all in-edges of a vertex, value
type is edge_descriptor)u Adjacency iterator (traverses all vertices adjacent to a
vertex, value type is vertex_descriptor)n Some graph types can’t provide efficient versions of all
iterator types (results in compile errors)
Introduction
The Boost Graph Libraryl Historyl Goalsl Design Issuesl BGL Solutionsl Generic Programming in C++l The GP Processl C++ Conceptl Example: InputIteratorl Tag Dispatchingl Concept Checkingl Concept Checking (2)l Concept Coveringl Concept Covering (2)l Named Function Parametersl Graph Traversal Conceptsl Graph Traversal: Iteratorsl Property Mapsl Property Maps (2)l Graph Modification Conceptsl Algorithmsl Algorithmic Visitorsl Graph Adaptors
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 28/48
Property Maps
n How to attach user defined properties to edges and vertices?n Possibilities: inside vertex/edge data structures, in external
data structures, calculated on demandn BGL uses a property map library to allow thatn Categories of properties:
u readable (can only be read, e.g. edge weight, vertexname)
u writable (can only be written, e.g. parent map)u read/write (e.g. color of nodes, distance properties)u lvalue (like read/write, but has to be in memory, it’s
possible to get a reference to it)n Interface again specified using (purposefully vague)
conceptsu Global functions: put(), get(), operator[]u ReadablePropertyMap, WritablePropertyMap,...
Introduction
The Boost Graph Libraryl Historyl Goalsl Design Issuesl BGL Solutionsl Generic Programming in C++l The GP Processl C++ Conceptl Example: InputIteratorl Tag Dispatchingl Concept Checkingl Concept Checking (2)l Concept Coveringl Concept Covering (2)l Named Function Parametersl Graph Traversal Conceptsl Graph Traversal: Iteratorsl Property Mapsl Property Maps (2)l Graph Modification Conceptsl Algorithmsl Algorithmic Visitorsl Graph Adaptors
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 29/48
Property Maps (2)
n Adding a property:1 proper ty < vertex_name_t , s td : : s t r i n g >
n Defining a new kind of property:1 namespace boost {
2 enum my_spec ia l_proper ty_ t { my_specia l_property = 42; } / / unique #
3 BOOST_INSTALL_PROPERTY ( vertex , my_specia l_property ) ;
4 }
n Nesting properties:1 typedef ad jacency_ l i s t <
2 l i s t S , / / s to re out edges o f each ver tex i n a std : : l i s t
3 l i s t S , / / s to re ver tex set i n a std : : l i s t
4 directedS , / / i t ’ s a d i r e c t e d graph
5 / / ve r tex p r o p e r t i e s
6 proper ty < vertex_name_t , s td : : s t r i n g ,
7 proper ty < ver tex_d is tance_ t , f loa t ,
8 proper ty < ver tex_co lo r_ t , de fau l t_co lo r_ type ,
9 proper ty < my_spec ia l_property_t , s td : : s t r i n g > > > > ,
10 / / edge p r o p e r t i e s
11 proper ty < edge_weight_t , f l o a t > > Graph ;
Introduction
The Boost Graph Libraryl Historyl Goalsl Design Issuesl BGL Solutionsl Generic Programming in C++l The GP Processl C++ Conceptl Example: InputIteratorl Tag Dispatchingl Concept Checkingl Concept Checking (2)l Concept Coveringl Concept Covering (2)l Named Function Parametersl Graph Traversal Conceptsl Graph Traversal: Iteratorsl Property Mapsl Property Maps (2)l Graph Modification Conceptsl Algorithmsl Algorithmic Visitorsl Graph Adaptors
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 30/48
Graph Modification Concepts
n BGL offers various concepts for graph modificationsn Possible modifications:
u Insert/remove edges and/or verticesu Change edge and/or vertex properties
n Factored into many small concepts to allow fine grainedselection
n Examples:u VertexMutablePropertyGraph (ability to add vertices
including properties)u MutableIncidenceGraph (ability to remove edges from
out-edges list of a vertex)u EdgeMutableGraph (ability to add and remove edges)u ...
Introduction
The Boost Graph Libraryl Historyl Goalsl Design Issuesl BGL Solutionsl Generic Programming in C++l The GP Processl C++ Conceptl Example: InputIteratorl Tag Dispatchingl Concept Checkingl Concept Checking (2)l Concept Coveringl Concept Covering (2)l Named Function Parametersl Graph Traversal Conceptsl Graph Traversal: Iteratorsl Property Mapsl Property Maps (2)l Graph Modification Conceptsl Algorithmsl Algorithmic Visitorsl Graph Adaptors
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 31/48
Algorithms
n Divided in categories:u Basic search algorithms (BFS, DFS, topological sort,...)u Shortest paths (Dijkstra, Bellman-Ford, Johnson all
pairs,...)u Minimum spanning tree (Kruskal, Prim)u Static connected components (connected, strong)u Incremental connected componentsu Maximum flow (Edmunds-Karp, Push Relabel)u Vertex ordering (Sloan, Cuthill-McKee,...)
n Can be used with any graph type modeling the requiredconcepts
n Parameterized with a visitor typen Sometimes parameterized with property mapsn Documented excellently (including examples)
Introduction
The Boost Graph Libraryl Historyl Goalsl Design Issuesl BGL Solutionsl Generic Programming in C++l The GP Processl C++ Conceptl Example: InputIteratorl Tag Dispatchingl Concept Checkingl Concept Checking (2)l Concept Coveringl Concept Covering (2)l Named Function Parametersl Graph Traversal Conceptsl Graph Traversal: Iteratorsl Property Mapsl Property Maps (2)l Graph Modification Conceptsl Algorithmsl Algorithmic Visitorsl Graph Adaptors
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 32/48
Algorithmic Visitors
n Allow users to insert operations at certain points within analgorithm
n Graph algorithms typically have multiple event pointsn Visitors have more methods than just operator() like functorsn Example: BFSVisitor concept
u initialize_vertex (init. every vertex before start)u discover_vertexu examine_edge (invoked on every out-edge after
discovering a vertex)u tree_edge (member of search tree)u non_tree_edgeu gray_targetu black_targetu finish_vertex
Introduction
The Boost Graph Libraryl Historyl Goalsl Design Issuesl BGL Solutionsl Generic Programming in C++l The GP Processl C++ Conceptl Example: InputIteratorl Tag Dispatchingl Concept Checkingl Concept Checking (2)l Concept Coveringl Concept Covering (2)l Named Function Parametersl Graph Traversal Conceptsl Graph Traversal: Iteratorsl Property Mapsl Property Maps (2)l Graph Modification Conceptsl Algorithmsl Algorithmic Visitorsl Graph Adaptors
Demo
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 33/48
Graph Adaptors
n edge_list adapts an iterator range of vertex pairs to modelEdgeListGraph
n reverse_graph flips in- and out-edges, effectivelytransposing the graph
n filtered_graph creates a filtered view of a graph using anedge and a vertex predicate (doesn’t copy the original graph)
n SGB Graph Pointer adapts a Stanford Base Graphn LEDA Graph (special case, not really an adaptor)n std::vector<EdgeList> to use std::vector<std::list<int> > like a graph
Introduction
The Boost Graph Library
Demol Taskl Original Solutionl Filter Entryl Priority Queuel Edge Representationl Vertex Representationl Vertex Representation (2)l Building the Graphl Building the Graph (2)l Running Dijkstral Boost Graph Library Solutionl Codel Code (2)
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 34/48
Demo
Introduction
The Boost Graph Library
Demol Taskl Original Solutionl Filter Entryl Priority Queuel Edge Representationl Vertex Representationl Vertex Representation (2)l Building the Graphl Building the Graph (2)l Running Dijkstral Boost Graph Library Solutionl Codel Code (2)
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 35/48
Task
1. Query the trader for available mimetypes and filters2. Build a graph representation from this collection of
mimetypes (approx. 70 vertices) and filters (approx. 100edges)
3. Perform the necessary operations:n Find all mimetypes convertible to some destination
mimetype (BFS/DFS with edge directions reversed!)n Find the shortest path between a source and a
destination mimetype (Dijkstra)4. Create a filter chain along the shortest path
Introduction
The Boost Graph Library
Demol Taskl Original Solutionl Filter Entryl Priority Queuel Edge Representationl Vertex Representationl Vertex Representation (2)l Building the Graphl Building the Graph (2)l Running Dijkstral Boost Graph Library Solutionl Codel Code (2)
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 36/48
Original Solution
n Part of KOffice[7]n Motivation
u Allows a very flexible use of filter componentsu Minimizes duplicated work
n Sources (in koffice/lib/kofficecore)u koFilterChain.(h|cpp) (approx. 900 LOC)u koFilterManager.(h|cpp) (approx. 420 LOC)u koFilter.(h|cpp) (approx. 170 LOC)u koQueryTrader.(h|cpp) (approx. 100 LOC)u priorityqueue.h (approx. 130 LOC)
n Code spent on graph code: approximately 530 (+130) lines
Introduction
The Boost Graph Library
Demol Taskl Original Solutionl Filter Entryl Priority Queuel Edge Representationl Vertex Representationl Vertex Representation (2)l Building the Graphl Building the Graph (2)l Running Dijkstral Boost Graph Library Solutionl Codel Code (2)
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 37/48
Filter Entry
1 class K o F i l t e r E n t r y : public KShared
2 {
3 public :
4 typedef KSharedPtr < K o F i l t e r E n t r y > Pt r ;
5
6 K o F i l t e r E n t r y ( ) : weight ( 0 ) { m_service = 0L ; } / / f o r QValueList
7 K o F i l t e r E n t r y ( KService : : P t r se rv i ce ) ;
8 ~ K o F i l t e r E n t r y ( ) { }
9
10 K o F i l t e r∗ c r e a t e F i l t e r ( KoF i l t e rCha in∗ chain , QObject∗ parent = 0 , const char∗ name = 0 ) ;
11
12 Q S t r i n g L i s t impor t ; / / The imported mimetype ( s )
13 Q S t r i n g L i s t export_ ; / / The exported mimetype ( s ) .
14 unsigned i n t weight ; / / The " weight " o f t h i s f i l t e r path .
15 QStr ing a v a i l a b l e ; / / Do we have to check dur ing runt ime ?
16
17 . . .
18
19 s t a t i c QValueList < K o F i l t e r E n t r y : : Ptr > query ( const QStr ing& _const r = QStr ing : : n u l l ) ;
20 KService : : P t r se rv i ce ( ) const { return m_service ; }
21
22 private :
23 KService : : P t r m_service ;
24 } ;
Introduction
The Boost Graph Library
Demol Taskl Original Solutionl Filter Entryl Priority Queuel Edge Representationl Vertex Representationl Vertex Representation (2)l Building the Graphl Building the Graph (2)l Running Dijkstral Boost Graph Library Solutionl Codel Code (2)
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 38/48
Priority Queue
1 template<class T> class Pr ior i tyQueue {
2 public :
3 . . .
4 unsigned i n t count ( ) const { return m_vector . s i ze ( ) ; }
5 bool isEmpty ( ) const { return m_vector . empty ( ) ; }
6 void i n s e r t ( T∗ i tem ) ;
7 /∗∗8 ∗ C a l l t h i s method a f t e r decreasing the key o f the i t h i tem . The heap
9 ∗ p r o p e r t i e s w i l l no longer be v a l i d i f you e i t h e r f o r g e t to c a l l t h a t
10 ∗ method , or i f you \ b increase the key .
11 ∗/
12 void keyDecreased ( T∗ i tem ) ;
13 T∗ extractMinimum ( ) ;
14 private :
15 / / Note : We have to use a 1−based index here , and we get / r e t u r n 0−based ones
16 i n t parent ( i n t i ) { return ( ( i + 1 ) >> 1 ) − 1 ; }
17 i n t l e f t ( i n t i ) { return ( ( i + 1 ) << 1 ) − 1 ; }
18 i n t r i g h t ( i n t i ) { return ( i + 1 ) << 1 ; }
19 void heap i f y ( i n t i ) ;
20 void bubbleUp ( T∗ i tem , i n t i ) ;
21 / / Bu i l ds the heap i n the vec to r i n O( n )
22 void bui ldHeap ( ) ;
23 std : : vector <T∗> m_vector ;
24 } ;
Introduction
The Boost Graph Library
Demol Taskl Original Solutionl Filter Entryl Priority Queuel Edge Representationl Vertex Representationl Vertex Representation (2)l Building the Graphl Building the Graph (2)l Running Dijkstral Boost Graph Library Solutionl Codel Code (2)
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 39/48
Edge Representation
1 class Edge
2 {
3 public :
4 / / c reates a new edge to " ve r tex " w i th the given weight .
5 Edge ( Vertex∗ vertex , K o F i l t e r E n t r y : : P t r f i l t e r E n t r y ) ;
6 ~Edge ( ) { }
7
8 unsigned i n t weight ( ) const { return m _ f i l t e r E n t r y ? m _ f i l t e r E n t r y−>weight : 0 ; }
9 K o F i l t e r E n t r y : : P t r f i l t e r E n t r y ( ) const { return m _ f i l t e r E n t r y ; }
10 const Vertex∗ ver tex ( ) const { return m_vertex ; }
11
12 / / Relaxes the " connected " ve r tex ( i . e . the weight o f the
13 / / connected ver tex = " predec.−>key ( ) " ( parameter ) + weight o f t h i s edge
14 / / As t h i s w i l l on ly be c a l l e d once we c a l c u l a t e the weight
15 / / o f the edge " on the f l y "
16 / / Note : We have to pass the queue as we have to c a l l keyDecreased : }
17 void r e l a x ( const Vertex∗ predecessor , Pr ior i tyQueue <Vertex >& queue ) ;
18
19 private :
20 Vertex∗ m_vertex ;
21 K o F i l t e r E n t r y : : P t r m _ f i l t e r E n t r y ;
22 } ;
Introduction
The Boost Graph Library
Demol Taskl Original Solutionl Filter Entryl Priority Queuel Edge Representationl Vertex Representationl Vertex Representation (2)l Building the Graphl Building the Graph (2)l Running Dijkstral Boost Graph Library Solutionl Codel Code (2)
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 40/48
Vertex Representation
1 class Vertex
2 {
3 public :
4 Vertex ( const QCString& mimeType ) ;
5 ~Vertex ( ) { }
6
7 QCString mimeType ( ) const { return m_mimeType; }
8 / / Current " weight " o f the ver tex − w i l l be " re laxed " when
9 / / running the s h o r t e s t path a lgo r i thm . Returns t r u e i f i t
10 / / r e a l l y has been " re laxed "
11 bool setKey ( unsigned i n t key ) ;
12 unsigned i n t key ( ) const { return m_weight ; }
13 / / Can be used to set the key back to " I n f i n i t y " (UINT_MAX)
14 / / and rese t the predecessor o f t h i s ve r tex
15 void rese t ( ) ;
16 / / P o s i t i o n i n the heap , needed f o r a f a s t keyDecreased opera t ion
17 void set Index ( i n t index ) { m_index= index ; }
18 i n t index ( ) const { return m_index ; }
19 / / predecessor on the way from the source to the d e s t i n a t i o n ,
20 / / needed f o r the s h o r t e s t path a lgo r i thm
21 void setPredecessor ( const Vertex∗ predecessor ) { m_predecessor=predecessor ; }
22 const Vertex∗ predecessor ( ) const { return m_predecessor ; }
23 . . .
Introduction
The Boost Graph Library
Demol Taskl Original Solutionl Filter Entryl Priority Queuel Edge Representationl Vertex Representationl Vertex Representation (2)l Building the Graphl Building the Graph (2)l Running Dijkstral Boost Graph Library Solutionl Codel Code (2)
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 41/48
Vertex Representation (2)
1 . . .
2 / / Adds an outgoing edge to the vertex , t r a n s f e r s ownership
3 void addEdge ( const Edge∗ edge ) ;
4 / / Finds the l i g h t e s t ( ! ) edge p o i n t i n g to the given vertex , i f any (0 i f not found )
5 / / This means i t w i l l always search the whole l i s t o f edges
6 const Edge∗ f indEdge ( const Vertex∗ ver tex ) const ;
7
8 / / This method i s c a l l e d when we need to r e l a x a l l " our " edges .
9 / / We need to pass the queue as we have to n o t i f y i t about key changes− ugly : (
10 void r e l a x V e r t i c e s ( Pr ior i tyQueue <Vertex >& queue ) ;
11
12 private :
13 Vertex ( const Vertex& rhs ) ;
14 Vertex& operator =( const Vertex& rhs ) ;
15
16 QPtrL is t <Edge> m_edges ;
17 const Vertex∗ m_predecessor ;
18 QCString m_mimeType;
19 unsigned i n t m_weight ; / / " key " i n s i d e the queue
20 i n t m_index ; / / p o s i t i o n i n s i d e the queue , needed f o r a f a s t keyDecreased ( )
21 } ;
Introduction
The Boost Graph Library
Demol Taskl Original Solutionl Filter Entryl Priority Queuel Edge Representationl Vertex Representationl Vertex Representation (2)l Building the Graphl Building the Graph (2)l Running Dijkstral Boost Graph Library Solutionl Codel Code (2)
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 42/48
Building the Graph
1 / / F i r s t we add the v e r t i c e s
2
3 QValueList <KoDocumentEntry > par ts ( KoDocumentEntry : : query ( ) ) ;
4 QValueList <KoDocumentEntry > : : C o n s t I t e r a t o r p a r t I t ( pa r t s . begin ( ) ) ;
5 QValueList <KoDocumentEntry > : : C o n s t I t e r a t o r partEnd ( par ts . end ( ) ) ;
6
7 while ( p a r t I t != partEnd ) {
8 const QCString key ( ( ∗p a r t I t ) . se rv i ce ()−>proper ty ( "X−KDE−NativeMimeType " ) . t o S t r i n g ( ) . l a t i n 1 ( ) ) ;
9 i f ( ! key . isEmpty ( ) )
10 m_vert ices . i n s e r t ( key , new Vertex ( key ) ) ;
11 ++ p a r t I t ;
12 }
13
14 . . .
Introduction
The Boost Graph Library
Demol Taskl Original Solutionl Filter Entryl Priority Queuel Edge Representationl Vertex Representationl Vertex Representation (2)l Building the Graphl Building the Graph (2)l Running Dijkstral Boost Graph Library Solutionl Codel Code (2)
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 43/48
Building the Graph (2)
1 / / Get a l l f i l t e r s (== edges )
2 QValueList < K o F i l t e r E n t r y : : Ptr > f i l t e r s ( K o F i l t e r E n t r y : : query ( ) ) ;
3 for ( ; i t != end ; ++ i t ) {
4 / / Make sure the " s t a r t i n g po in ts " ( mimetypes ) e x i s t i n the graph
5 . . .
6 / / Are we al lowed to use t h i s f i l t e r a t a l l ?
7 i f ( KoFi l terManager : : f i l t e r A v a i l a b l e ( ∗ i t ) ) {
8 Q S t r i n g L i s t : : C o n s t I t e r a t o r e x p o r t I t = ( ∗ i t )−>export_ . begin ( ) ;
9 Q S t r i n g L i s t : : C o n s t I t e r a t o r exportEnd = ( ∗ i t )−>export_ . end ( ) ;
10 for ( ; e x p o r t I t != exportEnd ; ++ e x p o r t I t ) {
11 / / F i r s t make sure the expor t ve r tex i s i n place
12 const QCString key = ( ∗e x p o r t I t ) . l a t i n 1 ( ) ; / / l a t i n 1 i s okay here
13 Vertex∗ exp = m_vert ices [ key ] ;
14 i f ( ! exp ) {
15 exp = new Vertex ( key ) ;
16 m_vert ices . i n s e r t ( key , exp ) ;
17 }
18 / / Then create the appropr ia te edges
19 i m p o r t I t = ( ∗ i t )−>impor t . begin ( ) ;
20 for ( ; i m p o r t I t != importEnd ; ++ i m p o r t I t )
21 m_vert ices [ ( ∗ i m p o r t I t ) . l a t i n 1 ( ) ]−>addEdge ( new Edge ( exp , ∗ i t ) ) ;
22 }
23 }
24 }
Introduction
The Boost Graph Library
Demol Taskl Original Solutionl Filter Entryl Priority Queuel Edge Representationl Vertex Representationl Vertex Representation (2)l Building the Graphl Building the Graph (2)l Running Dijkstral Boost Graph Library Solutionl Codel Code (2)
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 44/48
Running Dijkstra
1 void Graph : : shor tes tPaths ( ) {
2 Vertex∗ from = m_vert ices [ m_from ] ;
3 i f ( ! from ) return ;
4 from−>setKey ( 0 ) ;
5 Pr ior i tyQueue <Vertex > queue ( m_vert ices ) ;
6 while ( ! queue . isEmpty ( ) ) {
7 Vertex ∗min = queue . extractMinimum ( ) ;
8 / / Did we al ready r e l a x a l l connected v e r t i c e s ?
9 i f ( min−>key ( ) == UINT_MAX ) break ;
10 min−>r e l a x V e r t i c e s ( queue ) ;
11 }
12 m_graphValid = true ;
13 }
14 void Vertex : : r e l a x V e r t i c e s ( Pr ior i tyQueue <Vertex >& queue ) {
15 for ( Edge ∗e = m_edges . f i r s t ( ) ; e ; e = m_edges . next ( ) ) e−>r e l a x ( this , queue ) ;
16 }
17 void Edge : : r e l a x ( const Vertex∗ predecessor , Pr ior i tyQueue <Vertex>& queue ) {
18 i f ( ! m_vertex | | ! predecessor | | ! m _ f i l t e r E n t r y )
19 return ;
20 i f ( m_vertex−>setKey ( predecessor−>key ( ) + m _ f i l t e r E n t r y−>weight ) ) {
21 queue . keyDecreased ( m_vertex ) ; / / main ta in the heap proper ty
22 m_vertex−>setPredecessor ( predecessor ) ;
23 }
24 }
Introduction
The Boost Graph Library
Demol Taskl Original Solutionl Filter Entryl Priority Queuel Edge Representationl Vertex Representationl Vertex Representation (2)l Building the Graphl Building the Graph (2)l Running Dijkstral Boost Graph Library Solutionl Codel Code (2)
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 45/48
Boost Graph Library Solution
n To decouple it from KOfficeu Input: Graphviz[8] dot fileu Output: plain string
n About 50 lines of “real” coden Uses dijkstra_shortest_paths to create a predecessor
map
application/x-kspread
text/html
text/plain
application/x-kword
application/msword
Introduction
The Boost Graph Library
Demol Taskl Original Solutionl Filter Entryl Priority Queuel Edge Representationl Vertex Representationl Vertex Representation (2)l Building the Graphl Building the Graph (2)l Running Dijkstral Boost Graph Library Solutionl Codel Code (2)
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 46/48
Code
1 using namespace boost ;
2 GraphvizDigraph g_dot ;
3 read_graphviz ( argv [ 1 ] , g_dot ) ;
4 typedef a d j a c e n c y _ l i s t < vecS , vecS , di rectedS , no_property ,
5 proper ty < edge_weight_t , i n t > > Graph ;
6 typedef g r a p h _ t r a i t s < Graph > : : v e r t e x _ d e s c r i p t o r v e r t e x _ d e s c r i p t o r ;
7
8 Graph g ( num_vert ices ( g_dot ) ) ;
9 property_map < GraphvizDigraph , e d g e _ a t t r i b u t e _ t > : : type edge_attr_map = get ( edge_a t t r i bu te , g_dot ) ;
10 g r a p h _ t r a i t s < GraphvizDigraph > : : e d g e _ i t e r a t o r ei , ei_end ;
11 for ( t i e ( e i , ei_end ) = edges ( g_dot ) ; e i != ei_end ; ++ e i ) {
12 i n t weight = l e x i c a l _ c a s t < i n t >( edge_attr_map[∗ e i ] [ " l a b e l " ] ) ;
13 proper ty < edge_weight_t , i n t >edge_property ( weight ) ;
14 add_edge ( source ( ∗ei , g_dot ) , t a r g e t ( ∗ei , g_dot ) , edge_property , g ) ;
15 }
16 v e r t e x _ d e s c r i p t o r msword ;
17 property_map < GraphvizDigraph , v e r t e x _ a t t r i b u t e _ t > : : type ver tex_at t r_map=get ( v e r t e x _ a t t r i b u t e , g_dot ) ;
18 g r a p h _ t r a i t s < GraphvizDigraph > : : v e r t e x _ i t e r a t o r v i , vi_end ;
19 for ( t i e ( v i , vi_end ) = v e r t i c e s ( g_dot ) ; v i != vi_end ; ++ v i )
20 i f ( SOURCE == ver tex_at t r_map[∗ v i ] [ " l a b e l " ] ) {
21 msword = ∗v i ;
22 break ;
23 }
24 . . .
Introduction
The Boost Graph Library
Demol Taskl Original Solutionl Filter Entryl Priority Queuel Edge Representationl Vertex Representationl Vertex Representation (2)l Building the Graphl Building the Graph (2)l Running Dijkstral Boost Graph Library Solutionl Codel Code (2)
References
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 47/48
Code (2)
1 std : : vec to r < v e r t e x _ d e s c r i p t o r > parent ( num_vert ices ( g ) ) ;
2 / / A l l v e r t i c e s s t a r t out as t h e i r own parent
3 typedef g r a p h _ t r a i t s < Graph > : : v e r t i c e s _ s i z e _ t y p e s ize_type ;
4 const s ize_type num = num_vert ices ( g ) ;
5 for ( s ize_type p = 0 ; p < num; ++p )
6 parent [ p ] = p ;
7
8 d i j k s t r a _ s h o r t e s t _ p a t h s ( g , msword , predecessor_map ( &parent [ 0 ] ) ) ;
9
10 v e r t e x _ d e s c r i p t o r html ;
11 for ( t i e ( v i , vi_end ) = v e r t i c e s ( g_dot ) ; v i != vi_end ; ++ v i )
12 i f ( DESTINATION == ver tex_at t r_map[∗ v i ] [ " l a b e l " ] ) {
13 html = ∗v i ;
14 break ;
15 }
16 v e r t e x _ d e s c r i p t o r c u r r e n t = html ;
17 std : : vector <s td : : s t r i n g > path ;
18 while ( parent [ c u r r e n t ] != c u r r e n t ) {
19 c u r r e n t = parent [ c u r r e n t ] ;
20 path . push_back ( ver tex_at t r_map [ c u r r e n t ] [ " l a b e l " ] ) ;
21 }
22 std : : cout << " Shor tes t path from " << SOURCE << " to " << DESTINATION << " : \ n " ;
23 std : : copy ( path . rbeg in ( ) , path . rend ( ) , s td : : os t ream_ i te ra to r <s td : : s t r i n g >( s td : : cout , " −> " ) ) ;
24 std : : cout << ver tex_at t r_map [ html ] [ " l a b e l " ] << " \ n " ;
Introduction
The Boost Graph Library
Demo
Referencesl
Werner Trobin, May 26, 2004 The Boost Graph Library - p. 48/48
References
[1] The C++ Boost Library, http://www.boost.org/
[2] Boost Software License, http://www.boost.org/more/license_info.html
[3] Compiler Status Summary, http://boost.sourceforge.net/regression-logs/
[4] Matrix Template Library, http://www.osl.iu.edu/research/mtl/
[5] Kühl, Dietmar; Weihe, Karsten. 1996. Using Design Patterns for Reusable, Efficient Implementations of GraphAlgorithms. Konstanzer Schriften in Mathematik und Informatik, Nr.1, Jannuar 1996. Fakultät für Mathematik undInformatik, Universität Konstanz.
[6] Siek, Jeremy G.; Lee, Lie-Quan; Lumsdaine, Andrew; 2001. Boost Graph Library, The: User Guide and ReferenceManual. Addison Wesley Professional.
[7] KOffice, http://www.koffice.org/
[8] Graphviz, http://www.research.att.com/sw/tools/graphviz/
[9] LEDA, http://www.algorithmic-solutions.com/
[10] Knuth, Donald E. 1993. The Stanford GraphBase: A Platform for Combinatorial Computing. Addison Wesley Pub Co.
[11] Musser, David R.; Stepanov, Alexander A. 1987. A library of generic algorithms in Ada. Proc. of 1997 ACM SIGAdaInternational Conference, ACM Press, New York.