├── .gitignore
├── Exam
├── Ecrit RO_2016_juin_INT.pdf
├── Ecrit RO_2018_juin_INT.pdf
├── Ecrit RO_2019_avril_INT.pdf
└── Tex
│ ├── Ecrit RO_2016_juin_INT.tex
│ ├── Ecrit RO_2018_juin_INT.pdf
│ ├── Ecrit RO_2018_juin_INT.tex
│ └── Ecrit RO_2019_avril_INT.tex
├── Exercises
├── Exercises_OR_2016_INT.pdf
└── Tex
│ └── Exercises_OR_2016_INT.tex
├── LICENSE
├── Notebooks
├── .ipynb_checkpoints
│ └── graphsTraversals-checkpoint.ipynb
├── algopy
│ ├── README.md
│ ├── __init__.py
│ ├── docs
│ │ ├── Makefile
│ │ ├── conf.py
│ │ ├── conventions_and_rules.rst
│ │ ├── index.rst
│ │ ├── make.bat
│ │ └── modules.rst
│ ├── exception.py
│ ├── flycheck_tree.py
│ ├── graph.py
│ ├── graphmat.py
│ ├── queue.py
│ ├── spanning_forest.py
│ ├── stack.py
│ ├── tests
│ │ ├── __init__.py
│ │ ├── test_queue.py
│ │ └── test_stack.py
│ └── tree.py
└── graphsTraversals.ipynb
├── README.md
└── Slides
├── Tex
├── Style
│ ├── Mimo_Ionis.sty~
│ ├── My_Beamer.sty
│ ├── My_Beamer.sty~
│ ├── Mystyle.sty
│ └── Mystyle.sty~
├── fixingGraphTheoreticalTerminology.tex
├── maximumFlow.tex
├── projectPlanning.tex
├── shortestPath.tex
└── transportationProblems.tex
├── fixingGraphTheoreticalTerminology.pdf
├── maximumFlow.pdf
├── projectPlanning.pdf
├── shortestPath.pdf
└── transportationProblems.pdf
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Core latex/pdflatex auxiliary files:
2 | *.aux
3 | *.lof
4 | *.log
5 | *.lot
6 | *.fls
7 | *.out
8 | *.toc
9 | *.fmt
10 | *.fot
11 | *.cb
12 | *.cb2
13 |
14 | ## Intermediate documents:
15 | *.dvi
16 | *-converted-to.*
17 | # these rules might exclude image files for figures etc.
18 | # *.ps
19 | # *.eps
20 | # *.pdf
21 |
22 | ## Generated if empty string is given at "Please type another file name for output:"
23 | .pdf
24 |
25 | ## Bibliography auxiliary files (bibtex/biblatex/biber):
26 | *.bbl
27 | *.bcf
28 | *.blg
29 | *-blx.aux
30 | *-blx.bib
31 | *.run.xml
32 |
33 | ## Build tool auxiliary files:
34 | *.fdb_latexmk
35 | *.synctex
36 | *.synctex(busy)
37 | *.synctex.gz
38 | *.synctex.gz(busy)
39 | *.pdfsync
40 |
41 | ## Auxiliary and intermediate files from other packages:
42 | # algorithms
43 | *.alg
44 | *.loa
45 |
46 | # achemso
47 | acs-*.bib
48 |
49 | # amsthm
50 | *.thm
51 |
52 | # beamer
53 | *.nav
54 | *.pre
55 | *.snm
56 | *.vrb
57 |
58 | # changes
59 | *.soc
60 |
61 | # cprotect
62 | *.cpt
63 |
64 | # elsarticle (documentclass of Elsevier journals)
65 | *.spl
66 |
67 | # endnotes
68 | *.ent
69 |
70 | # fixme
71 | *.lox
72 |
73 | # feynmf/feynmp
74 | *.mf
75 | *.mp
76 | *.t[1-9]
77 | *.t[1-9][0-9]
78 | *.tfm
79 |
80 | #(r)(e)ledmac/(r)(e)ledpar
81 | *.end
82 | *.?end
83 | *.[1-9]
84 | *.[1-9][0-9]
85 | *.[1-9][0-9][0-9]
86 | *.[1-9]R
87 | *.[1-9][0-9]R
88 | *.[1-9][0-9][0-9]R
89 | *.eledsec[1-9]
90 | *.eledsec[1-9]R
91 | *.eledsec[1-9][0-9]
92 | *.eledsec[1-9][0-9]R
93 | *.eledsec[1-9][0-9][0-9]
94 | *.eledsec[1-9][0-9][0-9]R
95 |
96 | # glossaries
97 | *.acn
98 | *.acr
99 | *.glg
100 | *.glo
101 | *.gls
102 | *.glsdefs
103 |
104 | # gnuplottex
105 | *-gnuplottex-*
106 |
107 | # gregoriotex
108 | *.gaux
109 | *.gtex
110 |
111 | # hyperref
112 | *.brf
113 |
114 | # knitr
115 | *-concordance.tex
116 | # TODO Comment the next line if you want to keep your tikz graphics files
117 | *.tikz
118 | *-tikzDictionary
119 |
120 | # listings
121 | *.lol
122 |
123 | # makeidx
124 | *.idx
125 | *.ilg
126 | *.ind
127 | *.ist
128 |
129 | # minitoc
130 | *.maf
131 | *.mlf
132 | *.mlt
133 | *.mtc[0-9]*
134 | *.slf[0-9]*
135 | *.slt[0-9]*
136 | *.stc[0-9]*
137 |
138 | # minted
139 | _minted*
140 | *.pyg
141 |
142 | # morewrites
143 | *.mw
144 |
145 | # nomencl
146 | *.nlo
147 |
148 | # pax
149 | *.pax
150 |
151 | # pdfpcnotes
152 | *.pdfpc
153 |
154 | # sagetex
155 | *.sagetex.sage
156 | *.sagetex.py
157 | *.sagetex.scmd
158 |
159 | # scrwfile
160 | *.wrt
161 |
162 | # sympy
163 | *.sout
164 | *.sympy
165 | sympy-plots-for-*.tex/
166 |
167 | # pdfcomment
168 | *.upa
169 | *.upb
170 |
171 | # pythontex
172 | *.pytxcode
173 | pythontex-files-*/
174 |
175 | # thmtools
176 | *.loe
177 |
178 | # TikZ & PGF
179 | *.dpth
180 | *.md5
181 | *.auxlock
182 |
183 | # todonotes
184 | *.tdo
185 |
186 | # easy-todo
187 | *.lod
188 |
189 | # xindy
190 | *.xdy
191 |
192 | # xypic precompiled matrices
193 | *.xyc
194 |
195 | # endfloat
196 | *.ttt
197 | *.fff
198 |
199 | # Latexian
200 | TSWLatexianTemp*
201 |
202 | ## Editors:
203 | # WinEdt
204 | *.bak
205 | *.sav
206 |
207 | # Texpad
208 | .texpadtmp
209 |
210 | # Kile
211 | *.backup
212 |
213 | # KBibTeX
214 | *~[0-9]*
215 |
216 | # auto folder when using emacs and auctex
217 | *auto/*
218 |
219 | # expex forward references with \gathertags
220 | *-tags.tex
221 |
222 | # MacOS back up folders
223 | *.DS_Store
224 |
225 | # Emacs temps files
226 | *~
227 | *.el
228 |
229 | # Jupyter temporary folders
230 | *ipynb_checkpoints/*
231 |
232 | #
--------------------------------------------------------------------------------
/Exam/Ecrit RO_2016_juin_INT.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bashardudin/GraphsAndFlows/afdf1d1c60d54abec7484fbaa1b473b9d3d0894b/Exam/Ecrit RO_2016_juin_INT.pdf
--------------------------------------------------------------------------------
/Exam/Ecrit RO_2018_juin_INT.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bashardudin/GraphsAndFlows/afdf1d1c60d54abec7484fbaa1b473b9d3d0894b/Exam/Ecrit RO_2018_juin_INT.pdf
--------------------------------------------------------------------------------
/Exam/Ecrit RO_2019_avril_INT.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bashardudin/GraphsAndFlows/afdf1d1c60d54abec7484fbaa1b473b9d3d0894b/Exam/Ecrit RO_2019_avril_INT.pdf
--------------------------------------------------------------------------------
/Exam/Tex/Ecrit RO_2016_juin_INT.tex:
--------------------------------------------------------------------------------
1 | \documentclass[12pt,a4paper]{article}
2 | \usepackage[utf8]{inputenc}
3 | \usepackage[T1]{fontenc}
4 | \usepackage[english]{babel}
5 | \usepackage{fancyhdr}
6 | \usepackage{kpfonts}
7 | \usepackage[margin=1in]{geometry}
8 | \usepackage{exsheets}
9 | \usepackage{amsmath, amssymb, amsfonts}
10 | \usepackage{enumerate}
11 | \usepackage{tikz}
12 | \usetikzlibrary{arrows, decorations.text}
13 |
14 | \pagestyle{fancy}
15 | \renewcommand{\headrulewidth}{2pt}
16 | \fancyhead[L]{EPITA\_ING1\_BING\_2018\_S6\_PARTIEL\_GREF}
17 | \fancyhead[R]{June 2017}
18 |
19 | \fancyfoot[C]{\textbf{\thepage}}
20 | \fancyfoot[L]{}
21 |
22 | \SetupExSheets{solution/print=true}
23 | \SetupExSheets{question/type=exam}
24 | \SetupExSheets[points]{name=point,name-plural=points}
25 | \RenewQuSolPair{question}[name={\large Exercise}]{solution}
26 |
27 | \begin{document}
28 | \begin{center}
29 |
30 | {\Large \textbf{Networks and Flows on Graphs\footnote{Head of course : P.~Siarry.}}}\\
31 |
32 | \vspace{10pt}
33 | {\Large \textit{Final Exam}}
34 |
35 | \vspace{2\baselineskip}
36 | \end{center}
37 | \begin{center}
38 | \begin{minipage}{\textwidth}
39 | Duration of the exam : 1h30\\
40 | No documents are allowed\\
41 | Only \emph{non-programmable} pocket calculators are allowed\\
42 | Exercises can be done independently.
43 | \end{minipage}
44 | \end{center}
45 | \rule{\textwidth}{2pt}
46 |
47 |
48 | \vspace{\baselineskip}
49 |
50 | \begin{question}
51 | Applying Ford's algorithm compute the lengths of shortests paths
52 | linking vertex $a$ to any other vertex in the following graph:
53 | \vspace{2\baselineskip}
54 | \begin{center}
55 | \begin{tikzpicture}
56 | [minimum width={width("b")+1.5em},
57 | vertex/.style={circle, draw=black, fill=white, thick},
58 | arr/.style={->,>=stealth',semithick},
59 | scale=1.2]
60 | \node (f) at (13.5, 4.5) [vertex] {$f$};
61 | \node (i) at (11.5, 2) [vertex] {$i$}
62 | edge[arr] node[right] {$5$} (f);
63 | \node (j) at (7.5, 1) [vertex] {$j$}
64 | edge[arr] node[below] {$9$} (i)
65 | edge[arr] node[below] {$1$} (f);
66 | \node (h) at (9, 4.5) [vertex] {$h$}
67 | edge[arr] node[above] {$10$} (f)
68 | edge[arr] node[above] {$4$} (i)
69 | edge[arr] node[right] {$8$} (j);
70 | \node (d) at (11.5, 6.5) [vertex] {$d$}
71 | edge[arr] node[right] {$8$} (f)
72 | edge[arr] node[above] {$4$} (h);
73 | \node (g) at (7.5, 7) [vertex] {$g$}
74 | edge[arr] node[left] {$2$} (h)
75 | edge[arr] node[above] {$5$} (d);
76 | \node (e) at (2.5, 1) [vertex] {$e$}
77 | edge[arr] node[below] {$5$} (j);
78 | \node (c) at (5.5, 2.5) [vertex] {$c$}
79 | edge[arr] node[below] {$1$} (e)
80 | edge[arr] node[above] {$2$} (j)
81 | edge[arr] node[below] {$1$} (h);
82 | \node (b) at (4, 7) [vertex] {$b$}
83 | edge[arr] node[above] {$1$} (g);
84 | \node (l) at (6, 4.5) [vertex] {$l$}
85 | edge[arr] node[above] {$12$} (h)
86 | edge[arr] node[right] {$6$} (b);
87 | \node (k) at (3, 3.5) [vertex] {$k$}
88 | edge[arr] node[below] {$3$} (c)
89 | edge[arr] node[right] {$8$} (e)
90 | edge[arr] node[below] {$5$} (l);
91 | \node (a) at (1, 4.5) [vertex] {$a$}
92 | edge[arr] node[above] {$2$} (b)
93 | edge[arr] node[above] {$10$} (l)
94 | edge[arr] node[below] {$7$} (k)
95 | edge[arr] node[left] {$13$} (e);
96 | \path (g) edge[arr] node[left] {$3$} (l);
97 | \end{tikzpicture}
98 | \end{center}
99 | \vspace{2\baselineskip}
100 | \end{question}
101 |
102 | \begin{question}
103 | You're in charge of a construction project. Details and duration of
104 | tasks of each trade are summed up in the table below. Each labeled
105 | task comes with the list of tasks \emph{immediatly} preceding its
106 | start.
107 | \vspace{2\baselineskip}
108 | \begin{center}
109 | \renewcommand{\arraystretch}{1.5}
110 | \begin{tabular}{|c|c|c|c|}
111 | \hline
112 | Label of task & Task description & Time (in weeks) & Tasks preceding it \\
113 | \hline
114 | A & Maconry & 12 & -- \\
115 | \hline
116 | B & Framework & 1 & A \\
117 | \hline
118 | C & Zing works & 1 & B \\
119 | \hline
120 | D & Covering & 1 & C \\
121 | \hline
122 | E & Electricity, first stage & 2 & D \\
123 | \hline
124 | F & Sanitary facilities, first stage & 1 & D \\
125 | \hline
126 | G & Glaziery & 1 & D \\
127 | \hline
128 | H & Plastering & 4 & G \\
129 | \hline
130 | I & Sanitary facilites, second stage & 1 & H \\
131 | \hline
132 | J & Electricity, second stage & 1 & H \\
133 | \hline
134 | K & Tiling & 6 & I, J \\
135 | \hline
136 | L & Shutters & 1 & I \\
137 | \hline
138 | M & Inside carpentry & 2 & L \\
139 | \hline
140 | N & Ironmongery & 1 & L \\
141 | \hline
142 | \end{tabular}
143 | \end{center}
144 | \vspace{\baselineskip}
145 | \begin{enumerate}
146 | \item Draw the MPM (Meta Potential Model) graph of this project
147 | planning problem.
148 | \item Using relevant algorithms, give earliest scheduling dates.
149 | \begin{itemize}
150 | \item What is the minimum amount of time the project needs to be done?
151 | \item What are the critical tasks?
152 | \end{itemize}
153 | \item Using relevant algorithms, give latest scheduling dates.
154 | \begin{itemize}
155 | \item What is the total margin of the project? Compute free
156 | margins of non-critical tasks?
157 | \end{itemize}
158 | \end{enumerate}
159 | \end{question}
160 | \end{document}
161 |
162 | %%% Local Variables:
163 | %%% mode: latex
164 | %%% TeX-master: t
165 | %%% End:
166 |
--------------------------------------------------------------------------------
/Exam/Tex/Ecrit RO_2018_juin_INT.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bashardudin/GraphsAndFlows/afdf1d1c60d54abec7484fbaa1b473b9d3d0894b/Exam/Tex/Ecrit RO_2018_juin_INT.pdf
--------------------------------------------------------------------------------
/Exam/Tex/Ecrit RO_2018_juin_INT.tex:
--------------------------------------------------------------------------------
1 | \documentclass[12pt,a4paper]{article}
2 | \usepackage[utf8]{inputenc}
3 | \usepackage[T1]{fontenc}
4 | \usepackage[english]{babel}
5 | \usepackage{fancyhdr}
6 | \usepackage{kpfonts}
7 | \usepackage[margin=1in]{geometry}
8 | \usepackage{exsheets}
9 | \usepackage{amsmath, amssymb, amsfonts}
10 | \usepackage{enumerate}
11 | \usepackage{tikz}
12 | \usepackage{tabularx}
13 | \usetikzlibrary{arrows, decorations.text}
14 |
15 | \pagestyle{fancy}
16 | \renewcommand{\headrulewidth}{2pt}
17 | \fancyhead[L]{EPITA\_ING1\_BING\_2020\_S6\_PARTIEL\_GREF}
18 | \fancyhead[R]{June 2018}
19 |
20 | \fancyfoot[C]{\textbf{\thepage}}
21 | \fancyfoot[L]{}
22 |
23 | \SetupExSheets{solution/print=true}
24 | \SetupExSheets{question/type=exam}
25 | \SetupExSheets[points]{name=point,name-plural=points}
26 | \RenewQuSolPair{question}[name={\large Exercise}]{solution}
27 |
28 | \begin{document}
29 | \begin{center}
30 |
31 | {\Large \textbf{Networks and Flows on Graphs\footnote{Head of course : P.~Siarry.}}}\\
32 |
33 | \vspace{10pt}
34 | {\Large \textit{Final Exam}}
35 |
36 | \vspace{2\baselineskip}
37 | \end{center}
38 | \begin{center}
39 | \begin{minipage}{\textwidth}
40 | Duration of the exam : 1h30\\
41 | No documents are allowed\\
42 | Only \emph{non-programmable} pocket calculators are allowed\\
43 | Exercises can be done independently.
44 | \end{minipage}
45 | \end{center}
46 | \rule{\textwidth}{2pt}
47 |
48 |
49 | \vspace{\baselineskip}
50 |
51 | \begin{question}
52 | Exploiting a newly found mineral deposit involves the execution of
53 | hereby listed tasks. Table features each tasks identifier,
54 | description, duration and prior tasks.
55 |
56 | \vspace{2\baselineskip}
57 | \begin{center}
58 | \renewcommand{\arraystretch}{1.5}
59 | \begin{tabularx}{\textwidth}{|c|p{6.75cm}|c|c|}
60 | \hline
61 | Label of task & Task description & Time (in weeks) & Prior Tasks\\
62 | \hline
63 | A & Obtainging construction permit & 120 & -- \\
64 | \hline
65 | B & Setting up a 6 km track & 180 & A \\
66 | \hline
67 | C & Installation of two drill machines & 3 & B \\
68 | \hline
69 | D & Setting temporary offices for mapping team and lodging for drilling one & 30 & B \\
70 | \hline
71 | E & Tarmac the track & 60 & B \\
72 | \hline
73 | F & Water conveyance & 90 & D \\
74 | \hline
75 | G & Probing phase & 240 & C, D \\
76 | \hline
77 | H & Drilling and equipping three wells & 180 & E, F, G \\
78 | \hline
79 | I & Installing exploiting equipment down the wells & 30 & J, H \\
80 | \hline
81 | J & Setting up pemanent offices and lodgings for engineers and workers & 240 & E, F, G \\
82 | \hline
83 | K & Tracing and layout of galleries & 360 & J, H \\
84 | \hline
85 | L & Setting up washing system & 240 & J, H \\
86 | \hline
87 | \end{tabularx}
88 | \end{center}
89 | \vspace{\baselineskip}
90 | \begin{enumerate}
91 | \item Draw the MPM (Meta Potential Model) graph of this project
92 | planning problem.
93 | \item Using relevant algorithms, give earliest scheduling dates.
94 | \begin{itemize}
95 | \item What is the minimum amount of time the project needs to be done?
96 | \item What are the critical tasks?
97 | \end{itemize}
98 | \item Using relevant algorithms, give latest scheduling dates.
99 | \begin{itemize}
100 | \item What is the total margin of the project? Compute free
101 | margins of non-critical tasks?
102 | \end{itemize}
103 | \end{enumerate}
104 | \end{question}
105 | \begin{question}
106 | Using Floyd-Warshall's algorithm, compute all minimal paths between
107 | any two pairs of vertices of the following graph. Could we look for
108 | all maximal paths between any such pairs? \vspace{2\baselineskip}
109 | \begin{center}
110 | \begin{tikzpicture}
111 | [minimum width={width("b")+1.5em},
112 | vertex/.style={circle, draw=black, fill=white, thick},
113 | arr/.style={->,>=stealth',semithick},
114 | scale=1.2]
115 | \node (E) at (10, 5) [vertex] {$E$};
116 | \node (D) at (4, 4) [vertex] {$D$}
117 | edge[arr] node[below] {$3$} (E);
118 | \node (B) at (7, 6.5) [vertex] {$B$}
119 | edge[arr] node[above] {$5$} (E)
120 | edge[arr] node[right] {$-2$} (D);
121 | \node (C) at (4, 8) [vertex] {$C$}
122 | edge[arr, bend right] node[left] {$-1$} (D)
123 | edge[arr] node[above] {$2$} (B);
124 | \node (A) at (1, 6) [vertex] {$A$}
125 | edge[arr] node[above] {$3$} (C)
126 | edge[arr] node[below] {$2$} (D);
127 | \path (D) edge[arr, bend right] node[right] {$2$} (C);
128 | \end{tikzpicture}
129 | \end{center}
130 | \vspace{2\baselineskip}
131 | \end{question}
132 | \end{document}
133 |
134 | %%% Local Variables:
135 | %%% mode: latex
136 | %%% TeX-master: t
137 | %%% End:
138 |
--------------------------------------------------------------------------------
/Exam/Tex/Ecrit RO_2019_avril_INT.tex:
--------------------------------------------------------------------------------
1 | \documentclass[12pt,a4paper]{article}
2 | \usepackage[utf8]{inputenc}
3 | \usepackage[T1]{fontenc}
4 | \usepackage[english]{babel}
5 | \usepackage{fancyhdr}
6 | \usepackage{kpfonts}
7 | \usepackage[margin=1in]{geometry}
8 | \usepackage{exsheets}
9 | \usepackage{amsmath, amssymb, amsfonts}
10 | \usepackage{enumerate}
11 | \usepackage{tikz}
12 | \usepackage{tabularx}
13 | \usetikzlibrary{arrows, decorations.text}
14 |
15 | \pagestyle{fancy}
16 | \renewcommand{\headrulewidth}{2pt}
17 | \fancyhead[L]{EPITA\_ING1\_BING\_2021\_S6\_PARTIEL\_GREF}
18 | \fancyhead[R]{April 2019}
19 |
20 | \fancyfoot[C]{\textbf{\thepage}}
21 | \fancyfoot[L]{}
22 |
23 | \SetupExSheets{solution/print=true}
24 | \SetupExSheets{question/type=exam}
25 | \SetupExSheets[points]{name=point,name-plural=points}
26 | \RenewQuSolPair{question}[name={\large Exercise}]{solution}
27 |
28 | \begin{document}
29 | \begin{center}
30 |
31 | {\Large \textbf{Networks and Flows on Graphs\footnote{Head of course : P.~Siarry.}}}\\
32 |
33 | \vspace{10pt}
34 | {\Large \textit{Final Exam}}
35 |
36 | \vspace{2\baselineskip}
37 | \end{center}
38 | \begin{center}
39 | \begin{minipage}{\textwidth}
40 | Duration of the exam : 1h30\\
41 | No documents are allowed\\
42 | Only \emph{non-programmable} pocket calculators are allowed\\
43 | Exercises can be done independently.
44 | \end{minipage}
45 | \end{center}
46 | \rule{\textwidth}{2pt}
47 |
48 | \vspace{\baselineskip}
49 |
50 | \begin{question}
51 | Using Floyd-Warshall's algorithm, compute all minimal paths between
52 | any two pairs of vertices of the following graph. Could we look for
53 | all maximal paths between any such pairs? \vspace{2\baselineskip}
54 | \begin{center}
55 | \begin{tikzpicture}
56 | [minimum width={width("b")+1.5em},
57 | vertex/.style={circle, draw=black, fill=white, thick},
58 | arr/.style={-,semithick},
59 | scale=1.2]
60 | \node (0) at (0, 0) [vertex] {$0$};
61 | \node (3) at (2, 0) [vertex] {$3$}
62 | edge[arr] (0);
63 | \node (6) at (1, 1) [vertex] {$6$}
64 | edge[arr] (0)
65 | edge[arr] (3);
66 | \node (1) at (3, 0) [vertex] {$1$};
67 | \node (4) at (5, 0) [vertex] {$4$}
68 | edge[arr] (1);
69 | \node (7) at (4, 4) [vertex] {$7$}
70 | edge[arr] (1)
71 | edge[arr] (4);
72 | \node (2) at (6, 0) [vertex] {$2$};
73 | \node (5) at (8, 0) [vertex] {$5$}
74 | edge[arr] (2);
75 | \end{tikzpicture}
76 | \end{center}
77 | \vspace{2\baselineskip}
78 | \end{question}
79 |
80 | \begin{question}
81 | A project is described by the following dependancy table
82 | \begin{center}
83 | \renewcommand{\arraystretch}{1.5}
84 | \begin{tabularx}{.825\textwidth}{|c|p{6.75cm}|c|}
85 | \hline
86 | Label of task & Requirements before task starts & Time (in days) \\
87 | \hline
88 | A & & $10$ \\
89 | \hline
90 | B & & $15$ \\
91 | \hline
92 | C & A finished, B finished since $3$ days & $11$ \\
93 | \hline
94 | D & A finished since $7$ days & $7$ \\
95 | \hline
96 | E & A started since $16$ days, B finished & $9$ \\
97 | \hline
98 | F & B finished since $2$ days & $14$ \\
99 | \hline
100 | G & D finished, C finished since $1$ day & $7$ \\
101 | \hline
102 | H & E finished & $12$ \\
103 | \hline
104 | I & E finished since $6$ days & $8$ \\
105 | \hline
106 | \end{tabularx}
107 | \end{center}
108 | \vspace{\baselineskip}
109 | \begin{enumerate}
110 | \item Draw the MPM (Meta Potential Model) graph of this project
111 | planning problem.
112 | \item Using relevant algorithms, give earliest scheduling dates.
113 | \begin{itemize}
114 | \item What is the minimum amount of time the project needs to be done?
115 | \item What are the critical tasks?
116 | \item Represent project scheduling as a Gantt diagram.
117 | \end{itemize}
118 | \item Using relevant algorithms, give latest scheduling dates.
119 | \begin{itemize}
120 | \item Compute margins and free margins of non-critical tasks?
121 | \end{itemize}
122 | \end{enumerate}
123 | \end{question}
124 |
125 | \end{document}
126 |
127 | %%% Local Variables:
128 | %%% mode: latex
129 | %%% TeX-master: t
130 | %%% End:
131 |
--------------------------------------------------------------------------------
/Exercises/Exercises_OR_2016_INT.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bashardudin/GraphsAndFlows/afdf1d1c60d54abec7484fbaa1b473b9d3d0894b/Exercises/Exercises_OR_2016_INT.pdf
--------------------------------------------------------------------------------
/Exercises/Tex/Exercises_OR_2016_INT.tex:
--------------------------------------------------------------------------------
1 | \documentclass[11pt,a4paper]{article}
2 | \usepackage[utf8]{inputenc}
3 | \usepackage[T1]{fontenc}
4 | \usepackage[english]{babel}
5 | \usepackage{fancyhdr}
6 | \usepackage{kpfonts}
7 | \usepackage[margin=.8in]{geometry}
8 | \usepackage{exsheets}
9 | \usepackage{amsmath, amssymb, amsfonts}
10 | \usepackage{enumerate}
11 | \usepackage{tikz}
12 | \usetikzlibrary{arrows, decorations.text}
13 |
14 | \pagestyle{fancy}
15 | \renewcommand{\headrulewidth}{2pt}
16 | \fancyhead[L]{Epita - BING}
17 | \fancyhead[R]{2016}
18 |
19 | \fancyfoot[C]{\textbf{\thepage}}
20 | \fancyfoot[L]{}
21 |
22 | \SetupExSheets{subtitle-format = \Large\scshape}
23 | \SetupExSheets{headings-format = \large\bfseries}
24 | \SetupExSheets{headings = block-subtitle}
25 | \SetupExSheets{solution/print=true}
26 | \SetupExSheets{question/type=exam}
27 | \RenewQuSolPair{question}[name={\large Exercise}]{solution}
28 |
29 | \begin{document}
30 | \begin{center}
31 | {\Large \textbf{Networks and Flows on Graphs}}\\
32 | \vspace{10pt}
33 | {\Large \textit{Exercise Sheet}}
34 | \end{center}
35 | \rule{\textwidth}{2pt}
36 | \vspace{\baselineskip}
37 |
38 | \section{Basics on Graphs}
39 |
40 | \begin{question}[subtitle={Adjacency and Incidence Matrices}]
41 | Let $M$ be the matrix
42 | \[
43 | M = \begin{pmatrix}
44 | 0 & 1 & 0 & 1 & 0 \\
45 | 0 & 0 & 1 & 0 & 0 \\
46 | 0 & 0 & 0 & 0 & 1 \\
47 | 0 & 0 & 1 & 0 & 1 \\
48 | 0 & 0 & 0 & 0 & 0
49 | \end{pmatrix}
50 | \]
51 | representing a graph $G$ having vertices $A$, $B$, $C$, $D$, $E$.
52 | \begin{enumerate}
53 | \item Draw the graph having adacency matrix $M$.
54 | \item What is the incidency matrix of $G$?
55 | \item Compute $M^2$, $M^3$ and $M^4$. Can you tell what non-zero
56 | coefficients correspond to?
57 | \item Knowing that $M^{[k]}$ is the $k$-th boolean power of $M$,
58 | compute $M^{[2]}$, $M^{[3]}$ and $M^{[4]}$. Can you give a meaning
59 | to these matrices?
60 | \item Compute
61 | $A = I \oplus M \oplus M^{[2]} \oplus M^{[3]} \oplus M^{[4]}$,
62 | where $\oplus$ is the boolean sum. What does $A$ stand for?
63 | \end{enumerate}
64 | \end{question}
65 |
66 | \begin{question}[subtitle={Degrees and Cycles}]
67 | Consider the following graph, subsequently named $G$:
68 | \begin{center}
69 | \begin{tikzpicture}
70 | [minimum width={width("b")+1.5em},
71 | vertex/.style={circle, draw=black, fill=white, thick},
72 | arr/.style={->,>=stealth',semithick}]
73 | \node (C) at (7, 3.5) [vertex] {$C$};
74 | \node (A) at (3, 6) [vertex] {$A$};
75 | \node (F) at (0, 5) [vertex] {$F$}
76 | edge[arr, bend left=15] (A)
77 | edge[arr] (C);
78 | \node (E) at (0, 3) [vertex] {$E$}
79 | edge[arr, bend left=15] (F)
80 | edge[loop below, semithick, >=stealth'] (E);
81 | \node (B) at (6, 5.5) [vertex] {$B$}
82 | edge[arr, bend left] (A)
83 | edge[loop above, semithick, >=stealth'] (B)
84 | edge[arr, bend left=15] (C)
85 | edge[arr, bend left=15] (E);
86 | \node (D) at (3, 2.5) [vertex] {$D$}
87 | edge[arr] (B)
88 | edge[arr, bend left=15] (C)
89 | edge[arr, bend left=15] (E);
90 | \path (C) edge[arr, bend left=15] (D);
91 | \path (A) edge[arr, bend left=15] (F);
92 | \path (A) edge[arr, bend left=15] (B);
93 | \path (E) edge[arr, bend left=15] (B);
94 | \end{tikzpicture}
95 | \end{center}
96 | \begin{enumerate}
97 | \item Compute inner and outer degrees of each one of the vertices.
98 | \item Give an example of a simple path which is not elementary.
99 | \item Is there a hamiltonian circuit in $G$?
100 | \item Draw the oriented graph corresponding to $G$.
101 | \item Is $G$ connected? strongly connected?
102 | \end{enumerate}
103 | \end{question}
104 |
105 | \begin{question}[subtitle={Railways}]
106 | Consider the following railway track :
107 | \begin{center}
108 | \begin{tikzpicture}[scale=1.5]
109 | \draw (0,0) circle (1cm);
110 | \draw (2,0) circle (1cm);
111 | \draw (0, -1) -- (2, -1);
112 | \node at (1, -1.2) {$E$};
113 | \node at (.5, -.5) {$B$};
114 | \node at (1.5, -.5) {$C$};
115 | \node at (3, .7) {$D$};
116 | \node at (-1, .7) {$A$};
117 | \end{tikzpicture}
118 | \end{center}
119 | Each cross-point on the railway track has two available
120 | positions. Could you explain why trains will eventually never go
121 | through section $E$? What would happen if we added a section $F$
122 | symmetric to $E$?
123 | \end{question}
124 |
125 | \begin{question}[subtitle={Strongly Connected Components}]
126 | Give the strongly connected components of the following graph :
127 | \begin{center}
128 | \begin{tikzpicture}
129 | [minimum width={width("b")+1.5em},
130 | vertex/.style={circle, draw=black, fill=white, thick},
131 | arr/.style={->,>=stealth',semithick}, scale=1.8]
132 | \node (I) at (4, 1) [vertex] {$I$};
133 | \node (L) at (5, 2) [vertex] {$L$};
134 | \node (K) at (4, 2) [vertex] {$K$}
135 | edge[arr] (L);
136 | \node (J) at (4, 3) [vertex] {$J$}
137 | edge[arr] (K);
138 | \node (G) at (3, 1) [vertex] {$G$}
139 | edge[arr] (I);
140 | \node (F) at (3, 2) [vertex] {$F$}
141 | edge[arr, bend left=20] (G)
142 | edge[arr] (K)
143 | edge[arr] (J);
144 | \node (E) at (3, 3) [vertex] {$E$}
145 | edge[arr] (J)
146 | edge[loop, semithick, >=stealth'] (E);
147 | \node (A) at (0, 2) [vertex] {$A$};
148 | \node (B) at (1, 3) [vertex] {$B$}
149 | edge[arr] (A)
150 | edge[arr] (E);
151 | \node (C) at (2, 2) [vertex] {$C$}
152 | edge[arr] (B)
153 | edge[arr] (F);
154 | \node (D) at (1, 1) [vertex] {$D$}
155 | edge[arr] (C)
156 | edge[arr] (G);
157 | \path (A) edge[arr] (D);
158 | \path (G) edge[arr, bend left=20] (F);
159 | \path (L) edge[arr] (J);
160 | \end{tikzpicture}
161 | \end{center}
162 | \end{question}
163 |
164 | \section{Network Flows}
165 |
166 | \begin{question}[subtitle={Flows}]
167 | Ports $C$, $D$ and $E$ are respectively in need of $9$, $12$ and $7$
168 | containers of a given good $X$. They are connected to ports $A$ and
169 | $B$, which have each $10$ containers of $X$ that are ready to
170 | go. There are currently $4$ shipping routes :
171 | \begin{itemize}
172 | \item from $A$ to $C$ and $A$ to $D$ having respective maximal
173 | shipping capacities of $7$ and $4$ containers ;
174 | \item from $B$ to $C$ and $B$ to $E$ having respective maximal
175 | capacities of $5$ and $5$.
176 | \end{itemize}
177 | \begin{enumerate}
178 | \item Is it possible to satisfy all demands?
179 | \item How can one organise the traffic in order to ensure a maximum
180 | total number of containers? You're expected to start with initial
181 | solution sending $7$ containers through route $AC$. You are to
182 | update initial solution using Ford-Fulkerson algorithm. What is
183 | the mimimum cut corresponding to max flow solution?
184 | \end{enumerate}
185 | \end{question}
186 |
187 | \begin{question}[subtitle={Pairings}]
188 | During a bal, $5$ men and $5$ women are looking forward to
189 | dance. We're given the hard task of mathcing up the highest number
190 | of couples (gender assymetric ones) taking the below compatibility
191 | table
192 | \begin{center}
193 | \renewcommand{\arraystretch}{1.5}
194 | \begin{tabular}{r|c|c|c|c|c}
195 | & Marie & Claire & Suzanne & Anne & Jeanne \\
196 | \hline
197 | Joseph & $\spadesuit$ & $\heartsuit$ & $\spadesuit$ & $\spadesuit$ & $\spadesuit$ \\
198 | \hline
199 | Paul & $\heartsuit$ & $\spadesuit$ & $\spadesuit$ & $\spadesuit$ & $\spadesuit$ \\
200 | \hline
201 | Luc & $\heartsuit$ & $\heartsuit$ & $\spadesuit$ & $\spadesuit$ & $\spadesuit$ \\
202 | \hline
203 | Bernard & $\heartsuit$ & $\heartsuit$ & $\spadesuit$ & $\spadesuit$ & $\heartsuit$ \\
204 | \hline
205 | Francois & $\spadesuit$ & $\spadesuit$ & $\heartsuit$ & $\heartsuit$ & $\heartsuit$ \\
206 | \end{tabular}
207 | \end{center}
208 | \begin{enumerate}
209 | \item What is the graph best representing this matching problem?
210 | \item How can network flows formalism help you solve this matching problem?
211 | \end{enumerate}
212 | \end{question}
213 |
214 |
215 | \section{Optimal Transportation Programs}
216 |
217 | \begin{question}[subtitle={Transportation Program}]
218 | A road transport company has to ship a number of goods out of three
219 | docks $O_1$, $O_2$ and $O_3$ to $4$ destinations $D_1$, $D_2$, $D_3$
220 | and $D_4$. Each dock has $10$ available shipments and the needed
221 | shipments at each destination are $7$, $4$, $14$ and $5$
222 | respectively at $D_1$, $D_2$, $D_3$ and $D_4$. The following table
223 | sums up the costs of each route between a given dock and any
224 | destination
225 | \begin{center}
226 | \renewcommand{\arraystretch}{1.5}
227 | \begin{tabular}{c|c|c|c|c}
228 | & $D_1$ & $D_2$ & $D_3$ & $D_4$ \\
229 | \hline
230 | $O_1$ & 5 & 10 & 11 & 21 \\
231 | \hline
232 | $O_2$ & 6 & 8 & 11 & 2 \\
233 | \hline
234 | $O_3$ & 21 & 12 & 3 & 5 \\
235 | \end{tabular}
236 | \end{center}
237 | The company is looking for the least cost transportation program.
238 | \begin{enumerate}
239 | \item Give a basic solution to this transportation problem using the
240 | Balas-Hammer heuristic. What is the cost of this solution?
241 | \item What is the optimal transportation program? Is the optimum unique?
242 | \item Following improvements on the connection between $O_2$ and
243 | $D_1$, cost to go from $O_2$ to $D_1$ has gone down from $4$ to
244 | $6$. Is the previous solution still optimal? If not find the new
245 | optimal solution.
246 | \end{enumerate}
247 | \end{question}
248 |
249 | \section{Paths Optimisation}
250 |
251 | \begin{question}[subtitle={Along GR $58$}]
252 | At Cervières one can find the map below, it sums the level of
253 | difficulty going through any of the pictured paths. You goal is to
254 | plan the hike to the Queyras where a \emph{fondue} is waiting and a
255 | bottle of \emph{VEP}.
256 |
257 | The total difficulty of a given hike is the sum of difficulties of
258 | each elememtary route.
259 | \begin{enumerate}
260 | \item Using the Ford algorithm compute the easiest hike from
261 | Cervières to any other stop. What is the easiest hike from
262 | Cervières to Queyras?
263 | \item Is the Ford algorithm the best choice one can make to solve
264 | the previous issue, of going from Cervières to Queyras on the
265 | easiest hike. How would you do otherwise?
266 | \item If your aim was to break the record of the toughest hike, what
267 | route would you take?
268 | \end{enumerate}
269 |
270 | \end{question}
271 |
272 | \begin{question}[subtitle={Shortest Path Problem}]
273 | Using the Floyd-Warshall algorithm give the longest paths in between
274 | any two vertices of the following grahps
275 | \begin{center}
276 | \begin{tikzpicture}
277 | [minimum width={width("b")+1.5em},
278 | vertex/.style={circle, draw=black, fill=white, thick},
279 | arr/.style={->,>=stealth',semithick}]
280 | \node (E) at (13,3) [vertex] {$E$};
281 | \node (D) at (9,3) [vertex] {$D$}
282 | edge[
283 | arr,
284 | postaction={
285 | decorate,
286 | decoration={raise=-2.5ex, text along path, text align=center, text={1}}
287 | }
288 | ]
289 | node[below] {} (E);
290 | \node (B) at (13,7) [vertex] {$B$}
291 | edge[arr] node[right] {$2$} (E)
292 | edge[arr] node[below right] {$2$} (D);
293 | \node (C) at (9,7) [vertex] {$C$}
294 | edge[
295 | arr,
296 | postaction={
297 | decorate,
298 | decoration={raise=1ex, text along path, text align=center, text={3}}
299 | }
300 | ]
301 | node[above] {} (B)
302 | edge[arr, bend left] node[left] {$4$} (D);
303 | \node (A) at (5.5,5) [vertex] {$A$}
304 | edge[
305 | arr,
306 | postaction={
307 | decorate,
308 | decoration={raise=1ex, text along path, text align=center, text={4}}
309 | }
310 | ]
311 | node[above] {} (C)
312 | edge[
313 | arr,
314 | postaction={
315 | decorate,
316 | decoration={raise=-2.5ex, text along path, text align=center, text={8}}
317 | }
318 | ]
319 | node[below] {} (D);
320 | \path (D) edge[arr, bend left] node [left] {$-6$} (C);
321 | \end{tikzpicture}
322 | \end{center}
323 | Does looking for shortest paths in between any two vertices of this
324 | graph make sense?
325 | \end{question}
326 |
327 | \section{Scheduling}
328 |
329 | \begin{question}[subtitle={Project Scheduling}]
330 | A project is split into $8$ elementary tasks. In the table below, we
331 | sum up the needed time (in days) to accomplish a given task and the
332 | tasks one has to go through beforehand.
333 | \begin{center}
334 | \renewcommand{\arraystretch}{1.5}
335 | \begin{tabular}{|c|c|c|}
336 | \hline
337 | Tasks & Pre-tasks & Durations \\
338 | \hline
339 | a & -- & $2$ \\
340 | \hline
341 | b & -- & $3$ \\
342 | \hline
343 | c & -- & $7$ \\
344 | \hline
345 | d & b, h & $4$ \\
346 | e & a & $10$ \\
347 | \hline
348 | f & a, d & $6$ \\
349 | \hline
350 | g & b, c & $5$ \\
351 | \hline
352 | h & -- & $1$ \\
353 | \hline
354 | \end{tabular}
355 | \end{center}
356 | Our aim is to find a project scheduling that minimizes the total
357 | duration of the project.
358 | \begin{enumerate}
359 | \item Use the potential method to solve previous problem. Point out
360 | the earliest starting date for each task, the critical path and
361 | its duration. Draw the corresponding potential graph.
362 | \item Figure out the latest possible start of each task.
363 | \item Give up a PERT graph modeling the previous scheduling problem
364 | without introducing any external constraints (you'll need a number
365 | of virtual tasks). Recover back previous cirtical paths using
366 | relevant algorithms.
367 | \end{enumerate}
368 |
369 | \end{question}
370 |
371 |
372 | \begin{question}[subtitle= {Assisting the Director}]
373 | A movie producer is looking forward to plan his next movie to
374 | be. Here are the list of tasks to be done for the movie to get out
375 | on the screens.
376 | \begin{center}
377 | \renewcommand{\arraystretch}{1.5}
378 | \begin{tabular}{|c|l|c|p{5cm}|}
379 | \hline
380 | Task Code & Task detail & Duration & Precedency \\
381 | \hline
382 | A & Writing the scenario & 30 & \\
383 | \hline
384 | B & Casting & 12 & Can only start 15 days after A starts \\
385 | \hline
386 | C & Choosing shooting place & 8 & Can only start 20 days after A starts \\
387 | \hline
388 | D & Technical cut & 4 & A and C have to be finished \\
389 | \hline
390 | E & Preparing set & 7 & C and D have to be finished \\
391 | \hline
392 | F & Exterior shooting & 10 & A, B, C and D have to be finished \\
393 | \hline
394 | G & Interior shooting & 12 & D, E and F have to be finished \\
395 | \hline
396 | H & Synchronisation & 3 & F and G have to be finished \\
397 | \hline
398 | I & Editing & 14 & H has to be finished \\
399 | \hline
400 | J & Sound background & 7 & Can only start 3 days after the start of I and after H is finished \\
401 | \hline
402 | K & Mixing & 6 & I and J have to be finished \\
403 | \hline
404 | L & Answer print & 1 & Can only start 2 days after end of K \\
405 | \hline
406 | \end{tabular}
407 | \end{center}
408 | \begin{enumerate}
409 | \item Using the MPM model, give the earliest dates at which each
410 | task can be done. What is the critical path?
411 | \item Delete superfluous precedency constraints obtained by transitivity.
412 | \item Divide tasks $A$ and $I$ into subtasks and add an extra
413 | virtual task $K'$ of duration $2$. The goal is to have a graphs
414 | where all arrows going out from a given task have same valuation,
415 | $A$ will be divided into $4$ tasks for instance. The extra task
416 | $K'$ is there to make sure the arrow going out from $K$ has
417 | valuation corresponding to the duration of $K$.
418 | \item Draw a PERT graph adapted from previous work. What is the main
419 | disadvantage of the PERT approach in comparison with the MPM one?
420 | \item Is the set of extra arrows you get in your PERT graph a
421 | minimal set? Why do you need each of these arrows?
422 | \end{enumerate}
423 | \end{question}
424 | \end{document}
425 |
426 | %%% Local Variables:
427 | %%% mode: latex
428 | %%% TeX-master: t
429 | %%% End:
430 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | CC0 1.0 Universal
2 |
3 | Statement of Purpose
4 |
5 | The laws of most jurisdictions throughout the world automatically confer
6 | exclusive Copyright and Related Rights (defined below) upon the creator and
7 | subsequent owner(s) (each and all, an "owner") of an original work of
8 | authorship and/or a database (each, a "Work").
9 |
10 | Certain owners wish to permanently relinquish those rights to a Work for the
11 | purpose of contributing to a commons of creative, cultural and scientific
12 | works ("Commons") that the public can reliably and without fear of later
13 | claims of infringement build upon, modify, incorporate in other works, reuse
14 | and redistribute as freely as possible in any form whatsoever and for any
15 | purposes, including without limitation commercial purposes. These owners may
16 | contribute to the Commons to promote the ideal of a free culture and the
17 | further production of creative, cultural and scientific works, or to gain
18 | reputation or greater distribution for their Work in part through the use and
19 | efforts of others.
20 |
21 | For these and/or other purposes and motivations, and without any expectation
22 | of additional consideration or compensation, the person associating CC0 with a
23 | Work (the "Affirmer"), to the extent that he or she is an owner of Copyright
24 | and Related Rights in the Work, voluntarily elects to apply CC0 to the Work
25 | and publicly distribute the Work under its terms, with knowledge of his or her
26 | Copyright and Related Rights in the Work and the meaning and intended legal
27 | effect of CC0 on those rights.
28 |
29 | 1. Copyright and Related Rights. A Work made available under CC0 may be
30 | protected by copyright and related or neighboring rights ("Copyright and
31 | Related Rights"). Copyright and Related Rights include, but are not limited
32 | to, the following:
33 |
34 | i. the right to reproduce, adapt, distribute, perform, display, communicate,
35 | and translate a Work;
36 |
37 | ii. moral rights retained by the original author(s) and/or performer(s);
38 |
39 | iii. publicity and privacy rights pertaining to a person's image or likeness
40 | depicted in a Work;
41 |
42 | iv. rights protecting against unfair competition in regards to a Work,
43 | subject to the limitations in paragraph 4(a), below;
44 |
45 | v. rights protecting the extraction, dissemination, use and reuse of data in
46 | a Work;
47 |
48 | vi. database rights (such as those arising under Directive 96/9/EC of the
49 | European Parliament and of the Council of 11 March 1996 on the legal
50 | protection of databases, and under any national implementation thereof,
51 | including any amended or successor version of such directive); and
52 |
53 | vii. other similar, equivalent or corresponding rights throughout the world
54 | based on applicable law or treaty, and any national implementations thereof.
55 |
56 | 2. Waiver. To the greatest extent permitted by, but not in contravention of,
57 | applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and
58 | unconditionally waives, abandons, and surrenders all of Affirmer's Copyright
59 | and Related Rights and associated claims and causes of action, whether now
60 | known or unknown (including existing as well as future claims and causes of
61 | action), in the Work (i) in all territories worldwide, (ii) for the maximum
62 | duration provided by applicable law or treaty (including future time
63 | extensions), (iii) in any current or future medium and for any number of
64 | copies, and (iv) for any purpose whatsoever, including without limitation
65 | commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes
66 | the Waiver for the benefit of each member of the public at large and to the
67 | detriment of Affirmer's heirs and successors, fully intending that such Waiver
68 | shall not be subject to revocation, rescission, cancellation, termination, or
69 | any other legal or equitable action to disrupt the quiet enjoyment of the Work
70 | by the public as contemplated by Affirmer's express Statement of Purpose.
71 |
72 | 3. Public License Fallback. Should any part of the Waiver for any reason be
73 | judged legally invalid or ineffective under applicable law, then the Waiver
74 | shall be preserved to the maximum extent permitted taking into account
75 | Affirmer's express Statement of Purpose. In addition, to the extent the Waiver
76 | is so judged Affirmer hereby grants to each affected person a royalty-free,
77 | non transferable, non sublicensable, non exclusive, irrevocable and
78 | unconditional license to exercise Affirmer's Copyright and Related Rights in
79 | the Work (i) in all territories worldwide, (ii) for the maximum duration
80 | provided by applicable law or treaty (including future time extensions), (iii)
81 | in any current or future medium and for any number of copies, and (iv) for any
82 | purpose whatsoever, including without limitation commercial, advertising or
83 | promotional purposes (the "License"). The License shall be deemed effective as
84 | of the date CC0 was applied by Affirmer to the Work. Should any part of the
85 | License for any reason be judged legally invalid or ineffective under
86 | applicable law, such partial invalidity or ineffectiveness shall not
87 | invalidate the remainder of the License, and in such case Affirmer hereby
88 | affirms that he or she will not (i) exercise any of his or her remaining
89 | Copyright and Related Rights in the Work or (ii) assert any associated claims
90 | and causes of action with respect to the Work, in either case contrary to
91 | Affirmer's express Statement of Purpose.
92 |
93 | 4. Limitations and Disclaimers.
94 |
95 | a. No trademark or patent rights held by Affirmer are waived, abandoned,
96 | surrendered, licensed or otherwise affected by this document.
97 |
98 | b. Affirmer offers the Work as-is and makes no representations or warranties
99 | of any kind concerning the Work, express, implied, statutory or otherwise,
100 | including without limitation warranties of title, merchantability, fitness
101 | for a particular purpose, non infringement, or the absence of latent or
102 | other defects, accuracy, or the present or absence of errors, whether or not
103 | discoverable, all to the greatest extent permissible under applicable law.
104 |
105 | c. Affirmer disclaims responsibility for clearing rights of other persons
106 | that may apply to the Work or any use thereof, including without limitation
107 | any person's Copyright and Related Rights in the Work. Further, Affirmer
108 | disclaims responsibility for obtaining any necessary consents, permissions
109 | or other rights required for any use of the Work.
110 |
111 | d. Affirmer understands and acknowledges that Creative Commons is not a
112 | party to this document and has no duty or obligation with respect to this
113 | CC0 or use of the Work.
114 |
115 | For more information, please see
116 |
117 |
--------------------------------------------------------------------------------
/Notebooks/.ipynb_checkpoints/graphsTraversals-checkpoint.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": null,
6 | "metadata": {},
7 | "outputs": [],
8 | "source": []
9 | }
10 | ],
11 | "metadata": {
12 | "kernelspec": {
13 | "display_name": "Python 3",
14 | "language": "python",
15 | "name": "python3"
16 | },
17 | "language_info": {
18 | "codemirror_mode": {
19 | "name": "ipython",
20 | "version": 3
21 | },
22 | "file_extension": ".py",
23 | "mimetype": "text/x-python",
24 | "name": "python",
25 | "nbconvert_exporter": "python",
26 | "pygments_lexer": "ipython3",
27 | "version": "3.7.0"
28 | }
29 | },
30 | "nbformat": 4,
31 | "nbformat_minor": 2
32 | }
33 |
--------------------------------------------------------------------------------
/Notebooks/algopy/README.md:
--------------------------------------------------------------------------------
1 | # `grefpy`
2 |
3 | This is a partial portion of `algopy` module, which is used during
4 | first two years of undergraduate cycle @Epita. `grefpy` is the main
5 | module reference for *Graphs and Flows* course **(GREF)** @Epita.
6 |
7 | You can generate current doc using `sphinx`. Available structure is
8 | within folders `docs`.
9 |
--------------------------------------------------------------------------------
/Notebooks/algopy/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bashardudin/GraphsAndFlows/afdf1d1c60d54abec7484fbaa1b473b9d3d0894b/Notebooks/algopy/__init__.py
--------------------------------------------------------------------------------
/Notebooks/algopy/docs/Makefile:
--------------------------------------------------------------------------------
1 | # Minimal makefile for Sphinx documentation
2 | #
3 |
4 | # You can set these variables from the command line.
5 | SPHINXOPTS =
6 | SPHINXBUILD = python -msphinx
7 | SPHINXPROJ = AlgoPY
8 | SOURCEDIR = .
9 | BUILDDIR = _build
10 |
11 | # Put it first so that "make" without argument is like "make help".
12 | help:
13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
14 |
15 | .PHONY: help Makefile
16 |
17 | # Catch-all target: route all unknown targets to Sphinx using the new
18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
19 | %: Makefile
20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
--------------------------------------------------------------------------------
/Notebooks/algopy/docs/conf.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | #
4 | # AlgoPY documentation build configuration file, created by
5 | # sphinx-quickstart on Thu Aug 31 12:29:04 2017.
6 | #
7 | # This file is execfile()d with the current directory set to its
8 | # containing dir.
9 | #
10 | # Note that not all possible configuration values are present in this
11 | # autogenerated file.
12 | #
13 | # All configuration values have a default; values that are commented out
14 | # serve to show the default.
15 |
16 | # If extensions (or modules to document with autodoc) are in another directory,
17 | # add these directories to sys.path here. If the directory is relative to the
18 | # documentation root, use os.path.abspath to make it absolute, like shown here.
19 | #
20 | import os
21 | import sys
22 | sys.path.insert(0, os.path.abspath('../..'))
23 |
24 |
25 | # -- General configuration ------------------------------------------------
26 |
27 | # If your documentation needs a minimal Sphinx version, state it here.
28 | #
29 | # needs_sphinx = '1.0'
30 |
31 | # Add any Sphinx extension module names here, as strings. They can be
32 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
33 | # ones.
34 | extensions = ['sphinx.ext.autodoc',
35 | 'sphinx.ext.napoleon',
36 | 'sphinx_autodoc_typehints',
37 | 'sphinx.ext.doctest',
38 | 'sphinx.ext.coverage',
39 | 'sphinx.ext.mathjax',
40 | 'sphinx.ext.ifconfig',
41 | 'sphinx.ext.viewcode',
42 | 'sphinx.ext.githubpages',
43 | 'sphinx.ext.todo']
44 |
45 | # Add any paths that contain templates here, relative to this directory.
46 | templates_path = ['_templates']
47 |
48 | # The suffix(es) of source filenames.
49 | # You can specify multiple suffix as a list of string:
50 | # source_parsers = {
51 | # '.md': 'recommonmark.parser.CommonMarkParser',
52 | # }
53 | # source_suffix = ['.rst', '.md']
54 | source_suffix = ['.rst']
55 |
56 | # The master toctree document.
57 | master_doc = 'index'
58 |
59 | # General information about the project.
60 | project = 'AlgoPY'
61 | copyright = '2017, EPITA Prepa Algo Team'
62 | author = 'EPITA Prepa Algo Team'
63 |
64 | # The version info for the project you're documenting, acts as replacement for
65 | # |version| and |release|, also used in various other places throughout the
66 | # built documents.
67 | #
68 | # The short X.Y version.
69 | version = '0.1'
70 | # The full version, including alpha/beta/rc tags.
71 | release = '0.1.0'
72 |
73 | # The language for content autogenerated by Sphinx. Refer to documentation
74 | # for a list of supported languages.
75 | #
76 | # This is also used if you do content translation via gettext catalogs.
77 | # Usually you set "language" from the command line for these cases.
78 | language = None
79 |
80 | # List of patterns, relative to source directory, that match files and
81 | # directories to ignore when looking for source files.
82 | # This patterns also effect to html_static_path and html_extra_path
83 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
84 |
85 | # The name of the Pygments (syntax highlighting) style to use.
86 | pygments_style = 'sphinx'
87 |
88 | # If true, `todo` and `todoList` produce output, else they produce nothing.
89 | todo_include_todos = False
90 |
91 |
92 | # -- Options for HTML output ----------------------------------------------
93 |
94 | # The theme to use for HTML and HTML Help pages. See the documentation for
95 | # a list of builtin themes.
96 | #
97 | # html_theme = 'alabaster'
98 | html_theme = 'sphinx_rtd_theme'
99 |
100 | # Theme options are theme-specific and customize the look and feel of a theme
101 | # further. For a list of options available for each theme, see the
102 | # documentation.
103 | #
104 | html_theme_options = {
105 | 'collapse_navigation': False,
106 | 'display_version': True,
107 | 'navigation_depth': 3,
108 | }
109 |
110 | # Add any paths that contain custom static files (such as style sheets) here,
111 | # relative to this directory. They are copied after the builtin static files,
112 | # so a file named "default.css" will overwrite the builtin "default.css".
113 | html_static_path = ['_static']
114 |
115 | # Custom sidebar templates, must be a dictionary that maps document names
116 | # to template names.
117 | #
118 | # This is required for the alabaster theme
119 | # refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars
120 | # html_sidebars = {
121 | # '**': [
122 | # 'about.html',
123 | # 'navigation.html',
124 | # 'relations.html', # needs 'show_related': True theme option to display
125 | # 'searchbox.html',
126 | # 'donate.html',
127 | # ]
128 | # }
129 |
130 |
131 | # -- Options for HTMLHelp output ------------------------------------------
132 |
133 | # Output file base name for HTML help builder.
134 | htmlhelp_basename = 'AlgoPYdoc'
135 |
136 |
137 | # -- Options for LaTeX output ---------------------------------------------
138 |
139 | latex_elements = {
140 | # The paper size ('letterpaper' or 'a4paper').
141 | #
142 | # 'papersize': 'letterpaper',
143 |
144 | # The font size ('10pt', '11pt' or '12pt').
145 | #
146 | # 'pointsize': '10pt',
147 |
148 | # Additional stuff for the LaTeX preamble.
149 | #
150 | # 'preamble': '',
151 |
152 | # Latex figure (float) alignment
153 | #
154 | # 'figure_align': 'htbp',
155 | }
156 |
157 | # Grouping the document tree into LaTeX files. List of tuples
158 | # (source start file, target name, title,
159 | # author, documentclass [howto, manual, or own class]).
160 | latex_documents = [
161 | (master_doc, 'AlgoPY.tex', 'AlgoPY Documentation',
162 | 'EPITA Prepa Algo Team', 'manual'),
163 | ]
164 |
165 |
166 | # -- Options for manual page output ---------------------------------------
167 |
168 | # One entry per manual page. List of tuples
169 | # (source start file, name, description, authors, manual section).
170 | man_pages = [
171 | (master_doc, 'algopy', 'AlgoPY Documentation',
172 | [author], 1)
173 | ]
174 |
175 |
176 | # -- Options for Texinfo output -------------------------------------------
177 |
178 | # Grouping the document tree into Texinfo files. List of tuples
179 | # (source start file, target name, title, author,
180 | # dir menu entry, description, category)
181 | texinfo_documents = [
182 | (master_doc, 'AlgoPY', 'AlgoPY Documentation',
183 | author, 'AlgoPY', 'One line description of project.',
184 | 'Miscellaneous'),
185 | ]
186 |
187 |
188 | # -- Extra context info for HTML generation--------------------------------
189 |
190 | html_context = {
191 | "display_github": False, # Integrate GitHub
192 | "github_user": "MyUserName", # Username
193 | "github_repo": "MyDoc", # Repo name
194 | "github_version": "master", # Version
195 | "conf_py_path": "/source/", # Path in the checkout to the docs root
196 | }
197 |
198 | rst_prolog = """
199 | .. highlight:: python
200 | :linenothreshold: 1
201 |
202 | .. role:: python(code)
203 | :language: python
204 | """
205 |
--------------------------------------------------------------------------------
/Notebooks/algopy/docs/conventions_and_rules.rst:
--------------------------------------------------------------------------------
1 | #####################
2 | Conventions and Rules
3 | #####################
4 |
5 | This page lists the conventions and rules to follow when coding in Python for
6 | the *algorithmics* course, dispensed to first and second year students at
7 | **EPITA**.
8 |
9 | Any convention not found here is replaced by its Python
10 | `PEP8`_ counterpart. Conventions for *docstrings* are to follow `PEP257`_ and
11 | `Google conventions`_.
12 |
13 | .. _PEP8: https://www.python.org/dev/peps/pep-0008/
14 | .. _PEP257: https://www.python.org/dev/peps/pep-0257/
15 | .. _Google conventions: http://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html
16 |
17 |
18 | ************
19 | Coding Style
20 | ************
21 |
22 |
23 | Naming Conventions
24 | ==================
25 |
26 | Naming conventions follow either the *UPPERCASE*, *lowercase*, *CamelCase* or
27 | the *snake_case convention*, depending on named objects.
28 |
29 | * **Files and directories**: follow the *lowercase* convention.
30 | * **Functions and methods**: follow a light version of the *snake_case*
31 | convention.
32 | * **Variables, class instances and class attributes**: follow the *function
33 | convention*.
34 | * **Classes**: follow the *CamelCase* convention.
35 | * **Constants**: are expected to be in *UPPERCASE_SNAKE*.
36 | * **Auxiliary functions**: name of auxiliary function of function `name`, in
37 | charge of step or task `step` takes the form `__[name]_[step]`.
38 |
39 | .. hint:: Function names should be all lowercase while kept short and explicit.
40 | Separate words by underscores if necessary to improve readability.
41 |
42 | Punctuation and Spacing Conventions
43 | ===================================
44 |
45 | This section puts some emphasis on rules and conventions extracted from `PEP8`_,
46 | concerning syntactically correct options on code spacing and punctuation.
47 |
48 | * **Indentation** is to be given by 4 *spaces*.
49 | * There are no spaces before **commas** and **colons**, there is a
50 | space after a comma and a new line after a colon.
51 | * There is one space before an equality sign and one after it. Exception
52 | is made for default assignments in functions' parameters; there are no
53 | spaces neither before nor after the equality sign in that case.
54 | * There is one space before a binary operator and one after it.
55 | * There is no space after an opening **parenthesis** nor before a closing
56 | one. There is no space before an opening parenthesis when enclosing a
57 | function's list of parameters.
58 | * Same conventions hold for **brackets** and **braces**. There is no space
59 | before an opening **bracket** or **brace** when used to specify a key.
60 | * There are at least two spaces before inline **comments**.
61 |
62 | .. caution:: You're advised to configure your IDE or text editor to
63 | automatically replace *any tab* character by 4 *spaces*.
64 |
65 |
66 | ***********************************************
67 | Forbidden Functions, Keywords and Coding Habits
68 | ***********************************************
69 |
70 | Any Python function or keyword not explicitly allowed in this document is
71 | **FORBIDDEN**, exception made of progress stages below.
72 | Hereafter is a list of most common forbidden functions and keywords.
73 |
74 | * ``break`` and ``continue`` are absolutely forbidden instructions. More
75 | generally, any abusive use of flow breaking instructions (including ``return``
76 | instruction) is forbidden.
77 | * *lambda* functions are not allowed (as not needed at our level).
78 | * The course focus is **algorithmics**. No explicit use of object oriented
79 | programming on students' side is expected nor allowed.
80 | * Power (or exponentiation) operator ``**`` is not allowed.
81 |
82 |
83 | ***************
84 | Progress Stages
85 | ***************
86 |
87 | This the list of progress stages any algorithmics student goes through during
88 | first year. Each stage comes with its privileges: the use of previously
89 | forbidden built-in functions and keywords.
90 |
91 | Stage 1
92 | =======
93 |
94 | * some arithmetic operators: ``+``, ``-``, ``//``,
95 | ``%``, ``/``
96 | * ``def`` for functions
97 | * ``if``, ``elif`` and ``else`` clauses
98 | * ``while`` loops
99 |
100 | Stage 2
101 | =======
102 |
103 | * ``list`` objects
104 | * ``list.append`` method
105 | * ``list.pop`` method without any argument
106 | * ``len`` function on *list* objects
107 | * ``for`` loops
108 | * ``range`` function, within for loops and in its three variants
109 |
110 | Stage 3
111 | =======
112 |
113 | * ``list.insert`` and ``list.pop`` methods
114 |
115 | Stage 4
116 | =======
117 |
118 | * the ``is`` keyword, **now mandatory while testing against None value**
119 | * flow-breaking ``return`` instruction, **only** for marginal cases to keep
120 | loop bodies simpler
121 |
122 | Stage 5
123 | =======
124 |
125 | * ternaries
126 | * list initialization using syntax ``[val] * nb``
127 | * object coercion into boolean
128 | * sets and dictionaries
129 | * list comprehensions
130 | * deep copy, via ``copy.deepcopy``
131 |
--------------------------------------------------------------------------------
/Notebooks/algopy/docs/index.rst:
--------------------------------------------------------------------------------
1 | .. AlgoPY documentation master file, created by
2 | sphinx-quickstart on Thu Aug 31 12:29:04 2017.
3 | You can adapt this file completely to your liking, but it should at least
4 | contain the root `toctree` directive.
5 |
6 | Welcome to AlgoPY's documentation!
7 | ==================================
8 |
9 | .. toctree::
10 | :maxdepth: 2
11 | :caption: Contents:
12 |
13 | conventions_and_rules
14 | Inline documentation
15 |
16 | Indices and tables
17 | ==================
18 |
19 | * :ref:`genindex`
20 | * :ref:`modindex`
21 | * :ref:`search`
22 |
--------------------------------------------------------------------------------
/Notebooks/algopy/docs/make.bat:
--------------------------------------------------------------------------------
1 | @ECHO OFF
2 |
3 | pushd %~dp0
4 |
5 | REM Command file for Sphinx documentation
6 |
7 | if "%SPHINXBUILD%" == "" (
8 | set SPHINXBUILD=python -msphinx
9 | )
10 | set SOURCEDIR=.
11 | set BUILDDIR=_build
12 | set SPHINXPROJ=AlgoPY
13 |
14 | if "%1" == "" goto help
15 |
16 | %SPHINXBUILD% >NUL 2>NUL
17 | if errorlevel 9009 (
18 | echo.
19 | echo.The Sphinx module was not found. Make sure you have Sphinx installed,
20 | echo.then set the SPHINXBUILD environment variable to point to the full
21 | echo.path of the 'sphinx-build' executable. Alternatively you may add the
22 | echo.Sphinx directory to PATH.
23 | echo.
24 | echo.If you don't have Sphinx installed, grab it from
25 | echo.http://sphinx-doc.org/
26 | exit /b 1
27 | )
28 |
29 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%
30 | goto end
31 |
32 | :help
33 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%
34 |
35 | :end
36 | popd
37 |
--------------------------------------------------------------------------------
/Notebooks/algopy/docs/modules.rst:
--------------------------------------------------------------------------------
1 | Inline Documentation
2 | ====================
3 |
4 | .. toctree::
5 | :maxdepth: 4
6 |
7 | algopy
8 |
--------------------------------------------------------------------------------
/Notebooks/algopy/exception.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """Exception module.
3 |
4 | Provide simple exceptions to use in data type functions.
5 |
6 | """
7 |
8 | class ExempleSyntaxError(Exception):
9 | """Simple exception to raise when test input is wrongly formated."""
10 | pass
11 |
12 | class NoneException(Exception):
13 | """Simple exception to raise when parameter is None."""
14 | pass
15 |
--------------------------------------------------------------------------------
/Notebooks/algopy/flycheck_tree.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """General Tree module.
3 |
4 | *Warning:* All the functions defined in this module are assumed to receive a non-None
5 | value for their ``ref`` parameter.
6 |
7 | Todo:
8 | * Save to file? Via Dot?
9 | * Load from file -> done!
10 |
11 | """
12 |
13 | from . import queue
14 | from .queue import Queue
15 |
16 |
17 | class Tree:
18 | """Simple class for general tree.
19 |
20 | Attributes:
21 | key (Any): Node key.
22 | children (List[Tree]): Node children.
23 |
24 | """
25 |
26 | def __init__(self, key=None, children=None):
27 | """Init general tree, ensure children are properly set.
28 |
29 | Args:
30 | key (Any).
31 | children (List[Tree]).
32 |
33 | """
34 |
35 | self.key = key
36 |
37 | if children is None:
38 | self.children = []
39 | else:
40 | self.children = children
41 |
42 | @property
43 | def nbchildren(self):
44 | """Number of children of node."""
45 |
46 | return len(self.children)
47 |
48 |
49 | def size(ref):
50 | """Compute size of tree.
51 |
52 | Args:
53 | ref (Tree).
54 |
55 | Returns:
56 | int: The number of nodes of tree.
57 |
58 | """
59 |
60 | s = 1
61 | for i in range(ref.nbchildren):
62 | s += size(ref.children[i])
63 | return s
64 |
65 |
66 | def height(ref):
67 | """Compute height of Tree.
68 |
69 | Args:
70 | ref (Tree).
71 |
72 | Returns:
73 | int: The maximum depth of any leaf.
74 |
75 | """
76 |
77 | h = -1
78 | for i in range(ref.nbchildren):
79 | h = max(h, height(ref.children[i]))
80 | return h + 1
81 |
82 |
83 | def epl(ref, h=0):
84 | """Compute external paths' length.
85 |
86 | Args:
87 | ref (Tree).
88 | h (int): Current height.
89 |
90 | Returns:
91 | int: The total length of paths from root to leaves.
92 |
93 | """
94 |
95 | if ref.nbchildren > 0:
96 | length = 0
97 | for i in range(ref.nbchildren):
98 | length += epl(ref.children[i], h + 1)
99 | return length
100 | else:
101 | return h
102 |
103 |
104 | def search(ref, val):
105 | """Search for a value in tree.
106 |
107 | Args:
108 | ref (Tree).
109 | val (Any): Value to search.
110 |
111 | Returns:
112 | Tree: First node containing key val.
113 |
114 | """
115 |
116 | if ref.key == val:
117 | return ref
118 | else:
119 | for child in ref.children:
120 | found = search(child, val)
121 | if found is not None:
122 | return found
123 | return None
124 |
125 | def __loadtree(s, typelt,i=0):
126 | if i < len(s) and s[i] == '(': # can this test be removed?
127 | i = i + 1 # to skip the '('
128 | T = Tree()
129 | word = ""
130 | while not (s[i] in "()"):
131 | word = word + s[i]
132 | i += 1
133 | T.key = typelt(word)
134 | T.children = []
135 | while s[i] != ')':
136 | (C, i) = __loadtree(s, typelt, i)
137 | T.children.append(C)
138 | i = i + 1 # to skip the ')'
139 | return (T, i)
140 | else:
141 | return None
142 |
143 | def loadtree(path, typelt=int):
144 | # Open file and get full content
145 | file = open(path, 'r')
146 | content = file.read()
147 | # Remove all whitespace characters for easier parsing
148 | content = content.replace('\n', '').replace('\r', '') \
149 | .replace('\t', '').replace(' ', '')
150 | file.close()
151 | # Parse content and return tree
152 | (T, _) = __loadtree(content, typelt)
153 | return T
154 |
155 |
156 | def dot(ref):
157 | """Write down dot format of tree.
158 |
159 | Args:
160 | ref (Tree).
161 |
162 | Returns:
163 | str: String storing dot format of tree.
164 |
165 | """
166 |
167 | s = "graph {\n"
168 | s += "node [shape=circle, fixedsize=true, height=0.5, width=0.5]\n"
169 | q = Queue()
170 | q.enqueue(ref)
171 | while not q.isempty():
172 | ref = q.dequeue()
173 | for child in ref.children:
174 | s = s + " " + str(ref.key) + " -- " + str(child.key) + "\n"
175 | q.enqueue(child)
176 | s += "}"
177 | return s
178 |
179 |
180 | def display(ref, filename='temp'):
181 | """Render a tree to SVG format.
182 |
183 | *Warning:* Made for use within IPython/Jupyter only.
184 |
185 | Args:
186 | ref (Tree).
187 | filename (str): Temporary filename to store SVG output.
188 |
189 | Returns:
190 | SVG: IPython SVG wrapper object for tree.
191 |
192 | """
193 |
194 | # Ensure all modules are available
195 | try:
196 | from graphviz import Graph
197 | from IPython.display import SVG
198 | except:
199 | raise Exception("Missing module: graphviz and/or IPython.")
200 | # Traverse tree and generate temporary Graph object
201 | output_format = 'svg'
202 | graph = Graph(filename, format=output_format)
203 | q = Queue()
204 | q.enqueue(ref)
205 | while not q.isempty():
206 | ref = q.dequeue()
207 | graph.node(str(id(ref)), label=str(ref.key))
208 | for child in ref.children:
209 | graph.edge(str(id(ref)), str(id(child)))
210 | q.enqueue(child)
211 | # Render to temporary file and SVG object
212 | graph.render(filename=filename, cleanup=True)
213 | return SVG(filename + '.' + output_format)
214 |
--------------------------------------------------------------------------------
/Notebooks/algopy/graph.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """Graph module.
3 |
4 | Provide an implementation of graphs with adjacency lists.
5 |
6 | In a graph, vertices are considered numbered from 0 to the order of the graph
7 | minus one. The vertex key, or number, can then be used to access its
8 | adjacency list.
9 |
10 | Todo:
11 | * Decide names for load/save: to_dot/from_dot ? save/load with format
12 | parameter? Specific module?
13 | -> done!???
14 | * Add module level functions for specific tasks: build_from_list...
15 | ???
16 | * Handle multigraphs? (fix add_edge and dot)
17 | -> DONE!
18 |
19 | """
20 |
21 | #from .exception import NoneException # fait planter mon Python !!!!
22 |
23 |
24 | class Graph:
25 | """ Simple class for graph: adjacency lists
26 |
27 | Attributes:
28 | order (int): Number of nodes.
29 | directed (bool): True if the graph is directed. False otherwise.
30 | adjlists (List[List[int]]): Lists of connected vertices for each vertex.
31 |
32 | """
33 |
34 | def __init__(self, order, directed=False, costs=False):
35 | """Init graph, allocate adjacency lists
36 |
37 | Args:
38 | order (int): Number of nodes.
39 | directed (bool): True if the graph is directed. False otherwise.
40 | costs (bool): True if the graph is weighted. False otherwise.
41 |
42 | """
43 |
44 | self.order = order
45 | self.directed = directed
46 | if costs:
47 | self.costs = {}
48 | else:
49 | self.costs = None
50 | self.adjlists = []
51 | for _ in range(order):
52 | self.adjlists.append([])
53 |
54 |
55 | def addedge(self, src, dst, cost=None, multi=False):
56 | """Add egde to graph.
57 |
58 | Args:
59 | src (int): Source vertex.
60 | dst (int): Destination vertex.
61 | cost: if not None, the cost of edge (src, dst)
62 | multi (bool): True for multigraphs
63 |
64 | Raises:
65 | IndexError: If any vertex index is invalid.
66 | Exception: If graph is None.
67 |
68 | """
69 |
70 | # Check graph and vertex indices.
71 | if self is None:
72 | raise Exception('Empty graph')
73 | if src >= self.order or src < 0:
74 | raise IndexError("Invalid src index")
75 | if dst >= self.order or dst < 0:
76 | raise IndexError("Invalid dst index")
77 | # Add edge if multi or not already existing, and reverse-edge if undirected.
78 | if multi or (src != dst and dst not in self.adjlists[src]):
79 | self.adjlists[src].append(dst)
80 | if not self.directed and dst != src:
81 | self.adjlists[dst].append(src)
82 | if cost:
83 | self.costs[(src, dst)] = cost
84 | if not self.directed:
85 | self.costs[(dst, src)] = cost
86 |
87 |
88 | def addvertex(self, number=1):
89 | """Add number vertices to graph.
90 |
91 | Args:
92 | ref (Graph).
93 | number (int): Number of vertices to add.
94 |
95 | Raises:
96 | Exception: If graph is None.
97 |
98 | """
99 |
100 | # Check graph
101 | if self is None:
102 | raise Exception('Empty graph')
103 | # Increment order and extend adjacency list
104 | self.order += number
105 | for _ in range(number):
106 | self.adjlists.append([])
107 |
108 |
109 | def _dot(self, engine='fdp'):
110 | '''Generate dot representation (as object, not source).
111 |
112 | Requires graphviz module.
113 |
114 | Returns:
115 | string (SVG)
116 | '''
117 | try:
118 | from graphviz import Graph as gvGraph, Digraph as gvDigraph
119 | except:
120 | raise Exception('Missing module: graphviz')
121 | g = gvDigraph(engine=engine) if self.directed else gvGraph(engine=engine)
122 | for src in range(self.order):
123 | for dst in self.adjlists[src]:
124 | if self.directed or src <= dst:
125 | g.edge(str(src), str(dst))
126 | return g
127 |
128 |
129 | def _repr_svg_(self, engine='fdp'):
130 | '''Generate SVG representation.
131 |
132 | Requires graphviz module.
133 |
134 | Returns:
135 | string (SVG)
136 | '''
137 | return self._dot(engine=engine)._repr_svg_()
138 |
139 |
140 | def _display(self, engine='fdp'):
141 | '''Displays SVG representation directly in IPython notebook.
142 |
143 | Requires IPython and (through method _repr_svg_) graphviz modules.
144 | '''
145 | try:
146 | from IPython.display import display_svg
147 | except:
148 | raise Exception('Missing moduke: IPtyhon')
149 | display_svg(self._dot(engine=engine))
150 |
151 |
152 |
153 | def todot(ref):
154 | """Write down dot format of graph.
155 |
156 | Args:
157 | ref (Graph).
158 |
159 | Returns:
160 | str: String storing dot format of graph.
161 |
162 | """
163 |
164 | # Check if empty graph.
165 | if ref is None:
166 | return "graph G { }"
167 | # Build dot for non-empty graph.
168 | (s, link) = ("digraph ", " -> ") if ref.directed else ("graph ", " -- ")
169 | s += " G {\n"
170 | s += "node [shape = circle]\n"
171 | for src in range(ref.order):
172 | s += str(src) + '\n'
173 | for dst in ref.adjlists[src]:
174 | cost = ' [label=' + str(ref.costs[(src, dst)]) + '] ' if ref.costs else ""
175 | if ref.directed or src >= dst:
176 | s += " " + str(src) + link + str(dst) + cost + '\n'
177 | s += '}'
178 | return s
179 |
180 |
181 | # I still do not understand why not just use the dot generated before...
182 | def displaySVG(ref, filename='temp'):
183 | """Render a graph to SVG format.
184 |
185 | *Warning:* Made for use within IPython/Jupyter only.
186 |
187 | Args:
188 | ref (Graph).
189 | filename (str): Temporary filename to store SVG output.
190 |
191 | Returns:
192 | SVG: IPython SVG wrapper object for graph.
193 |
194 | """
195 |
196 | # Ensure all modules are available
197 | try:
198 | from graphviz import Graph as gvGraph, Digraph as gvDigraph
199 | from IPython.display import SVG
200 | except:
201 | raise Exception("Missing module: graphviz and/or IPython.")
202 | # Traverse graph and generate temporary Digraph/Graph object
203 | output_format = 'svg'
204 | if ref.directed:
205 | graph = gvDigraph(filename, format=output_format)
206 | else:
207 | graph = gvGraph(filename, format=output_format)
208 | if ref is not None:
209 | for src in range(ref.order):
210 | src_id = 'node_' + str(src)
211 | graph.node(src_id, label=str(src))
212 | for dst in ref.adjlists[src]:
213 | if ref.directed or src >= dst:
214 | graph.edge(src_id, 'node_' + str(dst))
215 | # Render to temporary file and SVG object
216 | graph.render(filename=filename, cleanup=True)
217 | return SVG(filename + '.' + output_format)
218 |
219 |
220 | def display(ref, eng=None):
221 | try:
222 | from graphviz import Source
223 | from IPython.display import display
224 | except:
225 | raise Exception("Missing module: graphviz and/or IPython.")
226 | display(Source(todot(ref), engine = eng))
227 |
228 |
229 | # load / save gra(wgra) format
230 |
231 | def loadgra(filename, multigraph=False):
232 | """Build a new graph from a GRA file.
233 |
234 | Args:
235 | filename (str): File to load.
236 |
237 | Returns:
238 | Graph: New graph.
239 |
240 | Raises:
241 | FileNotFoundError: If file does not exist. ????
242 |
243 | """
244 |
245 | with open(filename) as f:
246 | directed = bool(int(f.readline()))
247 | order = int(f.readline())
248 | g = Graph(order, directed)
249 | for line in f.readlines():
250 | edge = line.strip().split(' ')
251 | src, dst = int(edge[0]), int(edge[1])
252 | g.addedge(src, dst, multi=multigraph)
253 | return g
254 |
255 | def savegra(G, fileOut):
256 | gra = str(int(G.directed)) + '\n'
257 | gra += str(G.order) + '\n'
258 | for s in range(G.order):
259 | for adj in G.adjLists[s]:
260 | if G.directed or s >= adj:
261 | gra += str(s) + " " + str(adj) + '\n'
262 | with open(fileOut, mode='w') as fout:
263 | fout.write(gra)
264 |
265 | # add-on: sorts adjacency lists -> to have same results as those asked in tutorials/exams
266 |
267 | def sortgraph(G):
268 | for i in range(G.order):
269 | G.adjLists[i].sort()
270 |
271 | #
272 | def fromlist(order, directed, edges):
273 | """Build a new graph from an int tuple list.
274 |
275 | Args:
276 | order (int): Order of graph.
277 | directed (bool): True if the graph is directed. False otherwise.
278 | edges (List[(int, int)]): Source/Destination tuple list.
279 |
280 | Returns:
281 | Graph: New graph.
282 |
283 | Raises:
284 | IndexError: If either order or edge extremity is invalid.
285 |
286 | """
287 |
288 | # Check order:
289 | if order <= 0:
290 | raise IndexError('Invalid order')
291 | # Build graph
292 | g = Graph(order, directed)
293 | for (src, dst) in edges:
294 | g.addedge(src, dst)
295 | return g
296 |
297 |
--------------------------------------------------------------------------------
/Notebooks/algopy/graphmat.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """Graph module.
3 |
4 | Provide an implementation of graphs with adjacency matrix.
5 | This can also be called static implementation.
6 |
7 | In a graph, vertices are considered numbered from 0 to the order of the graph
8 | minus one. The vertex key, or number, can then be used to access its
9 | neighbour list.
10 |
11 | Todo:
12 | * Decide names for load/save: to_dot/from_dot ? save/load with format
13 | parameter? Specific module?
14 | * Add module level functions for specific tasks: build_from_list...
15 | * Add add_edge and add_node (and use in from_list/from_gra)
16 | * Handle multigraphs? (fix add_edge and dot)
17 |
18 | """
19 |
20 |
21 | class GraphMat:
22 | """ Simple class for static graph.
23 |
24 | Attributes:
25 | order (int): Number of nodes.
26 | directed (bool): True if the graph is directed. False otherwise.
27 |
28 | """
29 |
30 | def __init__(self, order, directed=False, costs=False):
31 | self.order = order
32 | self.directed = directed
33 | self.adj = [[0 for j in range(order)] for i in range(order)]
34 | if costs:
35 | self.costs = [[float('inf') for j in range(order)] for i in range(order)]
36 | else:
37 | self.costs = None
38 |
39 | def addedge(self, src, dst, cost=None, multi=False):
40 | """Add egde to graph.
41 |
42 | Args:
43 | src (int): Source vertex.
44 | dst (int): Destination vertex.
45 | cost: if not None, the cost of edge (src, dst)
46 | multi (bool): True for multigraphs
47 |
48 | Raises:
49 | IndexError: If any vertex index is invalid.
50 | Exception: If graph is None.
51 |
52 | """
53 |
54 | if self is None:
55 | raise Exception('Empty graph')
56 | if src >= self.order or src < 0:
57 | raise IndexError("Invalid src index")
58 | if dst >= self.order or dst < 0:
59 | raise IndexError("Invalid dst index")
60 | # Add edge if multi or not already existing, and reverse-edge if undirected.
61 | if multi or (src != dst and self.adj[src][dst] == 0):
62 | self.adj[src][dst] += 1
63 | if not self.directed and dst != src:
64 | self.adj[dst][src] += 1
65 | if cost:
66 | self.costs[src][dst] = cost
67 | if not self.directed:
68 | self.costs[dst][src] = cost
69 |
70 |
71 | def _dot(self, engine='fdp'):
72 | '''Generate dot representation (as object, not source).
73 |
74 | Requires graphviz module.
75 |
76 | Returns:
77 | string (SVG)
78 | '''
79 | try:
80 | from graphviz import Graph as gvGraph, Digraph as gvDigraph
81 | except:
82 | raise Exception('Missing module: graphviz')
83 | g = gvDigraph(engine=engine) if self.directed else gvGraph(engine=engine)
84 | for src in range(self.order):
85 | for dst in range(self.order):
86 | if self.adj[src][dst] and (self.directed or src <= dst):
87 | for i in range(self.adj[src][dst]):
88 | g.edge(str(src), str(dst))
89 | return g
90 |
91 |
92 | def _repr_svg_(self, engine='fdp'):
93 | '''Generate SVG representation.
94 |
95 | Requires graphviz module.
96 |
97 | Returns:
98 | string (SVG)
99 | '''
100 | return self._dot(engine=engine)._repr_svg_()
101 |
102 |
103 | def _display(self, engine='fdp'):
104 | '''Displays SVG representation directly in IPython notebook.
105 |
106 | Requires IPython and (through method _repr_svg_) graphviz modules.
107 | '''
108 | try:
109 | from IPython.display import display_svg
110 | except:
111 | raise Exception('Missing moduke: IPtyhon')
112 | display_svg(self._dot(engine=engine))
113 |
114 |
115 |
116 | def todot(ref):
117 | """Write down dot format of graph.
118 |
119 | Args:
120 | ref (GraphMat).
121 |
122 | Returns:
123 | str: String storing dot format of graph.
124 |
125 | """
126 |
127 | # Check if empty graph.
128 | if ref is None:
129 | return "graph G { }"
130 | # Build dot for non-empty graph.
131 | (s, link) = ("digraph", " -> ") if ref.directed else ("graph", " -- ")
132 | s += " G {\n"
133 | s += "node [shape = circle]\n"
134 | for src in range(ref.order):
135 | for dst in range(ref.order):
136 | if ref.directed or src >= dst:
137 | for i in range(ref.adj[src][dst]):
138 | s += " " + str(src) + link + str(dst) + '\n'
139 | s += '}'
140 | return s
141 |
142 |
143 | def displaySVG(ref, filename='temp'):
144 | """Render a graph to SVG format.
145 |
146 | *Warning:* Made for use within IPython/Jupyter only.
147 |
148 | Args:
149 | ref (GraphMat).
150 | filename (str): Temporary filename to store SVG output.
151 |
152 | Returns:
153 | SVG: IPython SVG wrapper object for graph.
154 |
155 | """
156 |
157 | # Ensure all modules are available
158 | try:
159 | from graphviz import Graph as gvGraph, Digraph as gvDigraph
160 | from IPython.display import SVG
161 | except:
162 | raise Exception("Missing module: graphviz and/or IPython.")
163 | # Traverse graph and generate temporary Digraph/Graph object
164 | output_format = 'svg'
165 | if ref.directed:
166 | graph = gvDigraph(filename, format=output_format)
167 | else:
168 | graph = gvGraph(filename, format=output_format)
169 | if ref is not None:
170 | for src in range(ref.order):
171 | src_id = 'node_' + str(src)
172 | graph.node(src_id, label=str(src))
173 | for dst in range(ref.order):
174 | if ref.adj[src][dst] > 0 and (ref.directed or src >= dst):
175 | graph.edge(src_id, 'node_' + str(dst))
176 | # Render to temporary file and SVG object
177 | graph.render(filename=filename, cleanup=True)
178 | return SVG(filename + '.' + output_format)
179 |
180 |
181 | def display(ref, eng=None):
182 | try:
183 | from graphviz import Source
184 | from IPython.display import display
185 | except:
186 | raise Exception("Missing module: graphviz and/or IPython.")
187 | display(Source(todot(ref), engine = eng))
188 |
189 |
190 | # load / save gra(wgra) format
191 |
192 | def loadgra(filename, multigraph=False):
193 | """Build a new graph from a GRA file.
194 |
195 | Args:
196 | filename (str): File to load.
197 |
198 | Returns:
199 | Graph: New graph.
200 |
201 | Raises:
202 | FileNotFoundError: If file does not exist.
203 |
204 | """
205 |
206 | with open(filename) as f:
207 | directed = bool(int(f.readline()))
208 | order = int(f.readline())
209 | g = GraphMat(order, directed)
210 | for line in f.readlines():
211 | edge = line.strip().split(' ')
212 | (src, dst) = (int(edge[0]), int(edge[1]))
213 | g.addedge(src, dst, multi=multigraph)
214 | return g
215 |
216 | def savegra(G, fileOut):
217 | gra = str(int(G.directed)) + '\n'
218 | gra += str(G.order) + '\n'
219 | for s in range(G.order):
220 | n = G.order if G.directed else s
221 | for adj in range(n):
222 | for i in range(G.adj[s][adj]):
223 | gra += str(s) + " " + str(adj) + '\n'
224 | with open(fileOut, mode='w') as fout:
225 | fout.write(gra)
226 | #
227 | def fromlist(order, directed, edges):
228 | """Build a new graph from an int tuple list.
229 |
230 | Args:
231 | order (int): Order of graph.
232 | directed (bool): True if the graph is directed. False otherwise.
233 | edges (List[(int, int)]): Source/Destination tuple list.
234 |
235 | Returns:
236 | GraphMat: New graph.
237 |
238 | Raises:
239 | IndexError: If either order or edge extremity is invalid.
240 |
241 | """
242 |
243 | # Check order:
244 | if order <= 0:
245 | raise IndexError('Invalid order')
246 | # Build graph
247 | g = GraphMat(order, directed)
248 | for (src, dst) in edges:
249 | g.adj[src][dst] += 1
250 | if not g.directed and src != dst:
251 | g.adj[dst][src] += 1
252 | return g
253 |
254 |
255 |
--------------------------------------------------------------------------------
/Notebooks/algopy/queue.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """Queue module."""
3 |
4 | from collections import deque
5 |
6 | class Queue:
7 | """Simple class for FIFO (first-in-first-out) container."""
8 |
9 | def __init__(self):
10 | """Init queue."""
11 |
12 | self.elements = deque()
13 |
14 | def enqueue(self, elt):
15 | """Add an element to the queue.
16 |
17 | Args:
18 | elt (Any): Element to enqueue.
19 |
20 | Returns:
21 | Queue: The updated queue.
22 |
23 | """
24 |
25 | self.elements.append(elt)
26 | return self
27 |
28 | def dequeue(self):
29 | """Remove and return next element from the queue.
30 |
31 | Returns:
32 | Any: Element from the queue.
33 |
34 | Raises:
35 | IndexError: If queue is empty.
36 |
37 | """
38 |
39 | return self.elements.popleft()
40 |
41 | def isempty(self):
42 | """Check whether queue is empty.
43 |
44 | Returns:
45 | bool: True if queue is empty, False otherwise.
46 |
47 | """
48 |
49 | return len(self.elements) == 0
50 |
--------------------------------------------------------------------------------
/Notebooks/algopy/spanning_forest.py:
--------------------------------------------------------------------------------
1 | # Spanning Forest visualization
2 | # Requires graphviz
3 |
4 | from graphviz import Digraph
5 |
6 | spanning_colors = {'discovery': 'black', 'forward': 'blue', 'backward': 'red', 'cross': 'orange' }
7 |
8 | class SpanningForest:
9 |
10 | def __init__(self, colors=spanning_colors, orders=False):
11 | self.__iner_tree = Digraph(node_attr={'shape': ('plain' if orders else 'oval')})
12 | self.__colors = colors
13 | self.__orders = orders
14 |
15 |
16 | def label(self, v, pre, post):
17 | self.__iner_tree.node(self._lab(v),
18 | label='< >'.format(v, pre, post))
19 |
20 | def discovery(self, src, dst):
21 | self.__iner_tree.edge(self._lab(src), self._lab(dst), color=self.__colors['discovery'])
22 |
23 | def forward(self, src, dst):
24 | self.__iner_tree.edge(self._lab(src), self._lab(dst), constraint='false', color=self.__colors['forward'])
25 |
26 | def backward(self, src, dst):
27 | self.__iner_tree.edge(self._lab(src), self._lab(dst), constraint='false', color=self.__colors['backward'])
28 |
29 | def cross(self, src, dst):
30 | self.__iner_tree.edge(self._lab(src), self._lab(dst), constraint='false', color=self.__colors['cross'])
31 |
32 | def _lab(self, v):
33 | return 'vert{}'.format(v) if self.__orders else str(v)
34 |
35 | def _repr_svg_(self):
36 | return self.__iner_tree._repr_svg_()
37 |
38 | def rank_roots(self, roots):
39 | for i in range(len(roots) - 1):
40 | self.__iner_tree.edge(self._lab(roots[i]), self._lab(roots[i + 1]),
41 | style = 'invis', minlen='8')
42 | with self.__iner_tree.subgraph() as r:
43 | r.attr(rank='same')
44 | for v in roots:
45 | r.node(self._lab(v))
46 |
47 | def _display(self):
48 | '''Displays SVG representation directly in IPython notebook.
49 |
50 | Requires IPython and (through method _repr_svg_) graphviz modules.
51 | '''
52 | try:
53 | from IPython.display import display_svg
54 | except:
55 | raise Exception('Missing moduke: IPtyhon')
56 | display_svg(self)
57 |
58 |
59 | @property
60 | def source(self):
61 | return self.__iner_tree.source
62 |
63 | def __dfs_dir(g, v, pre, post, tree, count):
64 | pre[v] = count
65 | count += 1
66 | for s in g.adjlists[v]:
67 | if pre[s] is None:
68 | tree.discovery(v, s)
69 | count = __dfs_dir(g, s, pre, post, tree, count)
70 | else:
71 | if post[s] is None:
72 | tree.backward(v, s)
73 | else:
74 | if pre[s] < pre[v]:
75 | tree.cross(v, s)
76 | else:
77 | tree.forward(v, s)
78 | post[v] = count
79 | return count + 1
80 |
81 | def dfs_extra_edges_directed(g, v, order=False):
82 | tree = SpanningForest(orders=order)
83 | pre, post = [None] * g.order, [None] * g.order
84 | count = 0
85 | roots = [v]
86 | count = __dfs_dir(g, v, pre, post, tree, count)
87 | for v in range(g.order):
88 | if pre[v] is None:
89 | roots.append(v)
90 | count = __dfs_dir(g, v, pre, post, tree, count)
91 | tree.rank_roots(roots)
92 | if order:
93 | for v in range(g.order):
94 | tree.label(v, pre[v], post[v])
95 | return tree
96 |
97 | def __dfs_undir(g, v, pre, parents, count, tree):
98 | count += 1
99 | pre[v] = count
100 | for s in g.adjlists[v]:
101 | if parents[s] is None:
102 | parents[s] = v
103 | tree.discovery(v, s)
104 | count = __dfs_undir(g, s, pre, parents, count, tree)
105 | else:
106 | if parents[v] != s and pre[s] < pre[v]:
107 | tree.backward(v, s)
108 | return count
109 |
110 | def dfs_extra_edges_undirected(g, v):
111 | parents = [None] * g.order
112 | count = 0
113 | tree = SpanningForest()
114 | pre = [None] * g.order
115 | parents[v] = -1
116 | count = __dfs_undir(g, v, pre, parents, count, tree)
117 | for v in range(g.order):
118 | if parents[v] is None:
119 | parents[v] = -1
120 | count = __dfs_undir(g, v, pre, parents, count, tree)
121 | return tree
122 |
--------------------------------------------------------------------------------
/Notebooks/algopy/stack.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """Stack module."""
3 |
4 | from collections import deque
5 |
6 | class Stack:
7 | """Simple class for LIFO (last-in-first-out) container."""
8 |
9 | def __init__(self):
10 | """Init stack."""
11 |
12 | self.elements = deque()
13 |
14 | def push(self, elt):
15 | """Add an element to the stack.
16 |
17 | Args:
18 | elt (Any): Element to push.
19 |
20 | Returns:
21 | Stack: The updated stack.
22 |
23 | """
24 |
25 | self.elements.append(elt)
26 | return self
27 |
28 | def peek(self):
29 | """Return top element without modifying the stack.
30 |
31 | Returns:
32 | Any: Top element from stack.
33 | """
34 |
35 | return self.elements[len(self.elements)-1]
36 |
37 | def pop(self):
38 | """Remove and return next element from the stack.
39 |
40 | Returns:
41 | Any: Element from stack.
42 | """
43 |
44 | return self.elements.pop()
45 |
46 | def isempty(self):
47 | """Check whether stack is empty.
48 |
49 | Returns:
50 | bool: True if stack is empty, False otherwise.
51 |
52 | """
53 |
54 | return len(self.elements) == 0
55 |
--------------------------------------------------------------------------------
/Notebooks/algopy/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bashardudin/GraphsAndFlows/afdf1d1c60d54abec7484fbaa1b473b9d3d0894b/Notebooks/algopy/tests/__init__.py
--------------------------------------------------------------------------------
/Notebooks/algopy/tests/test_queue.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """Queue test module."""
3 |
4 | from collections import deque
5 |
6 | from ..queue import Queue
7 |
8 | import unittest
9 |
10 | class TestQueue(unittest.TestCase):
11 |
12 | def setUp(self):
13 | self.bag = Queue()
14 |
15 | def test_init(self):
16 | """Test empty queue init."""
17 |
18 | self.assertEqual(deque, type(self.bag.elements))
19 |
20 | def test_isempty(self):
21 | """Test new queue emptyness."""
22 |
23 | self.assertTrue(self.bag.isempty())
24 |
25 | def test_enqueue(self):
26 | """Test enqueuing elements."""
27 |
28 | self.bag = self.bag.enqueue(0)
29 | self.assertEqual(1, len(self.bag.elements))
30 | self.assertEqual(0, self.bag.elements[0])
31 | self.bag = self.bag.enqueue(1)
32 | self.assertEqual(2, len(self.bag.elements))
33 | self.assertEqual(1, self.bag.elements[1])
34 |
35 | def test_dequeue(self):
36 | """Test dequeuing elements."""
37 |
38 | values = [ 0, 1, 2 ]
39 | for val in values:
40 | self.bag.elements.append(val)
41 | for val in values:
42 | self.assertEqual(val, self.bag.dequeue())
43 | self.assertEqual(0, len(self.bag.elements))
44 |
45 | if __name__ == '__main__':
46 | unittest.main()
47 |
--------------------------------------------------------------------------------
/Notebooks/algopy/tests/test_stack.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """Stack test module."""
3 |
4 | from collections import deque
5 |
6 | from ..stack import Stack
7 |
8 | import unittest
9 |
10 | class TestStack(unittest.TestCase):
11 |
12 | def setUp(self):
13 | self.bag = Stack()
14 |
15 | def test_init(self):
16 | """Test empty stack init."""
17 |
18 | self.assertEqual(deque, type(self.bag.elements))
19 |
20 | def test_isempty(self):
21 | """Test new stack emptyness."""
22 |
23 | self.assertTrue(self.bag.isempty())
24 |
25 | def test_push(self):
26 | """Test pushing elements."""
27 |
28 | self.bag = self.bag.push(0)
29 | self.assertEqual(1, len(self.bag.elements))
30 | self.assertEqual(0, self.bag.elements[0])
31 | self.bag = self.bag.push(1)
32 | self.assertEqual(2, len(self.bag.elements))
33 | self.assertEqual(1, self.bag.elements[1])
34 |
35 | def test_pop(self):
36 | """Test dequeuing elements."""
37 |
38 | values = [ 0, 1, 2 ]
39 | for val in values:
40 | self.bag.elements.append(val)
41 | for i in range(len(values) - 1, -1, -1):
42 | self.assertEqual(values[i], self.bag.pop())
43 | self.assertEqual(0, len(self.bag.elements))
44 |
45 | def test_top(self):
46 | """Test peeking at top element."""
47 |
48 | values = [ 0, 1, 2 ]
49 | for val in values:
50 | self.bag.elements.append(val)
51 | self.assertEqual(values[-1], self.bag.top())
52 | self.bag.elements.pop()
53 | self.assertEqual(values[-2], self.bag.top())
54 |
55 |
56 | if __name__ == '__main__':
57 | unittest.main()
58 |
--------------------------------------------------------------------------------
/Notebooks/algopy/tree.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """General Tree module.
3 |
4 | *Warning:* All the functions defined in this module are assumed to receive a non-None
5 | value for their ``ref`` parameter.
6 |
7 | Todo:
8 | * Save to file? Via Dot?
9 | * Load from file -> done!
10 |
11 | """
12 |
13 | from . import queue
14 | from .queue import Queue
15 |
16 |
17 | class Tree:
18 | """Simple class for general tree.
19 |
20 | Attributes:
21 | key (Any): Node key.
22 | children (List[Tree]): Node children.
23 |
24 | """
25 |
26 | def __init__(self, key=None, children=None):
27 | """Init general tree, ensure children are properly set.
28 |
29 | Args:
30 | key (Any).
31 | children (List[Tree]).
32 |
33 | """
34 |
35 | self.key = key
36 |
37 | if children is None:
38 | self.children = []
39 | else:
40 | self.children = children
41 |
42 | @property
43 | def nbchildren(self):
44 | """Number of children of node."""
45 |
46 | return len(self.children)
47 |
48 |
49 | def size(ref):
50 | """Compute size of tree.
51 |
52 | Args:
53 | ref (Tree).
54 |
55 | Returns:
56 | int: The number of nodes of tree.
57 |
58 | """
59 |
60 | s = 1
61 | for i in range(ref.nbchildren):
62 | s += size(ref.children[i])
63 | return s
64 |
65 |
66 | def height(ref):
67 | """Compute height of Tree.
68 |
69 | Args:
70 | ref (Tree).
71 |
72 | Returns:
73 | int: The maximum depth of any leaf.
74 |
75 | """
76 |
77 | h = -1
78 | for i in range(ref.nbchildren):
79 | h = max(h, height(ref.children[i]))
80 | return h + 1
81 |
82 |
83 | def epl(ref, h=0):
84 | """Compute external paths' length.
85 |
86 | Args:
87 | ref (Tree).
88 | h (int): Current height.
89 |
90 | Returns:
91 | int: The total length of paths from root to leaves.
92 |
93 | """
94 |
95 | if ref.nbchildren > 0:
96 | length = 0
97 | for i in range(ref.nbchildren):
98 | length += epl(ref.children[i], h + 1)
99 | return length
100 | else:
101 | return h
102 |
103 |
104 | def search(ref, val):
105 | """Search for a value in tree.
106 |
107 | Args:
108 | ref (Tree).
109 | val (Any): Value to search.
110 |
111 | Returns:
112 | Tree: First node containing key val.
113 |
114 | """
115 |
116 | if ref.key == val:
117 | return ref
118 | else:
119 | for child in ref.children:
120 | found = search(child, val)
121 | if found is not None:
122 | return found
123 | return None
124 |
125 | def __loadtree(s, typelt,i=0):
126 | if i < len(s) and s[i] == '(': # can this test be removed?
127 | i = i + 1 # to skip the '('
128 | T = Tree()
129 | word = ""
130 | while not (s[i] in "()"):
131 | word = word + s[i]
132 | i += 1
133 | T.key = typelt(word)
134 | T.children = []
135 | while s[i] != ')':
136 | (C, i) = __loadtree(s, typelt, i)
137 | T.children.append(C)
138 | i = i + 1 # to skip the ')'
139 | return (T, i)
140 | else:
141 | return None
142 |
143 | def loadtree(path, typelt=int):
144 | # Open file and get full content
145 | file = open(path, 'r')
146 | content = file.read()
147 | # Remove all whitespace characters for easier parsing
148 | content = content.replace('\n', '').replace('\r', '') \
149 | .replace('\t', '').replace(' ', '')
150 | file.close()
151 | # Parse content and return tree
152 | (T, _) = __loadtree(content, typelt)
153 | return T
154 |
155 |
156 | def dot(ref):
157 | """Write down dot format of tree.
158 |
159 | Args:
160 | ref (Tree).
161 |
162 | Returns:
163 | str: String storing dot format of tree.
164 |
165 | """
166 |
167 | s = "graph {\n"
168 | s += "node [shape=circle, fixedsize=true, height=0.5, width=0.5]\n"
169 | q = Queue()
170 | q.enqueue(ref)
171 | while not q.isempty():
172 | ref = q.dequeue()
173 | for child in ref.children:
174 | s = s + " " + str(ref.key) + " -- " + str(child.key) + "\n"
175 | q.enqueue(child)
176 | s += "}"
177 | return s
178 |
179 |
180 | def display(ref, filename='temp'):
181 | """Render a tree to SVG format.
182 |
183 | *Warning:* Made for use within IPython/Jupyter only.
184 |
185 | Args:
186 | ref (Tree).
187 | filename (str): Temporary filename to store SVG output.
188 |
189 | Returns:
190 | SVG: IPython SVG wrapper object for tree.
191 |
192 | """
193 |
194 | # Ensure all modules are available
195 | try:
196 | from graphviz import Graph
197 | from IPython.display import SVG
198 | except:
199 | raise Exception("Missing module: graphviz and/or IPython.")
200 | # Traverse tree and generate temporary Graph object
201 | output_format = 'svg'
202 | graph = Graph(filename, format=output_format)
203 | q = Queue()
204 | q.enqueue(ref)
205 | while not q.isempty():
206 | ref = q.dequeue()
207 | graph.node(str(id(ref)), label=str(ref.key))
208 | for child in ref.children:
209 | graph.edge(str(id(ref)), str(id(child)))
210 | q.enqueue(child)
211 | # Render to temporary file and SVG object
212 | graph.render(filename=filename, cleanup=True)
213 | return SVG(filename + '.' + output_format)
214 |
--------------------------------------------------------------------------------
/Notebooks/graphsTraversals.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Graphs Traversals"
8 | ]
9 | },
10 | {
11 | "cell_type": "markdown",
12 | "metadata": {},
13 | "source": [
14 | "This is a short reminder of traversal types on graphs."
15 | ]
16 | },
17 | {
18 | "cell_type": "code",
19 | "execution_count": null,
20 | "metadata": {},
21 | "outputs": [],
22 | "source": []
23 | }
24 | ],
25 | "metadata": {
26 | "kernelspec": {
27 | "display_name": "Python 3",
28 | "language": "python",
29 | "name": "python3"
30 | },
31 | "language_info": {
32 | "codemirror_mode": {
33 | "name": "ipython",
34 | "version": 3
35 | },
36 | "file_extension": ".py",
37 | "mimetype": "text/x-python",
38 | "name": "python",
39 | "nbconvert_exporter": "python",
40 | "pygments_lexer": "ipython3",
41 | "version": "3.7.0"
42 | }
43 | },
44 | "nbformat": 4,
45 | "nbformat_minor": 2
46 | }
47 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # GraphsAndFlows
2 | Network flows, transportation problems, shortesst paths and scheduling course @Epita
3 |
--------------------------------------------------------------------------------
/Slides/Tex/Style/Mimo_Ionis.sty~:
--------------------------------------------------------------------------------
1 | %%%% This is a style package for Ionisx math beamer presentations.
2 | %%%% The looks of the standard beamer blocks are redefined, some
3 | %%%% maths environnements are as well, and the \photo command for
4 | %%%% the author's photo.
5 |
6 | \ProvidesPackage{Mimo_Ionis}[2016/02/23 Style Mimos Ionis]
7 |
8 | \RequirePackage[T1]{fontenc}
9 | \RequirePackage[french]{babel} % Set up for typography and keywords translation
10 | \RequirePackage{graphicx} % Allows including images
11 | \RequirePackage{tikz} % Needed to tweak graphics
12 | \RequirePackage[most]{tcolorbox} % Needed to define the definition and theorem
13 |
14 |
15 | %%%%%%%%%%%%%%% Setting language translator %%%%%%%%%%%%%%%
16 |
17 | \uselanguage{French}
18 | \languagepath{French}
19 |
20 | %%%%%%%%%%%%%%% Defining colors %%%%%%%%%%%%%%%
21 |
22 | \definecolor{coolblack}{rgb}{0.0, 0.18, 0.39}
23 | \definecolor{sky}{rgb}{0.53, 0.81, 0.92}
24 |
25 | %%%%%%%%%%%%%%% Default theme %%%%%%%%%%%%%%%
26 |
27 | \usetheme{default}
28 | \usecolortheme{dove}
29 |
30 | %%%%%%%%%%%%%%% How does the head and footer look like %%%%%%%%%%%%%%%
31 |
32 | \setbeamertemplate{navigation symbols}{} % To remove the navigation symbols from the bottom of all slides uncomment this line
33 | \setbeamertemplate{headline}[default] % Style of the headline
34 | \setbeamertemplate{footline}[default] % Style of footline
35 |
36 | %%%%%%%%%%%%%%% Itemiez bullets %%%%%%%%%%%%%%%
37 |
38 | \setbeamertemplate{itemize item}[circle] % For the style of item bullets
39 |
40 | %%%%%%%%%%%%%%% Choosing fonts for document %%%%%%%%%%%%%%%
41 |
42 | \usefonttheme{serif} % For only math in serif add onlymath option in brackets
43 |
44 | %%%%%%%%%%%%%%% Setting color and font for frame titles %%%%%%%%%%%%%%%
45 |
46 | \setbeamercolor{frametitle}{fg=coolblack}
47 | \usefonttheme[onlylarge]{structurebold}
48 |
49 | %%%%%%%%%%%%%%% Background wallpaper %%%%%%%%%%%%%%%
50 |
51 | \usebackgroundtemplate{\includegraphics[width=\paperwidth,height=\paperheight]{../../../../img/fond_ppt_math_lignes.png}}
52 |
53 | %%%%%%%%%%%%%%% Command for the author's photo %%%%%%%%%%%%%%%
54 |
55 | \newcommand{\photo}[1]{
56 | \includegraphics[width=3cm]{#1}
57 | }%
58 |
59 | %%%%%%%%%%%%%%% Defining how title page looks like %%%%%%%%%%%%%%%
60 |
61 | \setbeamercolor{title}{fg=coolblack}
62 | \defbeamertemplate*{title page}{customized}[1][]
63 | {
64 | \begin{center}
65 | \vfill
66 | {
67 | \usebeamerfont{title}
68 | \usebeamercolor[fg]{title}
69 | \inserttitle\par
70 | \vspace{5pt}
71 | \usebeamercolor[fg]{subtitle}
72 | {\Large \textsc{\insertsubtitle}}\par
73 | }
74 | \vfill
75 | \insertauthor\par
76 | \insertinstitute\par
77 | \end{center}
78 | }
79 |
80 | %%%%%%%%%%%%%%% Redefining shape of blocks %%%%%%%%%%%%%%%
81 |
82 | \renewenvironment{block}[1]{%
83 | \begin{tcolorbox}[
84 | enhanced,
85 | parbox = false,
86 | attach boxed title to top left={xshift=3mm,yshift=-2.5mm,yshifttext=-1mm},
87 | colback=blue!5!white,
88 | colframe=coolblack,
89 | colbacktitle=coolblack,
90 | adjusted title = {#1},
91 | fonttitle=\bfseries,
92 | arc=0mm,
93 | boxed title style={size=small, top=-3pt, bottom=-2pt, colframe=coolblack, arc=0mm}
94 | ]
95 | }{%
96 | \end{tcolorbox}%
97 | }
98 |
99 | \newenvironment{shyblock}[1]{%
100 | \begin{tcolorbox}[
101 | enhanced,
102 | parbox = false,
103 | attach boxed title to top left={xshift=3mm,yshift=-2.5mm,yshifttext=-1mm},
104 | colback=white,
105 | colframe=coolblack,
106 | colbacktitle=white,
107 | coltitle=coolblack,
108 | adjusted title = {#1},
109 | fonttitle=\bfseries,
110 | arc=0mm,
111 | boxed title style={size=small, top = -3pt, bottom=-2pt, colframe=white, arc=0mm}
112 | ]
113 | }{%
114 | \end{tcolorbox}%
115 | }
116 |
117 | \renewenvironment{exampleblock}[1]{%
118 | \begin{tcolorbox}[
119 | enhanced,
120 | parbox = false,
121 | attach boxed title to top left={xshift=3mm,yshift=-2.5mm,yshifttext=-1mm},
122 | colback=blue!5!white,
123 | colframe=sky,
124 | colbacktitle=sky,
125 | coltitle=coolblack,
126 | adjusted title = {#1},
127 | fonttitle=\bfseries,
128 | arc=0mm,
129 | boxed title style={size=small, top =-3pt, bottom=-2pt, colframe=sky, arc=0mm}
130 | ]
131 | }{%
132 | \end{tcolorbox}%
133 | }
134 |
135 | \renewenvironment{alertblock}[1]{%
136 | \begin{tcolorbox}[
137 | enhanced,
138 | parbox = false,
139 | attach boxed title to top left={xshift=3mm,yshift=-2.5mm,yshifttext=-1mm},
140 | colback=red!5!white,
141 | colframe=red!75!black,
142 | colbacktitle=red!75!black,
143 | adjusted title = {#1},
144 | fonttitle=\bfseries,
145 | arc=0mm,
146 | boxed title style={size=small, top=-3pt, bottom = -2pt, colframe=red!75!black, arc=0mm}
147 | ]
148 | }{%
149 | \end{tcolorbox}%
150 | }
151 |
152 | %%%%%%%%%%%%%%% (Re-)Defining theorem-like environnements %%%%%%%%%%%%%%%
153 |
154 | \newenvironment{thm}[1][\unskip]{ % Theoreme
155 | \par
156 | \noindent
157 | \begin{alertblock}{Th\'eor\`eme #1}
158 | }{\end{alertblock}}
159 |
160 | \newenvironment{prop}[1][\unskip]{ % Proposition
161 | \par
162 | \noindent
163 | \begin{block}{Proposition #1}
164 | }{\end{block}}
165 |
166 | \newenvironment{lem}[1][\unskip]{ % Lemme
167 | \par
168 | \noindent
169 | \begin{shyblock}{Lemme #1}
170 | }{\end{shyblock}}
171 |
172 | \newenvironment{defn}[1][\unskip]{ % Definition
173 | \par
174 | \noindent
175 | \begin{exampleblock}{D\'efinition #1}
176 | }{\end{exampleblock}}
177 |
178 | \newenvironment{rem}[1][\unskip]{ % Remarque
179 | \par
180 | \vspace{.5\baselineskip}
181 | \noindent
182 | \textbf{Remarque #1 :}
183 | }{\vspace{\baselineskip}}
184 |
185 | \newenvironment{exemple}[1][\unskip]{ % Exemple
186 | \par
187 | \vspace{.5\baselineskip}
188 | \noindent
189 | \textbf{Exemple #1 :}
190 | }{\vspace{\baselineskip}}
191 |
192 | \newenvironment{preuve}[1][\unskip]{ % Demonstration
193 | \par
194 | \noindent
195 | \textbf{D\'emonstration #1}
196 |
197 | \vspace{2pt}
198 | }{\hfill $\blacksquare$ \vspace{\baselineskip}}
199 |
200 | \newenvironment{nota}[1][\unskip]{ % Demonstration
201 | \par
202 | \noindent
203 | \textbf{Notation #1 :}
204 | }{\vspace{\baselineskip}}
205 |
206 |
207 | \newenvironment{cor}[1][\unskip]{ % Corollaire
208 | \par
209 | \noindent
210 | \begin{shyblock}{Corollaire #1}
211 | }{\end{shyblock}}
212 |
213 |
214 | %%%%%%%%%%%%%%%%%%%%%%%%%%%
215 |
--------------------------------------------------------------------------------
/Slides/Tex/Style/My_Beamer.sty:
--------------------------------------------------------------------------------
1 | %%%% This is a style package for my own math beamer presentations.
2 | %%%% The looks of the standard beamer blocks are redefined, some maths
3 | %%%% environnements are as well.
4 |
5 | \ProvidesPackage{My_Beamer}[2016/03/25 My_Beamer]
6 |
7 | \RequirePackage[T1]{fontenc}
8 | \RequirePackage{graphicx} % Allows including images
9 | \RequirePackage{tikz} % Needed to tweak graphics
10 | \RequirePackage[most]{tcolorbox} % Needed to define the definition and theorem
11 | \RequirePackage{fourier}
12 |
13 | %%%%%%%%%%%%%%% Defining colors %%%%%%%%%%%%%%%
14 |
15 | \definecolor{mDarkBrown}{HTML}{604c38}
16 | \definecolor{mDarkTeal}{HTML}{23373b}
17 | \definecolor{mLightBrown}{HTML}{EB811B}
18 | \definecolor{mLightGreen}{HTML}{14B03D}
19 |
20 | %%%%%%%%%%%%%%% Default theme %%%%%%%%%%%%%%%
21 |
22 | \usetheme{metropolis}
23 |
24 | %%%%%%%%%%%%%%% How does the head and footer look like %%%%%%%%%%%%%%%
25 |
26 | \setbeamertemplate{navigation symbols}{} % To remove the navigation symbols from the bottom of all slides uncomment this line
27 | \setbeamertemplate{headline}[default] % Style of the headline
28 | \setbeamertemplate{footline}[default] % Style of footline
29 |
30 | %%%%%%%%%%%%%%% Itemiez bullets %%%%%%%%%%%%%%%
31 |
32 | \setbeamertemplate{itemize item}[circle] % For the style of item bullets
33 |
34 | %%%%%%%%%%%%%%% Choosing fonts for document %%%%%%%%%%%%%%%
35 |
36 | \usefonttheme{serif} % For only math in serif add onlymath option in brackets
37 |
38 | %%%%%%%%%%%%%%% Setting color and font for frame titles %%%%%%%%%%%%%%%
39 |
40 | \usefonttheme[onlylarge]{structurebold}
41 |
42 | %%%%%%%%%%%%%%% Redefining tikz functions %%%%%%%%%%%%%%%
43 |
44 | \tikzset{
45 | every overlay node/.style={
46 | draw=white,fill=white, anchor=north west,
47 | },
48 | }
49 | % Usage:
50 | % \tikzoverlay at (-1cm,-5cm) {content};
51 | % or
52 | % \tikzoverlay[text width=5cm] at (-1cm,-5cm) {content};
53 | \def\tikzoverlay{%
54 | \tikz[baseline,overlay]\node[every overlay node]
55 | }%
56 |
57 | %%%%%%%%%%%%%%% Redefining shape of blocks %%%%%%%%%%%%%%%
58 |
59 | \renewenvironment{block}[1]{%
60 | \begin{tcolorbox}[
61 | enhanced,
62 | parbox = false,
63 | attach boxed title to top left={xshift=3mm,yshift=-2.5mm,yshifttext=-1mm},
64 | colback=lightgray!20!white,
65 | colframe=mDarkTeal,
66 | colbacktitle=mDarkTeal,
67 | adjusted title = {#1},
68 | fonttitle=\bfseries,
69 | arc=0mm,
70 | boxed title style={size=small, top=-3pt, bottom=-2pt, colframe=mDarkTeal, arc=0mm}
71 | ]
72 | }{%
73 | \end{tcolorbox}%
74 | }
75 |
76 | \newenvironment{shyblock}[1]{%
77 | \begin{tcolorbox}[
78 | enhanced,
79 | parbox = false,
80 | attach boxed title to top left={xshift=3mm,yshift=-2.5mm,yshifttext=-1mm},
81 | colback=white,
82 | colframe=mDarkTeal,
83 | colbacktitle=white,
84 | coltitle=mDarkTeal,
85 | adjusted title = {#1},
86 | fonttitle=\bfseries,
87 | arc=0mm,
88 | boxed title style={size=small, top = -3pt, bottom=-2pt, colframe=white, arc=0mm}
89 | ]
90 | }{%
91 | \end{tcolorbox}%
92 | }
93 |
94 | \newenvironment{halfshyblock}[1]{%
95 | \begin{tcolorbox}[
96 | enhanced,
97 | parbox = false,
98 | attach boxed title to top left={xshift=3mm,yshift=-2.5mm,yshifttext=-1mm},
99 | colback=white,
100 | colframe=mDarkTeal,
101 | colbacktitle=white,
102 | coltitle=mLightBrown,
103 | adjusted title = {#1},
104 | fonttitle=\bfseries,
105 | arc=0mm,
106 | boxed title style={size=small, top = -3pt, bottom=-2pt, colframe=white, arc=0mm}
107 | ]
108 | }{%
109 | \end{tcolorbox}%
110 | }
111 |
112 | \renewenvironment{exampleblock}[1]{%
113 | \begin{tcolorbox}[
114 | enhanced,
115 | parbox = false,
116 | attach boxed title to top left={xshift=3mm,yshift=-2.5mm,yshifttext=-1mm},
117 | colback=mDarkBrown!10!white,
118 | colframe=mDarkBrown,
119 | colbacktitle=mDarkBrown,
120 | adjusted title = {#1},
121 | fonttitle=\bfseries,
122 | arc=0mm,
123 | boxed title style={size=small, top =-3pt, bottom=-2pt, colframe=mDarkBrown, arc=0mm}
124 | ]
125 | }{%
126 | \end{tcolorbox}%
127 | }
128 |
129 | \renewenvironment{alertblock}[1]{%
130 | \begin{tcolorbox}[
131 | enhanced,
132 | parbox = false,
133 | attach boxed title to top left={xshift=3mm,yshift=-2.5mm,yshifttext=-1mm},
134 | colback=mLightBrown!10!white,
135 | colframe=mLightBrown,
136 | colbacktitle=mLightBrown,
137 | adjusted title = {#1},
138 | fonttitle=\bfseries,
139 | arc=0mm,
140 | boxed title style={size=small, top=-3pt, bottom = -2pt, colframe=mLightBrown, arc=0mm}
141 | ]
142 | }{%
143 | \end{tcolorbox}%
144 | }
145 |
146 | %%%%%%%%%%%%%%% (Re-)Defining theorem-like environnements %%%%%%%%%%%%%%%
147 |
148 | \newenvironment{thm}[1][\unskip]{ % Theoreme
149 | \par
150 | \noindent
151 | \begin{alertblock}{Theorem #1}
152 | }{\end{alertblock}}
153 |
154 | \newenvironment{prop}[1][\unskip]{ % Proposition
155 | \par
156 | \noindent
157 | \begin{block}{Proposition #1}
158 | }{\end{block}}
159 |
160 | \newenvironment{lem}[1][\unskip]{ % Lemme
161 | \par
162 | \noindent
163 | \begin{shyblock}{Lemma #1}
164 | }{\end{shyblock}}
165 |
166 | \newenvironment{defn}[1][\unskip]{ % Definition
167 | \par
168 | \noindent
169 | \begin{exampleblock}{Definition #1}
170 | }{\end{exampleblock}}
171 |
172 | \newenvironment{rem}[1][\unskip]{ % Remarque
173 | \par
174 | \vspace{.2\baselineskip}
175 | \noindent
176 | \textbf{Remark #1 :}
177 | }{\par\vspace{5pt}}
178 |
179 | \newenvironment{exemple}[1][\unskip]{ % Exemple
180 | \par
181 | \vspace{2\baselineskip}
182 | \noindent
183 | \textbf{Example #1 :}
184 | }{\par}
185 |
186 | \newenvironment{demo}[1][\unskip]{ % Proof
187 | % \vspace{2\baselineskip}
188 | \noindent
189 | \textbf{Proof #1 :}
190 | }{\hfill $\blacksquare$ \par}
191 |
192 | \newenvironment{nota}[1][\unskip]{ % Notation
193 | \par
194 | \vspace{.2\baselineskip}
195 | \noindent
196 | \textbf{Notation #1 :}
197 | }{\par}
198 |
199 |
200 | \newenvironment{cor}[1][\unskip]{ % Corollaire
201 | \par
202 | \noindent
203 | \begin{shyblock}{Corollary #1}
204 | }{\end{shyblock}}
205 |
206 | \newenvironment{question}[1][\unskip]{
207 | \par
208 | \noindent
209 | \begin{halfshyblock}{Question #1}
210 | }{\end{halfshyblock}}
211 |
212 | %%%%%%%%%%%%%%% Empasizing text %%%%%%%%%%%%%%%
213 |
214 | \newcommand\mybox[3][mLightBrown]{\textcolor{#1}{\rule{#2}{#3}}}
215 |
216 | \newenvironment{paremph}[1][black]{%
217 | \begin{tcolorbox}[
218 | parbox = false,
219 | blanker,
220 | borderline west={1.2mm}{0pt}{#1}
221 | ]
222 | }{\end{tcolorbox}}
223 |
224 | %%%%%%%%%%%%%%% No indentation enumerate and itemize environments %%%%%%%%%%%%%%%
225 |
226 | \newenvironment{leftenumerate}
227 | {
228 | \setlength{\leftmargini}{0em}
229 | \begin{enumerate}
230 | }
231 | {
232 | \setlength{\leftmargini}{2em}
233 | \end{enumerate}
234 | }
235 |
236 | \newenvironment{leftitemize}
237 | {
238 | \setlength{\leftmargini}{0em}
239 | \begin{itemize}
240 | }
241 | {
242 | \setlength{\leftmargini}{2em}
243 | \end{itemize}
244 | }
245 |
246 | %%%%%%%%%%%%%%% Each section creates a frame with the section title %%%%%%%%%%%%%%%
247 |
248 | \AtBeginSection[]{
249 | \begin{frame}
250 | \vfill
251 | \centering
252 | \usebeamerfont{title}
253 | \usebeamercolor[fg]{title}
254 | \insertsectionhead\par%
255 | \vfill
256 | \end{frame}
257 | }
258 |
259 |
260 | %%%%%%%%%%%%%%%%%%%%%%%%%%%
261 |
--------------------------------------------------------------------------------
/Slides/Tex/Style/My_Beamer.sty~:
--------------------------------------------------------------------------------
1 | %%%% This is a style package for my own math beamer presentations.
2 | %%%% The looks of the standard beamer blocks are redefined, some maths
3 | %%%% environnements are as well.
4 |
5 | \ProvidesPackage{My_Beamer}[2016/03/25 My_Beamer]
6 |
7 | \RequirePackage[T1]{fontenc}
8 | \RequirePackage{graphicx} % Allows including images
9 | \RequirePackage{tikz} % Needed to tweak graphics
10 | \RequirePackage[most]{tcolorbox} % Needed to define the definition and theorem
11 | \RequirePackage{fourier}
12 |
13 | %%%%%%%%%%%%%%% Defining colors %%%%%%%%%%%%%%%
14 |
15 | \definecolor{mDarkBrown}{HTML}{604c38}
16 | \definecolor{mDarkTeal}{HTML}{23373b}
17 | \definecolor{mLightBrown}{HTML}{EB811B}
18 | \definecolor{mLightGreen}{HTML}{14B03D}
19 |
20 | %%%%%%%%%%%%%%% Default theme %%%%%%%%%%%%%%%
21 |
22 | \usetheme{metropolis}
23 |
24 | %%%%%%%%%%%%%%% How does the head and footer look like %%%%%%%%%%%%%%%
25 |
26 | \setbeamertemplate{navigation symbols}{} % To remove the navigation symbols from the bottom of all slides uncomment this line
27 | \setbeamertemplate{headline}[default] % Style of the headline
28 | \setbeamertemplate{footline}[default] % Style of footline
29 |
30 | %%%%%%%%%%%%%%% Itemiez bullets %%%%%%%%%%%%%%%
31 |
32 | \setbeamertemplate{itemize item}[circle] % For the style of item bullets
33 |
34 | %%%%%%%%%%%%%%% Choosing fonts for document %%%%%%%%%%%%%%%
35 |
36 | \usefonttheme{serif} % For only math in serif add onlymath option in brackets
37 |
38 | %%%%%%%%%%%%%%% Setting color and font for frame titles %%%%%%%%%%%%%%%
39 |
40 | \usefonttheme[onlylarge]{structurebold}
41 |
42 | %%%%%%%%%%%%%%% Redefining shape of blocks %%%%%%%%%%%%%%%
43 |
44 | \renewenvironment{block}[1]{%
45 | \begin{tcolorbox}[
46 | enhanced,
47 | parbox = false,
48 | attach boxed title to top left={xshift=3mm,yshift=-2.5mm,yshifttext=-1mm},
49 | colback=lightgray!20!white,
50 | colframe=mDarkTeal,
51 | colbacktitle=mDarkTeal,
52 | adjusted title = {#1},
53 | fonttitle=\bfseries,
54 | arc=0mm,
55 | boxed title style={size=small, top=-3pt, bottom=-2pt, colframe=mDarkTeal, arc=0mm}
56 | ]
57 | }{%
58 | \end{tcolorbox}%
59 | }
60 |
61 | \newenvironment{shyblock}[1]{%
62 | \begin{tcolorbox}[
63 | enhanced,
64 | parbox = false,
65 | attach boxed title to top left={xshift=3mm,yshift=-2.5mm,yshifttext=-1mm},
66 | colback=white,
67 | colframe=mDarkTeal,
68 | colbacktitle=white,
69 | coltitle=mDarkTeal,
70 | adjusted title = {#1},
71 | fonttitle=\bfseries,
72 | arc=0mm,
73 | boxed title style={size=small, top = -3pt, bottom=-2pt, colframe=white, arc=0mm}
74 | ]
75 | }{%
76 | \end{tcolorbox}%
77 | }
78 |
79 | \newenvironment{halfshyblock}[1]{%
80 | \begin{tcolorbox}[
81 | enhanced,
82 | parbox = false,
83 | attach boxed title to top left={xshift=3mm,yshift=-2.5mm,yshifttext=-1mm},
84 | colback=white,
85 | colframe=mDarkTeal,
86 | colbacktitle=white,
87 | coltitle=mLightBrown,
88 | adjusted title = {#1},
89 | fonttitle=\bfseries,
90 | arc=0mm,
91 | boxed title style={size=small, top = -3pt, bottom=-2pt, colframe=white, arc=0mm}
92 | ]
93 | }{%
94 | \end{tcolorbox}%
95 | }
96 |
97 | \renewenvironment{exampleblock}[1]{%
98 | \begin{tcolorbox}[
99 | enhanced,
100 | parbox = false,
101 | attach boxed title to top left={xshift=3mm,yshift=-2.5mm,yshifttext=-1mm},
102 | colback=mDarkBrown!10!white,
103 | colframe=mDarkBrown,
104 | colbacktitle=mDarkBrown,
105 | adjusted title = {#1},
106 | fonttitle=\bfseries,
107 | arc=0mm,
108 | boxed title style={size=small, top =-3pt, bottom=-2pt, colframe=mDarkBrown, arc=0mm}
109 | ]
110 | }{%
111 | \end{tcolorbox}%
112 | }
113 |
114 | \renewenvironment{alertblock}[1]{%
115 | \begin{tcolorbox}[
116 | enhanced,
117 | parbox = false,
118 | attach boxed title to top left={xshift=3mm,yshift=-2.5mm,yshifttext=-1mm},
119 | colback=mLightBrown!10!white,
120 | colframe=mLightBrown,
121 | colbacktitle=mLightBrown,
122 | adjusted title = {#1},
123 | fonttitle=\bfseries,
124 | arc=0mm,
125 | boxed title style={size=small, top=-3pt, bottom = -2pt, colframe=mLightBrown, arc=0mm}
126 | ]
127 | }{%
128 | \end{tcolorbox}%
129 | }
130 |
131 | %%%%%%%%%%%%%%% (Re-)Defining theorem-like environnements %%%%%%%%%%%%%%%
132 |
133 | \newenvironment{thm}[1][\unskip]{ % Theoreme
134 | \par
135 | \noindent
136 | \begin{alertblock}{Theorem #1}
137 | }{\end{alertblock}}
138 |
139 | \newenvironment{prop}[1][\unskip]{ % Proposition
140 | \par
141 | \noindent
142 | \begin{block}{Proposition #1}
143 | }{\end{block}}
144 |
145 | \newenvironment{lem}[1][\unskip]{ % Lemme
146 | \par
147 | \noindent
148 | \begin{shyblock}{Lemma #1}
149 | }{\end{shyblock}}
150 |
151 | \newenvironment{defn}[1][\unskip]{ % Definition
152 | \par
153 | \noindent
154 | \begin{exampleblock}{Definition #1}
155 | }{\end{exampleblock}}
156 |
157 | \newenvironment{rem}[1][\unskip]{ % Remarque
158 | \par
159 | \vspace{.2\baselineskip}
160 | \noindent
161 | \textbf{Remark #1 :}
162 | }{\par\vspace{5pt}}
163 |
164 | \newenvironment{exemple}[1][\unskip]{ % Exemple
165 | \par
166 | \vspace{2\baselineskip}
167 | \noindent
168 | \textbf{Example #1 :}
169 | }{\par}
170 |
171 | \newenvironment{demo}[1][\unskip]{ % Proof
172 | % \vspace{2\baselineskip}
173 | \noindent
174 | \textbf{Proof #1 :}
175 | }{\hfill $\blacksquare$ \par}
176 |
177 | \newenvironment{nota}[1][\unskip]{ % Notation
178 | \par
179 | \vspace{.2\baselineskip}
180 | \noindent
181 | \textbf{Notation #1 :}
182 | }{\par}
183 |
184 |
185 | \newenvironment{cor}[1][\unskip]{ % Corollaire
186 | \par
187 | \noindent
188 | \begin{shyblock}{Corollary #1}
189 | }{\end{shyblock}}
190 |
191 | \newenvironment{question}[1][\unskip]{
192 | \par
193 | \noindent
194 | \begin{halfshyblock}{Question #1}
195 | }{\end{halfshyblock}}
196 |
197 | %%%%%%%%%%%%%%% Empasizing text %%%%%%%%%%%%%%%
198 |
199 | \newcommand\mybox[3][mLightBrown]{\textcolor{#1}{\rule{#2}{#3}}}
200 |
201 | \newenvironment{paremph}[1][black]{%
202 | \begin{tcolorbox}[
203 | parbox = false,
204 | blanker,
205 | borderline west={1.2mm}{0pt}{#1}
206 | ]
207 | }{\end{tcolorbox}}
208 |
209 | %%%%%%%%%%%%%%% No indentation enumerate and itemize environments %%%%%%%%%%%%%%%
210 |
211 | \newenvironment{leftenumerate}
212 | {
213 | \setlength{\leftmargini}{0em}
214 | \begin{enumerate}
215 | }
216 | {
217 | \setlength{\leftmargini}{2em}
218 | \end{enumerate}
219 | }
220 |
221 | \newenvironment{leftitemize}
222 | {
223 | \setlength{\leftmargini}{0em}
224 | \begin{itemize}
225 | }
226 | {
227 | \setlength{\leftmargini}{2em}
228 | \end{itemize}
229 | }
230 |
231 | %%%%%%%%%%%%%%% Each section creates a frame with the section title %%%%%%%%%%%%%%%
232 |
233 | \AtBeginSection[]{
234 | \begin{frame}
235 | \vfill
236 | \centering
237 | \usebeamerfont{title}
238 | \usebeamercolor[fg]{title}
239 | \insertsectionhead\par%
240 | \vfill
241 | \end{frame}
242 | }
243 |
244 |
245 | %%%%%%%%%%%%%%%%%%%%%%%%%%%
246 |
--------------------------------------------------------------------------------
/Slides/Tex/Style/Mystyle.sty:
--------------------------------------------------------------------------------
1 | %%%% This package contains my shortcuts and predefined commandes for
2 | %%%% the Mimo project.
3 |
4 | \ProvidesPackage{Mystyle}[2016/03/03 Mon style Mimo]
5 |
6 | \RequirePackage{amsmath, amssymb, amsfonts}
7 | \RequirePackage{xcolor}
8 | \RequirePackage{colortbl}
9 | \RequirePackage{tcolorbox}
10 | \RequirePackage{wrapfig}
11 |
12 | \RequirePackage{alltt}
13 | \RequirePackage{algpseudocode}
14 | \RequirePackage{algorithm}
15 | \renewcommand{\algorithmicrequire}{\textbf{Input:}}
16 | \renewcommand{\algorithmicensure}{\textbf{Output:}}
17 | \newcommand{\algorithmicbreak}{\textbf{break}}
18 | \newcommand{\Break}{\State \algorithmicbreak}
19 |
20 | \RequirePackage{pgfplots}
21 | \usepgfplotslibrary{fillbetween}
22 | \usepgfplotslibrary{colorbrewer}
23 |
24 | \RequirePackage{tikz, tkz-tab}
25 | \usetikzlibrary{colorbrewer}
26 |
27 | \RequirePackage{multicol}
28 | \RequirePackage{hyperref}
29 | \RequirePackage{centernot}
30 |
31 | %%% Usual commands
32 |
33 | \newcommand{\N}{\mathbb{N}}
34 | \newcommand{\Z}{\mathbb{Z}}
35 | \newcommand{\R}{\mathbb{R}}
36 | \newcommand{\C}{\mathbb{C}}
37 |
38 | \DeclareMathOperator{\dd}{d\!}
39 | \DeclareMathOperator{\Sup}{Sup}
40 | \DeclareMathOperator{\val}{val\!}
41 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/Slides/Tex/Style/Mystyle.sty~:
--------------------------------------------------------------------------------
1 | %%%% This package contains my shortcuts and predefined commandes for
2 | %%%% the Mimo project.
3 |
4 | \ProvidesPackage{Mystyle}[2016/03/03 Mon style Mimo]
5 |
6 | \RequirePackage{amsmath, amssymb, amsfonts}
7 | \RequirePackage{xcolor}
8 | \RequirePackage{colortbl}
9 | \RequirePackage{tcolorbox}
10 | \RequirePackage{wrapfig}
11 |
12 | \RequirePackage{alltt}
13 | \RequirePackage{algpseudocode}
14 | \RequirePackage[Algorithmus]{algorithm}
15 | \renewcommand{\algorithmicrequire}{\textbf{Input:}}
16 | \renewcommand{\algorithmicensure}{\textbf{Output:}}
17 | \newcommand{\algorithmicbreak}{\textbf{break}}
18 | \newcommand{\Break}{\State \algorithmicbreak}
19 |
20 | \RequirePackage{pgfplots}
21 | \usepgfplotslibrary{fillbetween}
22 | \usepgfplotslibrary{colorbrewer}
23 |
24 | \RequirePackage{tikz, tkz-tab}
25 | \usetikzlibrary{colorbrewer}
26 |
27 | \RequirePackage{multicol}
28 | \RequirePackage{hyperref}
29 | \RequirePackage{centernot}
30 |
31 | %%% Usual commands
32 |
33 | \newcommand{\N}{\mathbb{N}}
34 | \newcommand{\Z}{\mathbb{Z}}
35 | \newcommand{\R}{\mathbb{R}}
36 | \newcommand{\C}{\mathbb{C}}
37 |
38 | \DeclareMathOperator{\dd}{d\!}
39 | \DeclareMathOperator{\Sup}{Sup}
40 | \DeclareMathOperator{\val}{val\!}
41 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/Slides/Tex/fixingGraphTheoreticalTerminology.tex:
--------------------------------------------------------------------------------
1 | \documentclass[32pt,aspectratio=169]{beamer}
2 |
3 | \usepackage[utf8]{inputenc} % Character encoding, choose your machine's default
4 | % encoding; latin1 or utf8. If you want it read by
5 | % others choose latin1.
6 | \pdfinfo{
7 | /Author (Bashar Dudin)
8 | /Title (Fixing Graph Theoretical Terminology)
9 | /Subject (Networks and Flows on Graphs)
10 | }
11 |
12 | \usepackage{./Style/My_Beamer} % This is my Beamer style.
13 | \usepackage{./Style/Mystyle} % This is my own defined commands
14 |
15 | %----------------------------------------------------------------------------------------
16 | % TITLE PAGE
17 | %----------------------------------------------------------------------------------------
18 |
19 | \author[BD]{Bashar Dudin}
20 |
21 | \institute[]{EPITA}
22 |
23 | \title{Networks and Flows on Graphs} %
24 | \subtitle{Fixing Graph Theoretical Terminology}
25 |
26 | \begin{document}
27 |
28 | \begin{frame}[plain]
29 | \titlepage % Print the title page as the first slide
30 | \end{frame}
31 |
32 | \begin{frame}{What Is a Graph?}
33 | \begin{defn}
34 | A \emph{directed graph} (or \emph{digraph}) $G$ is given by a set $V$ of
35 | \emph{vertices} together with a set $A$ of \emph{arrows}; an arrow being an
36 | (ordered) couple $a = (x,y)$ of vertices. The vertex $x$ is called
37 | the \emph{source} of $a$ while $y$ is its \emph{target}. We write $G = (V, A)$
38 | for the digraph $G$.
39 | \end{defn}
40 | \pause
41 | \begin{question}
42 | What is the most general digraph you can draw? Can you have two
43 | loops for a single edge? How many arrows in between two vertices?
44 | \end{question}
45 | \end{frame}
46 |
47 | \begin{frame}{What Is a Graph?}
48 | \begin{defn}
49 | An \emph{(undirected) simple graph} $G$ is given by a set $V$ of vertices
50 | together with a set $A$ of \emph{edges}; an edge being an (unordered)
51 | pair $e = \{x,y\}$ of vertices. We write $G = (V, E)$ for the
52 | digraph $G$.
53 | \end{defn}
54 | \pause
55 | \begin{rem}
56 | Notice that to be a \alert{pair} $\{x, y\}$ you need to have
57 | $x \neq y$. So, simple graphs do not have loops.
58 | \end{rem}
59 |
60 | \begin{overlayarea}{\textwidth}{.35\textheight}
61 | \begin{onlyenv}<3-4| handout:1>
62 | There is a canonical way of attaching a simple graph to a digraph
63 | $G$ :
64 | \begin{itemize}
65 | \item<3-> Delete loops of the set of arrows of $G$, these are given by
66 | couples having two identical entries
67 | \item<4-> build up the set of edges as the collectiong of pairs
68 | $\{x, y\}$ for each arrow $(x, y)$ in $G$.
69 | \end{itemize}
70 | \end{onlyenv}
71 | \begin{onlyenv}<5|handout:2>
72 | \begin{question}
73 | Can you think of other ways of defining a graph? For instance how
74 | would you give a definition to allow multiple arrows in a digraph?
75 | Or to allow loops and multiple edges in a graph?
76 | \end{question}
77 | \end{onlyenv}
78 | \end{overlayarea}
79 | \end{frame}
80 |
81 | \begin{frame}{Finding Your Way in Graphs}
82 | \begin{columns}
83 | \begin{column}{.55\textwidth}
84 | \begin{halfshyblock}{Graph}
85 | {\small
86 | \textbf{Chain :} A sequence of edges where each edge has a
87 | common vertex with the preceding one (except the first), the
88 | other being common with the next edge (except the last).
89 |
90 | \textbf{Cycle :} A closed chain.
91 |
92 | \textbf{Simple chain :} Containing each edge at most once.
93 |
94 | \textbf{Elementary chain :} Containing each vertex at most
95 | once.
96 |
97 | \textbf{Hamiltonian chain :} Passing once by each vertex.
98 |
99 | \textbf{Eulerian chain :} Passing once by each edge.
100 |
101 | \textbf{length of chain :} The number of edges in the chain.
102 | }
103 | \end{halfshyblock}
104 | \end{column}
105 | \begin{column}{.55\textwidth}
106 | \begin{halfshyblock}{Digraph}
107 | {\small \textbf{Path :} A sequence of arrows where each
108 | arrow's target is the source of the next arrow (except the
109 | last).
110 |
111 | \vspace{\baselineskip}
112 |
113 | \textbf{Circuit :} A closed path.
114 |
115 | \textbf{Simple path :} Containing each arrow at most once.
116 |
117 | \textbf{Elementary path :} Containing each vertex at most
118 | once.
119 |
120 | \textbf{Hamiltonian path :} Passing once by each vertex.
121 |
122 | \textbf{Eulerian path :} Passing once by each arrow.
123 |
124 | \textbf{length of chain :} The number of arrows in the chain.
125 | }
126 | \end{halfshyblock}
127 | \end{column}
128 | \end{columns}
129 | \end{frame}
130 |
131 | \begin{frame}{Connectedness}
132 | \begin{columns}[T]
133 | \begin{column}{.55\textwidth}
134 | \begin{halfshyblock}{Graph}
135 | {\small
136 | \textbf{Connectedness :} A graph is said to be
137 | \emph{connected} if any two distinct vertices are the endpoints of
138 | a chain.
139 |
140 | \textbf{Connected components :} Maximal subgraphs that are
141 | connected.
142 | }
143 | \end{halfshyblock}
144 | \end{column}
145 | \begin{column}{.55\textwidth}
146 | \begin{halfshyblock}{Digraph}
147 | {\small
148 | \textbf{Strong connectedness :} A digraph is said to be
149 | \emph{strongly connected} if any two distinct vertices are the
150 | initial source and target of a path.
151 |
152 | \textbf{Strongly connected components :} Maximal subraphs
153 | that are strongly connected.}
154 | \end{halfshyblock}
155 | \end{column}
156 | \end{columns}
157 | \vspace{\baselineskip}
158 | \begin{rem}
159 | A digraph is said to be connected if its underlying graph is
160 | connected. Connected components of a digraph are defined the
161 | same way.
162 | \end{rem}
163 | \end{frame}
164 |
165 | \begin{frame}{Two extreme cases of connected graphs}
166 | \begin{columns}[T]
167 | \begin{column}{.55\textwidth}
168 | \begin{halfshyblock}{Trees}
169 | {\small
170 | A tree $T$ is a graph where each two vertices are linked by
171 | exactly one chain. It is equivalently given by
172 | \begin{itemize}
173 | \item $T$ is connected and cycle-free
174 | \item $T$ is connected of maximal order
175 | \item $T$ is connected and deleting any edge disconnects it
176 | \item $T$ is cycle-free and adding any edge creates one.
177 | \end{itemize}
178 | }
179 | \end{halfshyblock}
180 | \end{column}
181 | \begin{column}{.55\textwidth}
182 | \begin{halfshyblock}{Complete Graphs}
183 | {\small
184 | The complete graph $\mathcal{K}_n$ is the graph having $n$
185 | vertices and all possible edges linking them.
186 |
187 | \vspace{\baselineskip}
188 |
189 | It has exactly $\displaystyle{\frac{n(n-1)}{2}}$ edges.
190 |
191 | \vspace{\baselineskip}
192 |
193 | Can you draw $\mathcal{K}_5$ on a paper without having two
194 | edges overlapping?
195 | }
196 | \end{halfshyblock}
197 | \end{column}
198 | \end{columns}
199 | \end{frame}
200 |
201 | \begin{frame}{Adjacency Matrix}
202 | \begin{defn}
203 | Let $G = (V, E)$ be a graph. Two distinct vertices of $G$ are said
204 | to be adjacent if they are endpoints of the same edge.
205 | \end{defn}
206 | \pause One can represent a graph in a machine in one of the two
207 | following ways:
208 | \begin{itemize}
209 | \item<3->[\textcolor<5->{lightgray!30!white}{\textbullet}]
210 | \textcolor<5->{lightgray!30!white}{As a collection of vertices, each
211 | coming with its list of adjacent vertices}
212 | \item<4-> As a matrix called the \emph{adjacency matrix} of the graph.
213 | \end{itemize}
214 | \end{frame}
215 |
216 | \begin{frame}{Adjacency Matrix}
217 | \begin{defn}
218 | Let $G$ be a graph (resp. digraph) having $n$ vertices. The
219 | \emph{adjacency matrix} of $G$ is a square matrix having $n$
220 | columns and $n$ rows, identically indexed by the vertices. Entry
221 | $(i, j)$ is $1$ iff there is an edge (arrow) from $i$ to $j$,
222 | otherwise it is zero.
223 | \end{defn}
224 | \pause
225 | \begin{rem}
226 | The adjacency matrix of a graph is symmetric. A digraph having a
227 | symmetric adjacency matrix has, for any given arrow $(x, y)$
228 | between distinct vertices, an arrow $(y, x)$ going the other way
229 | around. \pause That's the reason why some mathematical textbooks see a
230 | graph as a digraph having this property. In that context arrows
231 | are called half-edges.
232 | \end{rem}
233 | \pause
234 | \begin{question}
235 | Do you know any interesting theoretical results about symmetric
236 | matrices?
237 | \end{question}
238 | \end{frame}
239 |
240 | \begin{frame}{Adjacency Matrix}
241 | \begin{prop}
242 | Let $G$ be either a graph or a digraph and write $M$ for its
243 | adjacency matrix. For any given $k \in \N^*$, the matrix $M^k$ has
244 | entry $(i, j)$ equal to the number of chains (paths) having source
245 | $i$ and target $j$.
246 | \end{prop}
247 | \pause
248 | \setlength\columnseprule{.1pt}
249 | \begin{multicols}{2}
250 | \begin{demo}
251 | This is done by induction. In case $k = 1$, a path of length $1$
252 | is just an edge (or an arrow) and this is just the definition of
253 | the adjacency matrix. \pause Assume that entries of the matrix
254 | $M^k$ correspond to the number of chains (paths) from the row to
255 | the column index. Let $a_k[i, j]$ be the $(i, j)$ coefficient of
256 | $M^k$. Then the entry $a_{k+1}[i, j]$ of $M^{k+1}$ is given by
257 | \begin{align*}
258 | a_{k+1}[i, j] &= \sum_{\ell = 1}^n a_k[i, \ell]a_1[\ell, j]\\
259 | & = \sum_{\big\{\ell \big| \textrm{$\ell$ is adjacent to $j$}\big\}} a_k[i, \ell]
260 | \end{align*}
261 | which is exactly what we are looking for.
262 | \end{demo}
263 | \end{multicols}
264 | \end{frame}
265 |
266 | \begin{frame}{Generalization and Variant of Adjacency Matrix}
267 | \begin{defn}
268 | Let $G$ be a graph (resp. digraph) having $n$ vertices and
269 | \emph{weighted} edges (resp. arrows). The \emph{adjacency matrix}
270 | of $G$ is a square matrix having $n$ columns and $n$ rows,
271 | identically indexed by the vertices. If there is an edge from $i$
272 | to $j$ then entry $(i, j)$ gets the weight of that edge, otherwise
273 | entry $(i, j)$ is zero.
274 | \end{defn}
275 | \pause Given such a graph $G$ with possible weights different from
276 | $1$, then the $k$-th power of its adjacency matrix $M$ is less
277 | easily interpretable; the contribution of each edge or arrow to a
278 | path will be taken with the corresponding weight. \pause
279 |
280 | \vspace{\baselineskip}
281 |
282 | Sometimes we are only interested in the fact there is an edge,
283 | arrow, chain or path between two given vertices. In that case we
284 | look at the adjacency matrix as a \emph{boolean} matrix. This will
285 | be worked out in an exercice later on.
286 | \end{frame}
287 |
288 | \begin{frame}
289 | \begin{center}
290 | {\Large \textbf{It's all for now!}}
291 | \end{center}
292 | \end{frame}
293 |
294 |
295 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
296 |
297 | \end{document}
298 |
299 | %%% Local Variables:
300 | %%% mode: latex
301 | %%% TeX-master: t
302 | %%% End:
303 |
--------------------------------------------------------------------------------
/Slides/Tex/maximumFlow.tex:
--------------------------------------------------------------------------------
1 | \documentclass[32pt, aspectratio=169]{beamer}
2 |
3 | \usepackage[utf8]{inputenc} % Character encoding, choose your machine's default
4 | % encoding; latin1 or utf8. If you want it read by
5 | % others choose latin1.
6 | \pdfinfo{
7 | /Author (Bashar Dudin)
8 | /Title (Maximum Flow Problem)
9 | /Subject (Networks and Flows on Graphs)
10 | }
11 |
12 | \usepackage{./Style/My_Beamer} % This is my Beamer style.
13 | \usepackage{./Style/Mystyle} % This is my own defined commands
14 |
15 | %----------------------------------------------------------------------------------------
16 | % TITLE PAGE
17 | %----------------------------------------------------------------------------------------
18 |
19 | \author[BD]{Bashar Dudin}
20 |
21 | \institute[]{EPITA}
22 |
23 | \title{Networks and Flows on Graphs} %
24 | \subtitle{Maximum Flow Problem}
25 |
26 | \begin{document}
27 |
28 | \begin{frame}[plain]
29 | \titlepage % Print the title page as the first slide
30 | \end{frame}
31 |
32 | \begin{frame}{What is it about?}
33 | \begin{halfshyblock}{Maximum Flow Problem}
34 | You have a water network together with a unique source. Each water
35 | conduct has a maximum water flow capacity. Using the whole network
36 | how can you maximize the water flow at a given sink?
37 | \end{halfshyblock}
38 | \end{frame}
39 |
40 | \begin{frame}{Mathematical Modeling}
41 | A (transportation) network is a simple digraph $G = (V, A)$ having a
42 | single source $s$, a single sink $t$, and for each arrow $a$ of $G$
43 | a valued capacity $c(a)$.
44 | \pause
45 | \begin{defn}
46 | A flow on a network $G$ is a map $f: A \to \R_+$ such that:
47 | \begin{itemize}
48 | \item For each $a \in A$, $f(a) \leq c(a)$,
49 | \item For each vertex $v$, except for the source and sink, the sum
50 | of values $f$ takes on ingoing arrows is equal to the sum taken
51 | by $f$ on outgoing arrows. In a more pedantic fashion
52 | \begin{displaymath}
53 | \forall v \in V\setminus \{s, t\}, \quad \sum_{\{a | a \to s\}} f(a) = \sum_{\{a | s \to a\}}f(a)
54 | \end{displaymath}
55 | \end{itemize}
56 | \end{defn}
57 | \end{frame}
58 |
59 | \begin{frame}{Mathematical Modeling}
60 | \begin{defn}
61 | The value $\val\big[f\big]$ of a flow $f$ on a network $G = (V, A)$ is the
62 | sum of values taken by $f$ on arrows going into $t$.
63 | \end{defn}
64 | \pause
65 | \begin{halfshyblock}{Maximum Flow Problem}
66 | Given a network $G$ find a flow $f$ on $G$ with maximum value
67 | flow.
68 | \end{halfshyblock}
69 | \end{frame}
70 |
71 | \begin{frame}{Cuts}
72 | \begin{defn}[of a cut]
73 | A cut of a digraph $G=(X, A)$ is a subset $S$ of vertices such that $S$
74 | contains the source $s$ but not the sink $t$.
75 | \end{defn}
76 | \pause
77 | We write $\overline{S}$ for the complement of $S$ in $X$, the set
78 | of arrows having tail in $S$ and head in $\overline{S}$ is written
79 | $\big(S, \overline{S} \big)$.
80 | \begin{rem}
81 | The two simplest cuts are respectively given by the cut only
82 | containing the source and the one containing every vertex but the sink.
83 | \end{rem}
84 | \pause
85 | \begin{defn}
86 | Given a flow $f$ on a network $G= (X, A)$. The value flow
87 | $f\big[S\big]$ at a cut $S$ of $G$ is the sum
88 | $f\big[S, \overline{S} \big]$ of values taken by $f$ on elements in
89 | $\big(S, \overline{S}\big)$ minus the sum $f\big[\overline{S}, S\big]$
90 | of values taken by $f$ on $\big(\overline{S}, S\big)$.
91 | \end{defn}
92 | \end{frame}
93 |
94 | \begin{frame}{Cuts}
95 | \begin{prop}
96 | Given a flow $f$ on a network $G$ the value flow at any cut
97 | is independant of the cut.
98 | \end{prop}
99 | \begin{overlayarea}{\textwidth}{.65\textheight}
100 | \begin{onlyenv}<2| handout:1>
101 | \vspace{2pt}
102 | This means the value of a given flow can be recovered as the
103 | value at any cut. In particular, the value flow is equal to the
104 | sum of values taken by the flow at arrows going out of the
105 | source.
106 | \end{onlyenv}
107 |
108 | \begin{onlyenv}<3-| handout:2>
109 | \vspace{2pt}
110 | \begin{demo}
111 | Let $S_\infty$ be the cut of $G$ containing everything but the
112 | sink. Let
113 | $S \subsetneq S_1 \subsetneq \cdots \subsetneq S_\infty$ be a
114 | maximal sequence of cuts (convince yourself that $S_{k+1}$ has
115 | exactly one more vertex than $S_k$). By definition
116 | \begin{displaymath}
117 | f\big[S_\infty\big] = \val\big[f\big]
118 | \end{displaymath}
119 | Let $v_{k+1}$ be the only vertex in $S_{k+1}$ but not in $S_k$.
120 | \begin{displaymath}
121 | f\big[S_{k+1}\big] =
122 | f\big[S_{k}\big] - \sum_{S_{k} \to a \to v_{k+1}} f(a)
123 | + \sum_{v_{k+1} \to a \to S_{k}} f(a)
124 | + \sum_{v_{k+1} \to a \to \smash{\overline{S}}_{k+1}} f(a)
125 | - \sum_{\smash{\overline{S}_{k+1}}\to a \to v_{k+1}} f(a)
126 | \end{displaymath}
127 | These last four terms are exactly the difference between the
128 | values of $f$ at ingoing arrows into $v_{k+1}$ and outgoing ones
129 | from $v_{k+1}$. This difference is zero.
130 | \end{demo}
131 | \end{onlyenv}
132 | \end{overlayarea}
133 | \end{frame}
134 |
135 | \begin{frame}{Cuts}
136 | \begin{defn}
137 | Given an s-t cut $S$ of $G$, we call \emph{capacity} of $S$ the
138 | non-negative number
139 | \begin{displaymath}
140 | c\big[S\big] = \sum_{a \in (S, \smash{\overline{S}})} c(a).
141 | \end{displaymath}
142 | \end{defn}
143 | \begin{halfshyblock}{Facts}
144 | Let $f$ be a flow on a network $G$ and let $S$ be an s-t cut of
145 | $G$.
146 | \begin{itemize}
147 | \item $\val\big[f\big] \leq c\big[S\big]$
148 | \item $\val\big[f\big] = c\big[S\big]$ iff for all
149 | $a \in \big(S, \overline{S}\big)$, $f(a) = c(a)$ and for all
150 | $a \in \big(\overline{S}, S\big)$, $f(a) = 0$.
151 | \end{itemize}
152 | \end{halfshyblock}
153 | Thus, if $\val\big[f\big] = c\big[S\big]$ then $f$ is a flow having
154 | maximal flow value and $S$ is an s-t cut having minimal capacity.
155 | \end{frame}
156 | \begin{frame}{Max-Flow Min-Cut Theorem}
157 | \begin{thm}
158 | The maximum value over all s-t flows is equal to the minimum
159 | capacity over all s-t cuts.
160 | \end{thm}
161 | \pause
162 | A more precise statement is to say that, given a network $G$, there
163 | is a flow $f$ and an s-t cut $S$ such that
164 | $\val\big[f\big] = c\big[S\big]$ iff $f$ has maximum value among
165 | flows on $G$ and $S$ has minimum capacity among s-t cuts of $G$.
166 | \pause
167 | \begin{halfshyblock}{Conclusion}
168 | Finding the maximum value of a flow is equivalent to finding a
169 | minimizing cut.
170 | \end{halfshyblock}
171 | \end{frame}
172 |
173 | \begin{frame}{Ford-Fulkerson Algorithm}
174 | A chain $C$ in a network $G$, joining the source $s$ to the sink
175 | $t$, comes with a natural orientation (a choice of an arrow for each
176 | edge) consistantly going from the source to the sink. We write $C_+$
177 | the set of arrows of $G$ supported on $C$ and matching its
178 | orientation. We write $C_-$ the set of arrows of $G$ supported on
179 | $C$ and opposite to that orientation. \pause
180 | \begin{defn}
181 | Let $f$ be a flow on a network $G$. An \emph{augmenting chain} in $G$ is a chain
182 | $C$ joining the source $s$ to the sink $t$, such that
183 | \begin{displaymath}
184 | \alpha = \min\Big\{\min_{a \in C_+}c(a)-f(a), \min_{a \in C_-}f(a)\Big\} > 0
185 | \end{displaymath}
186 | \end{defn}
187 | \end{frame}
188 |
189 | \begin{frame}{Ford-Fulkerson Algorithm}
190 | Let $f$ be a flow on a network $G$. Given an augmenting chain $C$ in
191 | $G$ one can modify $f$ along $C$ (and $C$ alone) by adding $\alpha$
192 | to each arrow in $C_+$ and substracting $\alpha$ to each arrow in
193 | $C_-$. Looking at the value of this new flow $\varphi$ at the source
194 | one can see that
195 | \begin{displaymath}
196 | \val[\varphi] = \val[f] + \alpha
197 | \end{displaymath}
198 | This shows that $f$ was not a flow of maximim flow value. \pause In fact
199 | \begin{prop}
200 | A flow is of maximum flow value on a network $G$ iff there are no
201 | augmenting chains in $G$.
202 | \end{prop}
203 | \pause
204 | \begin{rem}
205 | The fact a flow on a network that doesn't have any augmenting
206 | chains is of maximal flow value is harder to grasp. You can get a
207 | proof in \emph{Introduction to Algorithms} by Thomas H.~Cormen and
208 | al.
209 | \end{rem}
210 | \end{frame}
211 |
212 | \begin{frame}{Ford-Fulkerson Algorithm}
213 | \begin{algorithm}[H]
214 | \caption{Ford-Fulkerson Algorithm}
215 | \small{
216 | \begin{algorithmic}[1]
217 | \Statex
218 | \Require $G$ a network and $f$ a flow on $G$
219 | \Ensure a maximal flow on $G$
220 | \Statex
221 | \Procedure{Ford-Fulkerson}{$G$, $f$}
222 | \State $(C, \alpha) \gets$ \Call{AugmentingChain}{$G$, $f$}
223 | \While{$C \neq$ \textbf{None}}
224 | \State $f$ is increased or decreased by $\alpha$ on arrows in $C$ depending on orientation
225 | \State $(C, \alpha) \gets$ \Call{AugmentingChain}{$G$, $f$}
226 | \EndWhile
227 | \EndProcedure
228 | \Statex
229 | \end{algorithmic}
230 | }
231 | \end{algorithm}
232 | \end{frame}
233 |
234 | \begin{frame}{Ford-Fulkerson Algorithm}
235 | \begin{algorithm}[H]
236 | \caption{Finding an augmenting chain}
237 | \small{
238 | \begin{algorithmic}[1]
239 | \Statex
240 | \Require $G$ a network and $f$ a flow on $G$
241 | \Ensure an augmenting chain on $G$ if any, and $\alpha$
242 | \Statex
243 | \Function{AugmentingChain}{$G$, $f$}
244 | \State Mark the source by a $+$
245 | \State Mark head $h$ of any unsaturated arrow $(t, h)$, whose tail is marked, by $+t$
246 | \State Mark tail $t$ of any arrow $(t, h)$ having non-zero flow, whose head is marked, by $-h$
247 | \If{sink is marked}
248 | \State \Return an augmenting chain $C$ by following marks from the sink to the source, and $\alpha$
249 | \EndIf
250 | \EndFunction
251 | \Statex
252 | \end{algorithmic}
253 | }
254 | \end{algorithm}
255 | \end{frame}
256 |
257 | \begin{frame}{Termination}
258 | \begin{halfshyblock}{Termination}
259 | The Ford-Fulkerson algorithm terminates if all capacities and flow
260 | values on arrows are rational.
261 | \end{halfshyblock}\pause
262 | This is clear : if flow is not of maximal value, we can find an
263 | augmenting chain along which we can increase flow value. At some
264 | point we get a maximal flow. \pause As to why we get a flow of
265 | maximal value : launch Ford-Fulkerson's algorithm one last time,
266 | write $S$ for all marked vertices (this is not the set of all
267 | vertices because there is no augmenting chains), then the set of all
268 | arrows in $\big(S, \overline{S}\big)$ are saturated and all those in
269 | $\big(\overline{S}, S\big)$ get flow value $0$. This is enough to
270 | say that the capacity of s-t cut $S$ is equal to the value flow we
271 | got; i.e. we have a minimal cut and thus a maximal flow.
272 | \begin{rem}
273 | If you google the Ford-Fulkerson algorithm, you should be able to
274 | find counter-examples in the case of irrational capacities.
275 | \end{rem}
276 | \end{frame}
277 |
278 | \begin{frame}{Complexity}
279 | The complexity of the Ford-Fulkerson algorithm depends on how
280 | efficient you are to find augmentig paths, that's why it is
281 | sometimes called the Ford-Fulkerson \emph{method} rather than
282 | algorithm. \pause Without specifying how we visit vertices we have
283 | that
284 | \begin{halfshyblock}{Complexity}
285 | Given a network $G = (V, A)$ with integer capacities and maximal
286 | value flow $m$ the Ford-Fulkerson complexity is $O\big(ma\big)$,
287 | where $a$ is the number of arrows of $G$.
288 | \end{halfshyblock}
289 | To increase flow value by $1$ you need to find an augmenting path by
290 | going through arrows of $G$, to possibly mark their sources and
291 | targets. Starting by the $0$ flow you need to do it at worst $m$
292 | times, each time going through all arrows. \pause
293 | \begin{question}
294 | Can you imagine modifying the given algorithm for a better
295 | complexity?
296 | \end{question}
297 | \end{frame}
298 |
299 | \begin{frame}{Further readings}
300 | We are done with the basics, we'll be going through a couple of
301 | exercices about maximal flows and matchings. \pause Your are
302 | encouraged to read about the following two related topics
303 | \begin{itemize}
304 | \item maximal flows at minimal costs
305 | \item general preference based matchings (uses what is sometimes
306 | called the \emph{hungarian method}).
307 | \end{itemize}
308 | \end{frame}
309 |
310 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
311 |
312 | \end{document}
313 |
314 |
315 | % Notice that given a flow $f$ on a network $G$ the value of $f$ is
316 | % equally the sum of the value flow on arrows going out of the source
317 | % (minus the value at the source if there is any). \pause Here is a
318 | % way to convince yourself of this fact: \pause Given a vertex $v$ of $G$
319 | % call a predecessor of $v$ the tail of any arrow going into $v$. The
320 | % value flow of $f$ is the sum of values taken at arrows going into
321 | % the sink $t$. The balancing condition at each vertex says this is
322 | % also the sum of values taken by $f$ at arrows going into each
323 | % predecessor of $t$. If you're careful enough about termination of
324 | % such process you can prove the previous claim. It will be proven in
325 | % a more general context.
326 |
327 | %%% Local Variables:
328 | %%% mode: latex
329 | %%% TeX-master: t
330 | %%% End:
331 |
--------------------------------------------------------------------------------
/Slides/Tex/projectPlanning.tex:
--------------------------------------------------------------------------------
1 | \documentclass[32pt,aspectratio=169]{beamer}
2 |
3 | \usepackage[utf8]{inputenc} % Character encoding, choose your machine's default
4 | % encoding; latin1 or utf8. If you want it read by
5 | % others choose latin1
6 | \pdfinfo{
7 | /Author (Bashar Dudin)
8 | /Title (Project Scheduling)
9 | /Subject (Networks and Flows on Graphs)
10 | }
11 |
12 | \usepackage{./Style/My_Beamer} % This is my Beamer style.
13 | \usepackage{./Style/Mystyle} % This is my own defined commands
14 |
15 | %----------------------------------------------------------------------------------------
16 | % TITLE PAGE
17 | %----------------------------------------------------------------------------------------
18 |
19 | \author[BD]{Bashar Dudin}
20 |
21 | \institute[]{EPITA}
22 |
23 | \title{Networks and Flows on Graphs} %
24 | \subtitle{Project Scheduling}
25 |
26 | \begin{document}
27 |
28 | \begin{frame}[plain]
29 | \titlepage % Print the title page as the first slide
30 | \end{frame}
31 |
32 | \begin{frame}{What Is It About ?}
33 | \begin{halfshyblock}{A Project Scheduling Problem}
34 | We're confronted with a project scheduling (or planning) problem
35 | if, in order to achieve an \emph{objective}, we need to go through
36 | a set of \emph{tasks}, each having limited \emph{ressources} and
37 | the set of which is subject to a number of \emph{constraints}.
38 | \end{halfshyblock}
39 | \pause
40 | \begin{itemize}
41 | \item \emph{Tasks} can only be defined once you know what you are
42 | dealing with, the hard part is to make full sense of how you
43 | decompose your project into tasks
44 | \item \emph{Ressources} are generally thought of as the needed time
45 | for a task to be accomplished, it can also be funds, the number of
46 | needed employees, etc ...
47 | \item \emph{Constraints} are grouped into three big types :
48 | \emph{potential constraints}, \emph{disjunctive constraints} and
49 | \emph{cumulative constraints}.
50 | \end{itemize}
51 | \end{frame}
52 |
53 | \begin{frame}{Types of Constraints}
54 | \textbf{Potential constraints}
55 | \begin{paremph}
56 | \begin{itemize}
57 | \item[] These are \emph{precedence constraints} and
58 | \emph{constraints of temporal position}. The former correspond
59 | to constraints of type : ``for task $B$ to start task $A$ has to
60 | be finished'' ; these are about the order
61 | in which tasks take place. The constraints of temporal position
62 | correspond to constraints of type : ``task $A$ cannot start
63 | before January, $2$''. Mathematically, they are modeled
64 | identically.
65 | \end{itemize}
66 | \end{paremph}
67 | \textbf{Disjunctive constraints}
68 | \begin{paremph}
69 | \begin{itemize}
70 | \item[] These are constraints of type : ``tasks $A$ and $B$ cannot
71 | happen simultaneously''.
72 | \end{itemize}
73 | \end{paremph}
74 | \textbf{Cumulative constraints}
75 | \begin{paremph}
76 | \begin{itemize}
77 | \item[] These are relative to the evolution
78 | of resources needed to accomplish a task. They are generally
79 | hard to model.
80 | \end{itemize}
81 | \end{paremph}
82 | \end{frame}
83 |
84 | \begin{frame}{Types of Constraints}
85 | \textbf{Potential constraints}
86 | \begin{paremph}
87 | \begin{itemize}
88 | \item[] These are \emph{precedence constraints} and
89 | \emph{constraints of temporal position}. The former correspond
90 | to constraints of type : ``for task $B$ to start task $A$ has to
91 | be finished'' ; these are about the order
92 | in which tasks take place. The constraints of temporal position
93 | correspond to constraints of type : ``task $A$ cannot start
94 | before January, $2$''. Mathematically, they are modeled
95 | identically.
96 | \end{itemize}
97 | \end{paremph}
98 | \color{lightgray}{
99 | \textbf{Disjunctive constraints}
100 | \begin{paremph}[lightgray]
101 | \begin{itemize}
102 | \item[] \color{lightgray}{These are constraints of type : ``tasks $A$ and $B$ cannot
103 | happen simultaneously''.}
104 | \end{itemize}
105 | \end{paremph}
106 | \textbf{Cumulative constraints}
107 | \begin{paremph}[lightgray]
108 | \begin{itemize}
109 | \item[] \color{lightgray}{These are relative to the evolution
110 | of resources needed to accomplish a task. They are generally
111 | hard to model.}
112 | \end{itemize}
113 | \end{paremph}
114 | }
115 | \end{frame}
116 |
117 | \begin{frame}{What Are We Looking for ?}
118 | There are three things we're interested in when dealing with
119 | scheduling problems (assuming we only have potential constraints)
120 | \begin{itemize}
121 | \item<1-> earliest dates at which tasks can start
122 | \item<2-> latest dates ; once the minimum date has been computed
123 | \item<3-> margins, i.e. the difference between latest and earliest
124 | date of a task.
125 | \end{itemize}
126 | \pause[4]
127 | We shall working two standard approaches aiming at answering these
128 | $3$ related questions : the MPM method (the french method) and PERT
129 | method (the american one).
130 | \end{frame}
131 |
132 | \begin{frame}{Scheduling methods}
133 | \textbf{MPM (Meta Potential Method)}
134 | \begin{paremph}
135 | \begin{itemize}
136 | \item[] In the MPM approach tasks are understood as vertices of a
137 | graph, whose arrows correspond to precedence constraints. Each
138 | arrow is valued by a number representing the time between the
139 | start of its origin till the start of its target.
140 | \end{itemize}
141 | \end{paremph}
142 | \pause
143 | \textbf{PERT (Program Evaluation and Review Technique)}
144 | \begin{paremph}
145 | \begin{itemize}
146 | \item[] In the PERT case, the tasks are represented by arrows,
147 | while vertices should be understood as intermediate achievements
148 | attained once a task is completed. An arrow is valued by the
149 | time the corresponding task takes. Using a PERT diagram needs
150 | serious work on the chosen way of modeling the problem at
151 | hand. It's advantage in respect to the MPM approach is the fact
152 | it is better suited when randomness is involved.
153 | \end{itemize}
154 | \end{paremph}
155 | \end{frame}
156 |
157 | \begin{frame}
158 | \frametitle{Working Example}
159 | Consider a project given by tasks a to g, under the following
160 | conditions of resource and constraints
161 | \begin{figure}
162 | \begin{tabular}{|c|c|c|}
163 | \hline
164 | Tasks & Needed Time & Constraints \\
165 | \hline
166 | a & $6$ & \\
167 | \hline
168 | b & $3$ & \\
169 | \hline
170 | c & $6$ & \\
171 | \hline
172 | d & $2$ & b accomplished \\
173 | \hline
174 | e & $4$ & b accomplished \\
175 | \hline
176 | f & $3$ & d and a accomplished \\
177 | \hline
178 | g & $1$ & f, e, c accomplished \\
179 | \hline
180 | \end{tabular}
181 | \end{figure}
182 | \end{frame}
183 |
184 | \begin{frame}
185 | \frametitle{Working Example : MPM model}
186 | \begin{onlyenv}<1>
187 | Each vertex corresponds to one of the tasks, $s$ and $t$ are start
188 | and end of project.
189 | \begin{figure}
190 | \centering
191 | \begin{tikzpicture}
192 | [minimum width={width("b")+1.5em},
193 | vertex/.style={circle,draw=blue!50,fill=blue!20,thick},
194 | arr/.style={->,>=stealth',semithick}]
195 | \node (s) at (3,5) [vertex] {$s$};
196 | \node (t) at (15,5) [vertex] {$t$};
197 | \node (a) at (6,7) [vertex] {$a$};
198 | \node (b) at (6,5) [vertex] {$b$};
199 | \node (c) at (6,3) [vertex] {$c$};
200 | \node (d) at (9,5) [vertex] {$d$};
201 | \node (e) at (9,4) [vertex] {$e$};
202 | \node (f) at (12,7) [vertex] {$f$};
203 | \node (g) at (12,3) [vertex] {$g$};
204 | \end{tikzpicture}
205 | \end{figure}
206 | \end{onlyenv}
207 | \begin{onlyenv}<2>
208 | Arrows give a picture of the potential constraints satisfied by
209 | the tasks.
210 | \begin{figure}
211 | \centering
212 | \begin{tikzpicture}
213 | [minimum width={width("b")+1.5em},
214 | vertex/.style={circle,draw=blue!50,fill=blue!20,thick},
215 | arr/.style={->,>=stealth',semithick}]
216 | \node (s) at (3,5) [vertex] {$s$}
217 | edge[arr] (a)
218 | edge[arr] (b)
219 | edge[arr] (c);
220 | \node (t) at (15,5) [vertex] {$t$};
221 | \node (a) at (6,7) [vertex] {$a$}
222 | edge[arr] (f);
223 | \node (b) at (6,5) [vertex] {$b$}
224 | edge[arr] (d)
225 | edge[arr] (e);
226 | \node (c) at (6,3) [vertex] {$c$}
227 | edge[arr] (g);
228 | \node (d) at (9,5) [vertex] {$d$}
229 | edge[arr] (f);
230 | \node (e) at (9,4) [vertex] {$e$}
231 | edge[arr] (g);
232 | \node (f) at (12,7) [vertex] {$f$}
233 | edge[arr] (g);
234 | \node (g) at (12,3) [vertex] {$g$}
235 | edge[arr] (t);
236 | \end{tikzpicture}
237 | \end{figure}
238 | \end{onlyenv}
239 | \begin{onlyenv}<3->
240 | Valuation at arrow is the time laps between start point
241 | of origin till start point of target.
242 | \begin{figure}
243 | \centering
244 | \begin{tikzpicture}
245 | [minimum width={width("b")+1.5em},
246 | vertex/.style={circle,draw=blue!50,fill=blue!20,thick},
247 | arr/.style={->,>=stealth',semithick}]
248 | \node (s) at (3,5) [vertex] {$s$}
249 | edge[arr] node[above, red] {$0$} (a)
250 | edge[arr] node[above, red] {$0$} (b)
251 | edge[arr] node[above, red] {$0$} (c);
252 | \node (t) at (15,5) [vertex] {$t$};
253 | \node (a) at (6,7) [vertex] {$a$}
254 | edge[arr] node[above, red] {$6$}(f);
255 | \node (b) at (6,5) [vertex] {$b$}
256 | edge[arr] node[above, red] {$3$} (d)
257 | edge[arr] node[below, red] {$3$} (e);
258 | \node (c) at (6,3) [vertex] {$c$}
259 | edge[arr] node[below, red] {$6$} (g);
260 | \node (d) at (9,5) [vertex] {$d$}
261 | edge[arr] node[above, red] {$2$} (f);
262 | \node (e) at (9,4) [vertex] {$e$}
263 | edge[arr] node[above, red] {$3$} (g);
264 | \node (f) at (12,7) [vertex] {$f$}
265 | edge[arr] node[right, red] {$3$} (g);
266 | \node (g) at (12,3) [vertex] {$g$}
267 | edge[arr] node[above, red] {$1$} (t);
268 | \end{tikzpicture}
269 | \end{figure}
270 | \end{onlyenv}
271 | \end{frame}
272 |
273 | \begin{frame}
274 | \frametitle{Working Example : MPM / Earliest Dates}
275 | \begin{columns}
276 | \begin{column}{.6\textwidth}
277 |
278 | \vspace{.2\baselineskip}
279 | The point is to compute the earliest date at which the project
280 | ends.
281 |
282 | \vspace{.3\baselineskip}
283 | This is governed by paths from source to target that take
284 | the longest time. These are called \emph{critical
285 | paths}, the name comes from the fact any delay $\varepsilon$
286 | in tasks along this path would delay the whole project by
287 | $\varepsilon$.
288 |
289 | \vspace{.3\baselineskip}
290 | Our goal can be achieved by adapting Ford's algorithms to look
291 | for longest paths in our graph.
292 |
293 | \vspace{.3\baselineskip}
294 | \begin{alertblock}{Beware}
295 | For this strategy to work, it is
296 | important to have graphs without circuits! in our case that
297 | would mean there are contradicting tasks ...
298 | \end{alertblock}
299 | \end{column}
300 | \begin{column}{.4\textwidth}
301 | \begin{onlyenv}<1>
302 | \begin{figure}
303 | \begin{tikzpicture}
304 | [scale= .9, minimum width={width("b")+1.5em},
305 | vertex/.style={circle,draw=blue!50,fill=blue!20,thick},
306 | arr/.style={->,>=stealth',semithick}]
307 | \node (t) at (8,2.5) [vertex] {$t$};
308 | \node (g) at (6,4) [vertex] {$g$}
309 | edge[arr] node[below left, red] {$1$} (t)
310 | ;
311 | \node (f) at (10,4) [vertex] {$f$}
312 | edge[arr] node[above, red] {$3$} (g)
313 | ;
314 | \node (e) at (7,6) [vertex] {$e$}
315 | edge[arr] node[right, red] {$3$} (g)
316 | ;
317 | \node (d) at (8,6) [vertex] {$d$}
318 | edge[arr] node[left, red] {$2$} (f)
319 | ;
320 | \node (c) at (6,8) [vertex] {$c$}
321 | edge[arr] node[left, red] {$6$} (g)
322 | ;
323 | \node (b) at (8,8) [vertex] {$b$}
324 | edge[arr] node[right, red] {$3$} (d)
325 | edge[arr] node[left, red] {$3$} (e)
326 | ;
327 | \node (a) at (10,8) [vertex] {$a$}
328 | edge[arr] node[right, red] {$6$}(f)
329 | ;
330 | \node (s) at (8,10) [vertex] {$s$}
331 | edge[arr] node[right, red] {$0$} (a)
332 | edge[arr] node[right, red] {$0$} (b)
333 | edge[arr] node[right, red] {$0$} (c)
334 | ;
335 | \end{tikzpicture}
336 | \end{figure}
337 | \end{onlyenv}
338 | \end{column}
339 | \end{columns}
340 | \end{frame}
341 |
342 | \begin{frame}
343 | \frametitle{Working Example : MPM / Earliest Dates}
344 | \begin{columns}
345 | \begin{column}{.6\textwidth}
346 | The point is to compute the earliest date at which the project
347 | ends.
348 |
349 | \vspace{.3\baselineskip}
350 | This is governed by paths from source to target that take
351 | the longest time. These are called \emph{critical
352 | paths}, the name comes from the fact any delay $\varepsilon$
353 | in tasks along this path would delay the whole project by
354 | $\varepsilon$.
355 |
356 | \vspace{.3\baselineskip}
357 | Our goal can be achieved by adapting Ford's algorithms to look
358 | for longest paths in our graph.
359 |
360 | \vspace{.3\baselineskip}
361 | \begin{alertblock}{Beware}
362 | For this strategy to work, it is
363 | important to have graphs without circuits! in our case that
364 | would mean there are contradicting tasks ...
365 | \end{alertblock}
366 | \end{column}
367 | \begin{column}{.4\textwidth}
368 | \begin{onlyenv}<1>
369 |
370 | \vspace{.5\baselineskip}
371 | \begin{tikzpicture}
372 | [scale= .9, minimum width={width("b")+1.5em},
373 | vertex/.style={circle,draw=blue!50,fill=blue!20,thick},
374 | arr/.style={->,>=stealth',semithick}]
375 | \node (t) at (8,2.5) [vertex, label=0:$10$] {$t$};
376 | \node (g) at (6,4) [vertex, label=180:$9$] {$g$}
377 | edge[arr] node[below left, red] {$1$} (t)
378 | ;
379 | \node (f) at (10,4) [vertex, label=0:$6$] {$f$}
380 | edge[arr] node[above, red] {$3$} (g)
381 | ;
382 | \node (e) at (7,6) [vertex, label=180:$3$] {$e$}
383 | edge[arr] node[right, red] {$3$} (g)
384 | ;
385 | \node (d) at (8,6) [vertex, label=0:$3$] {$d$}
386 | edge[arr] node[left, red] {$2$} (f)
387 | ;
388 | \node (c) at (6,8) [vertex, label=0:$0$] {$c$}
389 | edge[arr] node[left, red] {$6$} (g)
390 | ;
391 | \node (b) at (8,8) [vertex, label=0:$0$] {$b$}
392 | edge[arr] node[right, red] {$3$} (d)
393 | edge[arr] node[left, red] {$3$} (e)
394 | ;
395 | \node (a) at (10,8) [vertex, label=0:$0$] {$a$}
396 | edge[arr] node[right, red] {$6$}(f)
397 | ;
398 | \node (s) at (8,10) [vertex, label=0:$0$] {$s$}
399 | edge[arr] node[right, red] {$0$} (a)
400 | edge[arr] node[right, red] {$0$} (b)
401 | edge[arr] node[right, red] {$0$} (c)
402 | ;
403 | \end{tikzpicture}
404 | \end{onlyenv}
405 | \end{column}
406 | \end{columns}
407 | \end{frame}
408 |
409 | \begin{frame}
410 | \frametitle{Working Example : MPM / Earliest Dates}
411 | \begin{columns}
412 | \begin{column}{.6\textwidth}
413 | The earliest date at which to expect our project is accomplished
414 | is $10$ time units from our starting date.
415 |
416 | \vspace{.3\baselineskip}
417 | More generally, we have computed the earliest date at which to
418 | expect any task to start. The start $t$ which correspond to the
419 | end of the project starts at $10$.
420 |
421 | \vspace{.3\baselineskip}
422 | All \emph{critical paths} from source to target are the
423 | (elementary) ones contained in the subgraph in green. There is
424 | only one here.
425 | \end{column}
426 | \begin{column}{.4\textwidth}
427 | \begin{onlyenv}<1>
428 |
429 | \vspace{.5\baselineskip}
430 | \begin{tikzpicture}
431 | [scale= .9, minimum width={width("b")+1.5em},
432 | vertex/.style={circle,draw=blue!50,fill=blue!20,thick},
433 | vertexg/.style={circle,draw=green!50!black,fill=green!10,thick},
434 | arr/.style={->,>=stealth',semithick}]
435 | \node (t) at (8,2.5) [vertexg, label=0:$10$] {$t$};
436 | \node (g) at (6,4) [vertexg, label=180:$9$] {$g$}
437 | edge[arr, green!50!black, very thick] node[below left, red] {$1$} (t)
438 | ;
439 | \node (f) at (10,4) [vertexg, label=0:$6$] {$f$}
440 | edge[arr, green!50!black, very thick] node[above, red] {$3$} (g)
441 | ;
442 | \node (e) at (7,6) [vertex, label=180:$3$] {$e$}
443 | edge[arr] node[right, red] {$3$} (g)
444 | ;
445 | \node (d) at (8,6) [vertex, label=0:$3$] {$d$}
446 | edge[arr] node[left, red] {$2$} (f)
447 | ;
448 | \node (c) at (6,8) [vertex, label=0:$0$] {$c$}
449 | edge[arr] node[left, red] {$6$} (g)
450 | ;
451 | \node (b) at (8,8) [vertex, label=0:$0$] {$b$}
452 | edge[arr] node[right, red] {$3$} (d)
453 | edge[arr] node[left, red] {$3$} (e)
454 | ;
455 | \node (a) at (10,8) [vertexg, label=0:$0$] {$a$}
456 | edge[arr, green!50!black, very thick] node[right, red] {$6$}(f)
457 | ;
458 | \node (s) at (8,10) [vertexg, label=0:$0$] {$s$}
459 | edge[arr, green!50!black, very thick] node[right, red] {$0$} (a)
460 | edge[arr] node[right, red] {$0$} (b)
461 | edge[arr] node[right, red] {$0$} (c)
462 | ;
463 | \end{tikzpicture}
464 | \end{onlyenv}
465 | \end{column}
466 | \end{columns}
467 | \end{frame}
468 |
469 | \begin{frame}
470 | \frametitle{Working Example : MPM / Latest Dates}
471 | \begin{columns}
472 | \begin{column}{.6\textwidth}
473 | Knowing that the project, at the earliest, ends $10$ time units
474 | after it starts, we can compute the latest dates at which
475 | non-critical tasks can start.
476 |
477 | \vspace{.3\baselineskip}
478 | To do so, one looks for lengths of \emph{shortest} paths
479 | starting at $t$ with valuation $10$.
480 |
481 | \begin{uncoverenv}<0>
482 | \vspace{.3\baselineskip}
483 | We get the graph on the right. Each vertex is valued by the
484 | latest date at which it can start, keeping the project ending
485 | time at $10$.
486 |
487 | \vspace{.3\baselineskip}
488 | Notice that valuation of the critical path do not change.
489 | \end{uncoverenv}
490 | \end{column}
491 | \begin{column}{.4\textwidth}
492 | \begin{onlyenv}<1>
493 |
494 | \vspace{.5\baselineskip}
495 | \begin{tikzpicture}
496 | [scale= .9, minimum width={width("b")+1.5em},
497 | vertex/.style={circle,draw=blue!50,fill=blue!20,thick},
498 | vertexg/.style={circle,draw=green!50!black,fill=green!10,thick},
499 | arr/.style={->,>=stealth',semithick}]
500 | \node (t) at (8,2.5) [vertexg, label=0:$10$] {$t$};
501 | \node (g) at (6,4) [vertexg, label=180:$$] {$g$}
502 | edge[arr, green!50!black, very thick] node[below left, red] {$1$} (t)
503 | ;
504 | \node (f) at (10,4) [vertexg, label=0:$$] {$f$}
505 | edge[arr, green!50!black, very thick] node[above, red] {$3$} (g)
506 | ;
507 | \node (e) at (7,6) [vertex, label=180:$$] {$e$}
508 | edge[arr] node[right, red] {$3$} (g)
509 | ;
510 | \node (d) at (8,6) [vertex, label=0:$$] {$d$}
511 | edge[arr] node[left, red] {$2$} (f)
512 | ;
513 | \node (c) at (6,8) [vertex, label=0:$$] {$c$}
514 | edge[arr] node[left, red] {$6$} (g)
515 | ;
516 | \node (b) at (8,8) [vertex, label=0:$$] {$b$}
517 | edge[arr] node[right, red] {$3$} (d)
518 | edge[arr] node[left, red] {$3$} (e)
519 | ;
520 | \node (a) at (10,8) [vertexg, label=0:$$] {$a$}
521 | edge[arr, green!50!black, very thick] node[right, red] {$6$}(f)
522 | ;
523 | \node (s) at (8,10) [vertexg, label=0:$$] {$s$}
524 | edge[arr, green!50!black, very thick] node[right, red] {$0$} (a)
525 | edge[arr] node[right, red] {$0$} (b)
526 | edge[arr] node[right, red] {$0$} (c)
527 | ;
528 | \end{tikzpicture}
529 | \end{onlyenv}
530 | \end{column}
531 | \end{columns}
532 | \end{frame}
533 |
534 | \begin{frame}
535 | \frametitle{Working Example : MPM / Latest Dates}
536 | \begin{columns}
537 | \begin{column}{.6\textwidth}
538 | Knowing that the project, at the earliest, ends $10$ time units
539 | after it starts, we can compute the latest dates at which
540 | non-critical tasks can start.
541 |
542 | \vspace{.3\baselineskip}
543 | To do so, one looks for lengths of \emph{shortest} paths
544 | starting at $t$ with valuation $10$.
545 |
546 | \vspace{.3\baselineskip}
547 | We get the graph on the right. Each vertex is valued by the
548 | latest date at which it can start, keeping the project ending
549 | time at $10$.
550 |
551 | \vspace{.3\baselineskip}
552 | Notice that valuation of the critical path do not change.
553 | \end{column}
554 | \begin{column}{.4\textwidth}
555 | \begin{onlyenv}<1>
556 |
557 | \vspace{.5\baselineskip}
558 | \begin{tikzpicture}
559 | [scale= .9, minimum width={width("b")+1.5em},
560 | vertex/.style={circle,draw=blue!50,fill=blue!20,thick},
561 | vertexg/.style={circle,draw=green!50!black,fill=green!10,thick},
562 | arr/.style={->,>=stealth',semithick}]
563 | \node (t) at (8,2.5) [vertexg, label=0:$10$] {$t$};
564 | \node (g) at (6,4) [vertexg, label=180:$9$] {$g$}
565 | edge[arr, green!50!black, very thick] node[below left, red] {$1$} (t)
566 | ;
567 | \node (f) at (10,4) [vertexg, label=0:$6$] {$f$}
568 | edge[arr, green!50!black, very thick] node[above, red] {$3$} (g)
569 | ;
570 | \node (e) at (7,6) [vertex, label=180:$6$] {$e$}
571 | edge[arr] node[right, red] {$3$} (g)
572 | ;
573 | \node (d) at (8,6) [vertex, label=0:$4$] {$d$}
574 | edge[arr] node[left, red] {$2$} (f)
575 | ;
576 | \node (c) at (6,8) [vertex, label=0:$3$] {$c$}
577 | edge[arr] node[left, red] {$6$} (g)
578 | ;
579 | \node (b) at (8,8) [vertex, label=0:$1$] {$b$}
580 | edge[arr] node[right, red] {$3$} (d)
581 | edge[arr] node[left, red] {$3$} (e)
582 | ;
583 | \node (a) at (10,8) [vertexg, label=0:$0$] {$a$}
584 | edge[arr, green!50!black, very thick] node[right, red] {$6$}(f)
585 | ;
586 | \node (s) at (8,10) [vertexg, label=0:$0$] {$s$}
587 | edge[arr, green!50!black, very thick] node[right, red] {$0$} (a)
588 | edge[arr] node[right, red] {$0$} (b)
589 | edge[arr] node[right, red] {$0$} (c)
590 | ;
591 | \end{tikzpicture}
592 | \end{onlyenv}
593 | \end{column}
594 | \end{columns}
595 | \end{frame}
596 |
597 | \begin{frame}
598 | \frametitle{Working Example : MPM / Margins}
599 | \begin{columns}
600 | \begin{column}{.6\textwidth}
601 |
602 | The margin at a vertex is simply the difference between the
603 | latest date to start and the earliest one.
604 |
605 | \vspace{.3\baselineskip}
606 | Notice that along the critical path, margins are $0$.
607 | \end{column}
608 | \begin{column}{.4\textwidth}
609 | \begin{onlyenv}<1>
610 |
611 | \vspace{.5\baselineskip}
612 | \begin{tikzpicture}
613 | [scale= .9, minimum width={width("b")+1.5em},
614 | vertex/.style={circle,draw=blue!50,fill=blue!20,thick},
615 | vertexg/.style={circle,draw=green!50!black,fill=green!10,thick},
616 | arr/.style={->,>=stealth',semithick}]
617 | \node (t) at (8,2.5) [vertexg, label=0:$0$] {$t$};
618 | \node (g) at (6,4) [vertexg, label=180:$0$] {$g$}
619 | edge[arr, green!50!black, very thick] node[below left, red] {$1$} (t)
620 | ;
621 | \node (f) at (10,4) [vertexg, label=0:$0$] {$f$}
622 | edge[arr, green!50!black, very thick] node[above, red] {$3$} (g)
623 | ;
624 | \node (e) at (7,6) [vertex, label=180:$3$] {$e$}
625 | edge[arr] node[right, red] {$3$} (g)
626 | ;
627 | \node (d) at (8,6) [vertex, label=0:$1$] {$d$}
628 | edge[arr] node[left, red] {$2$} (f)
629 | ;
630 | \node (c) at (6,8) [vertex, label=0:$3$] {$c$}
631 | edge[arr] node[left, red] {$6$} (g)
632 | ;
633 | \node (b) at (8,8) [vertex, label=0:$1$] {$b$}
634 | edge[arr] node[right, red] {$3$} (d)
635 | edge[arr] node[left, red] {$3$} (e)
636 | ;
637 | \node (a) at (10,8) [vertexg, label=0:$0$] {$a$}
638 | edge[arr, green!50!black, very thick] node[right, red] {$6$}(f)
639 | ;
640 | \node (s) at (8,10) [vertexg, label=0:$0$] {$s$}
641 | edge[arr, green!50!black, very thick] node[right, red] {$0$} (a)
642 | edge[arr] node[right, red] {$0$} (b)
643 | edge[arr] node[right, red] {$0$} (c)
644 | ;
645 | \end{tikzpicture}
646 | \end{onlyenv}
647 | \end{column}
648 | \end{columns}
649 | \end{frame}
650 |
651 | \begin{frame}
652 | \frametitle{Working Example : The PERT approach}
653 | Recall that in the PERT approach, tasks give rise to arrows valued
654 | by the time a task needs to be accomplished. Vertices correspond to
655 | intermediate objectives ; defining them comes, at first, from the
656 | concrete situation at hand.
657 |
658 | \vspace{.3\baselineskip}
659 | In our case, starting from a vertex $5$ corresponding to project
660 | end, we can define vertex $4$ as $f$, $c$, $e$ are accomplished etc
661 | ... This is arguably a ``mathematician'' example.
662 | \begin{figure}
663 | \centering
664 | \begin{tikzpicture}
665 | [scale=.85, minimum width={width("b")+1.5em},
666 | vertex/.style={circle,draw=blue!50,fill=blue!20,thick},
667 | arr/.style={->,>=stealth',semithick}]
668 | \node (5) at (13,5) [vertex] {$5$};
669 | \node (4) at (9,5) [vertex] {$4$}
670 | edge[arr] node[above, red] {$g\,\, [1]$} (5);
671 | \node (3) at (6,3) [vertex] {$3$}
672 | edge[arr] node[below, red] {$e\,\, [4]$} (4);
673 | \node (2) at (6,7) [vertex] {$2$}
674 | edge[arr] node[above, red] {$f\,\, [3]$}(4);
675 | \node (1) at (3,5) [vertex] {$1$}
676 | edge[arr] node[above, red] {$a\,\, [6]$} (2)
677 | edge[arr] node[above, red] {$c\,\, [6]$} (4)
678 | edge[arr] node[above, red] {$b\,\, [3]$} (3);
679 | \end{tikzpicture}
680 | \end{figure}
681 | \end{frame}{}
682 |
683 | \begin{frame}
684 | \centering
685 | {\Large \textbf{This is it for the course on Graphs, Networks and Flows.\\
686 | Good luck with your final exams!}}
687 | \end{frame}
688 |
689 |
690 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
691 |
692 | \end{document}
693 |
694 | %%% Local Variables:
695 | %%% mode: latex
696 | %%% TeX-master: t
697 | %%% End:
698 |
--------------------------------------------------------------------------------
/Slides/Tex/shortestPath.tex:
--------------------------------------------------------------------------------
1 | \documentclass[32pt,aspectratio=169]{beamer}
2 |
3 | \usepackage[utf8]{inputenc} % Character encoding, choose your machine's default
4 | % encoding; latin1 or utf8. If you want it read by
5 | % others choose latin1.
6 | \pdfinfo{
7 | /Author (Bashar Dudin)
8 | /Title (Transportation problems)
9 | /Subject (Networks and Flows on Graphs)
10 | }
11 |
12 | \usepackage{./Style/My_Beamer} % This is my Beamer style.
13 | \usepackage{./Style/Mystyle} % This is my own defined commands
14 |
15 | %----------------------------------------------------------------------------------------
16 | % TITLE PAGE
17 | %----------------------------------------------------------------------------------------
18 |
19 | \author[BD]{Bashar Dudin}
20 |
21 | \institute[]{EPITA}
22 |
23 | \title{Networks and Flows on Graphs} %
24 | \subtitle{Shortest Path Problems}
25 |
26 | \begin{document}
27 |
28 | \begin{frame}[plain]
29 | \titlepage % Print the title page as the first slide
30 | \end{frame}
31 |
32 | \begin{frame}{What is it about?}
33 | \begin{halfshyblock}{Shortest path problem}
34 | Given a weighted directed graph a shortest path problem is about
35 | looking at paths having minimal lengths (weighted lenghts)
36 | \begin{itemize}
37 | \item[\textcolor<2->{lightgray}{\textbullet}] \textcolor<2->{lightgray}{between two given vertices (single-pair shortest path problem)}
38 | \item from a given source to any other vertex in the graph (single-source shortest path problem)
39 | \item between all pairs of vertices (all-pairs shortest path problem)
40 | \end{itemize}
41 | \end{halfshyblock}
42 | \pause[3]In order to be able to answer any of these problems the digraphs
43 | we're working with need not have any negative valued
44 | circuits (in case of single source, ones accessible from the source).
45 | \pause[4]
46 | \begin{rem}
47 | One could look for longest paths in a digraph. For graphs having no
48 | positive-valued circuits one can adapt the algorithms solving
49 | shortest path problems tweaking them a little.
50 | \end{rem}
51 | \end{frame}
52 |
53 | \begin{frame}[t]{Single-source shortest path problem : Ford's Algorithm}
54 | \small{
55 | \begin{algorithmic}[1]
56 | \Require $G$ a digraph having source $s$, $n$
57 | vertices and no negative-valued circuits accessible from $s$
58 | \Statex write $\nu$ the weight map from the set of arrows to integers
59 | \Ensure minimal lengths of paths from $s$
60 | \State number vertices arbitrarily $v_0$, $\ldots$, $v_{n-1}$ ensuring $s$ is the first
61 | \State initialize the vertex $v_0$ with $\lambda_0 =0$ and all others with $\lambda_i = +\infty$
62 |
63 | \Statex
64 | \For{$\_$ from $0$ to $n-1$}
65 | \ForAll{arrows $(v_\ell, v_j)$}
66 | \If{$\lambda_j > \lambda_\ell + \nu(v_\ell, v_j)$}
67 | \State $\lambda_j \gets \lambda_\ell + \nu(v_\ell, v_j)$
68 | \EndIf
69 | \EndFor
70 | \EndFor
71 |
72 | \State{\Return the list of $\lambda_i$s with the corresponding vertices}
73 | \end{algorithmic}
74 | }
75 | \tikzoverlay[text width=5.5cm] at (8.5cm, 4.8cm) {
76 | \begin{tcolorbox}[
77 | enhanced,
78 | parbox = false,
79 | colback=mLightBrown!10!white,
80 | colframe=mLightBrown,
81 | arc=0mm,
82 | ]
83 | \small{By adding an extra check to this algorithm one can also
84 | detect possible negative-valued circuits, without having to
85 | check it beforehand}
86 | \end{tcolorbox}%
87 | };
88 | \end{frame}
89 |
90 | \begin{frame}[t]{Ford's Algorithm : building a tree of shortest paths}
91 | \small{
92 | \begin{algorithmic}[1]
93 | \Require $G$ a digraph having source $s$, $n$ vertices and
94 | no negative-valued circuits accessible from $s$
95 | \Statex write $\nu$ the weight map from the set of arrows to integers
96 | \Ensure minimal lengths of paths from $s$ \alert{together with a tree $T$ of shortest paths}
97 |
98 | \State number vertices arbitrarily $v_0$, $\ldots$, $v_{n-1}$ ensuring $s$ is the first
99 | \State initialize the vertex $v_0$ with $\lambda_0 =0$ and all others with $\lambda_i = +\infty$
100 | \Statex \alert{$T$ is a tree having a single vertex $s$}
101 | \For{$\_$ from $0$ to $n-1$}
102 | \ForAll{arrows $(v_\ell, v_j)$}
103 | \If{$\lambda_j > \lambda_\ell + \nu(v_\ell, v_j)$}
104 | \State $\lambda_j \gets \lambda_\ell + \nu(v_\ell, v_j)$
105 | \State \alert{$T[j] \gets \ell$}
106 | \EndIf
107 | \EndFor
108 | \EndFor
109 |
110 | \State{\Return the list of $\lambda_i$s with the corresponding vertices \alert{and $T$}}
111 | \end{algorithmic}
112 | }
113 | \tikzoverlay[text width=5.5cm] at (8.5cm, 5.35cm) {
114 | \begin{tcolorbox}[
115 | enhanced,
116 | parbox = false,
117 | colback=mLightBrown!10!white,
118 | colframe=mLightBrown,
119 | arc=0mm,
120 | ]
121 | \small{The tree $T$ is built up by attaching to each vertex $k$ its
122 | predecessor $T[k]$, if there is any. To get a shortest path
123 | between $s$ and a vertex $v$ follow the unique path in $T$
124 | linking both.}
125 | \end{tcolorbox}%
126 | };
127 | \end{frame}
128 |
129 | \begin{frame}{Validity and complexity of Ford's algorithm}
130 | Let $V$ be the set of vertices of $G$ and $A$ its set of arrows.
131 | Line $2$ of Ford's algorithm takes $|V|$ operations. One goes $|V|$
132 | times through the loop at line $3$, for each iteration, one goes
133 | $|A|$ times through loop at line $4$. In total, we get a complexity
134 | for Ford's algorithm of
135 | $O\big(|V| + |V||A|\big) = O\big( |V||A|\big)$
136 | \begin{halfshyblock}{Validity}
137 | An elementary shortest path from $s$ to a vertex $v$ has length at
138 | most $|V|-1$. Given such an elementary path $a_0, \ldots, a_m$
139 | with $a_0=s$ and $a_m=v$ each sub-path from $s$ to any
140 | intermediate vertex is also a shortest path (otherwise we can make
141 | a shorter one from $s$ to $v$). Following Ford's algorithm along
142 | the previous path, one can show, by induction that $\lambda_m$ can
143 | only be equal to the (weighted) length of $a_0, \ldots, a_m$,
144 | i.e. the shortest path from $s$ to $v$.
145 | \end{halfshyblock}
146 | \end{frame}
147 |
148 |
149 | \begin{frame}{Single-source shortest path problem : Djikstra's algorithm}
150 | \small{
151 | \begin{algorithmic}[1]
152 | \Require $G$ a digraph having source $s$, $n$
153 | vertices and positive weight function $\nu$
154 | \Ensure minimal lengths of paths from $s$ to each vertex of $G$
155 |
156 | \State $V$ is the set of vertices of $G$ except for $s$
157 | \State initialize $s$ with $\lambda_s =0$, each of its
158 | successors $v$ with $\lambda_v = \nu(s, v)$
159 | \Statex and all other $v$ with $\lambda_v = +\infty$
160 |
161 | \While{$V \neq \emptyset$}
162 | \State find $v$ such that $\lambda_v$ is minimal among elements in $V$
163 | \ForAll{arrows $(v, v_j)$}
164 | \If{$\lambda_j > \lambda_v + \nu(v, v_j)$}
165 | \State $\lambda_j \gets \lambda_v + \nu(v, v_j)$
166 | \EndIf
167 | \EndFor
168 | \State $V \gets V\setminus \{v\}$
169 | \EndWhile
170 |
171 | \State{\Return the list of $\lambda$s with the corresponding vertices}
172 | \end{algorithmic}
173 | }
174 | \tikzoverlay[text width=5cm] at (9cm, 5.5cm) {
175 | \begin{tcolorbox}[
176 | enhanced,
177 | parbox = false,
178 | colback=mLightBrown!10!white,
179 | colframe=mLightBrown,
180 | arc=0mm,
181 | ]
182 | Building a tree of shortest paths can be adapted from what was
183 | done previously in the case of Ford's algorithm.
184 | \end{tcolorbox}%
185 | };
186 | \end{frame}
187 |
188 | \begin{frame}{Validity and Complexity of Djikstra's algorithm}
189 | A quick analysis of Djikstra's algorithm, as given here, shows it
190 | has complexity $O\big(|V|^2\big)$, where $V$ is the set of vertices
191 | of $G$. Indeed, the first loop is taken $|V|$ times, computing the
192 | minimum $\lambda_v$ and going through all your adjacent vertices
193 | during each loop, gives a final complexity of
194 | $O\Big(|V|\big(|V|+|A|\big)\Big)$ where $A$ is the set of arrows of
195 | $G$.
196 | \begin{rem}
197 | Implementation of Djikstra's algorithm can drop complexity to
198 | $O\big(|V|\lg|V| + |A|\big)$. How can you do that?
199 | \end{rem}
200 | \begin{halfshyblock}{Validity}
201 | Since all arrows are positively weighted, the minimal potential
202 | length $\lambda_v$ chosen at each step of line $4$ in Djikstra's
203 | algorithm would not have changed if we had run Ford's algorithm.
204 | \end{halfshyblock}
205 | \end{frame}
206 |
207 | \begin{frame}{All-pairs shortest path problem : Floyd-Warshall algorithm}
208 | We are looking for shortest paths between any two pairs of vertices
209 | in a given digraph $G$ with weighted arrows. \alert{Such paths exist
210 | as long as cycles are not negatively valued}.
211 |
212 | \vspace{.5\baselineskip}
213 |
214 | Number the vertices of $G$ from $1$ to $n$. Let $w_{ij}^k$
215 | be the minimal weight a path from $i$ to $j$ has, assuming
216 | intermediate vertices are in $\{1, \ldots, k\}$. If there is no such
217 | path $w_{ij} = +\infty$. If $P$ is a path joining $i$ to $j$ and having
218 | intermediate vertices in $\{1, \ldots, k \}$ then
219 | \begin{itemize}
220 | \item either $P$ does not go through $k$
221 | \item or $P$ goes only once through $k$ (only positive valued cycles);
222 | it is the concatenation of a path from $i$ to $k$ and one from $k$
223 | to $j$, only supported along $\{ 1, \ldots, k-1\}$.
224 | \end{itemize}
225 | This means that
226 | \begin{displaymath}
227 | w_{ij}^k = \min\Big( w_{ij}^{k-1}, w_{ik}^{k-1} + w_{kj}^{k-1} \Big)
228 | \end{displaymath}
229 | \end{frame}
230 |
231 | \begin{frame}{All-pairs shortest path problem : Floyd-Warshall algorithm}
232 | \small{
233 | \begin{algorithmic}[1]
234 | \Statex
235 | \Require $W$ the (generalized) adjacency matrix of a digraph $G$ having weighted arrows and only positve weighted cycles
236 | \Ensure minimal (weighted) lengths of paths between any two vertices of $G$
237 | \Statex
238 | \For{$k \in \{1, \ldots, n\}$}
239 | \For{$i \in \{1, \ldots, n\}$}
240 | \For{$j \in \{1, \ldots, n\}$}
241 | \State $W[i,j] \gets \min\Big(W[i,j], W[i,k] + W[k,j]\Big)$
242 | \EndFor
243 | \EndFor
244 | \EndFor
245 | \State \Return $W$
246 | \end{algorithmic}
247 | }
248 | \end{frame}
249 |
250 | \begin{frame}{Building up shortest paths using output of Floyd-Warshall algorithm}
251 | The output is a matrix $\Pi$ where entry at position $(i, j)$ gets a
252 | predecessor of $j$ along a shortest path from $i$ to $j$. To get a
253 | full shortest path from $i$ to $j$ read the matrix smartly.
254 |
255 | \vspace{.3\baselineskip}
256 | \small{
257 | \begin{algorithmic}[1]
258 | \Require Matrix $W$ of minimal lengths between any two pairs of vertices of $G$
259 | \Ensure A matrix $\Pi$ giving at entry $(i, j)$ a predecessor of
260 | $j$ along a shortest path from $i$ to $j$
261 | \For{$j \in \{1, \ldots, n\}$}
262 | \For{$i \in \{1, \ldots, n\}$}
263 | \ForAll{arrows $(v,j)$}
264 | \If{$W[i,j] \neq +\infty$ and $W[i,j] = W[i,v] + W[v,j]$}
265 | \State{$\Pi[i,j] \gets v$}
266 | \EndIf
267 | \EndFor
268 | \EndFor
269 | \EndFor
270 | \State{\Return{$\Pi$}}
271 | \end{algorithmic}
272 | }
273 | \end{frame}
274 |
275 | \begin{frame}
276 | \centering
277 | \Large \textbf{This is all we'll learn on this topic!}
278 | \end{frame}
279 |
280 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
281 |
282 | \end{document}
283 |
284 | %%% Local Variables:
285 | %%% mode: latex
286 | %%% TeX-master: t
287 | %%% End:
288 |
--------------------------------------------------------------------------------
/Slides/fixingGraphTheoreticalTerminology.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bashardudin/GraphsAndFlows/afdf1d1c60d54abec7484fbaa1b473b9d3d0894b/Slides/fixingGraphTheoreticalTerminology.pdf
--------------------------------------------------------------------------------
/Slides/maximumFlow.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bashardudin/GraphsAndFlows/afdf1d1c60d54abec7484fbaa1b473b9d3d0894b/Slides/maximumFlow.pdf
--------------------------------------------------------------------------------
/Slides/projectPlanning.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bashardudin/GraphsAndFlows/afdf1d1c60d54abec7484fbaa1b473b9d3d0894b/Slides/projectPlanning.pdf
--------------------------------------------------------------------------------
/Slides/shortestPath.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bashardudin/GraphsAndFlows/afdf1d1c60d54abec7484fbaa1b473b9d3d0894b/Slides/shortestPath.pdf
--------------------------------------------------------------------------------
/Slides/transportationProblems.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bashardudin/GraphsAndFlows/afdf1d1c60d54abec7484fbaa1b473b9d3d0894b/Slides/transportationProblems.pdf
--------------------------------------------------------------------------------