DGraph.cpp 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. /*=========================================================================
  2. Library: CTK
  3. Copyright (c) 2010 Kitware Inc.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.commontk.org/LICENSE
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. =========================================================================*/
  14. // Qt includes
  15. #include <QFile>
  16. #include <QTextStream>
  17. #include <QRegExp>
  18. #include <QStringList>
  19. #include <QDebug>
  20. // CTK includes
  21. #include <ctkDependencyGraph.h>
  22. // STD includes
  23. #include <cstdlib>
  24. #include <iostream>
  25. //----------------------------------------------------------------------------
  26. QString help(const QString& progName)
  27. {
  28. QString msg = "Usage: %1 <graphfile> [-paths Label]";
  29. return msg.arg(progName);
  30. }
  31. //----------------------------------------------------------------------------
  32. void displayError(const QString& progName, const QString& msg)
  33. {
  34. std::cerr << QString("%1\n%2\n%3\n").arg(progName).
  35. arg(msg).
  36. arg(help(progName)).toStdString();
  37. }
  38. //----------------------------------------------------------------------------
  39. int getOrGenerateId(QHash<int, QString>& vertexIdToLabel,
  40. QHash<QString, int>& vertexLabelToId,
  41. const QString& label)
  42. {
  43. // If needed, generate vertex id
  44. int vertexId = -1;
  45. if (!vertexLabelToId.keys().contains(label))
  46. {
  47. vertexId = vertexLabelToId.keys().size() + 1;
  48. vertexLabelToId[label] = vertexId;
  49. vertexIdToLabel[vertexId] = label;
  50. }
  51. else
  52. {
  53. vertexId = vertexLabelToId[label];
  54. }
  55. return vertexId;
  56. }
  57. //----------------------------------------------------------------------------
  58. int main(int argc, char** argv)
  59. {
  60. bool verbose = false;
  61. bool outputTopologicalOrder = true;
  62. // a graph file is expected
  63. if (argc < 2)
  64. {
  65. displayError(argv[0], QLatin1String("Missing one argument"));
  66. return EXIT_FAILURE;
  67. }
  68. bool outputPath = false;
  69. QString label;
  70. if (argc == 3)
  71. {
  72. displayError(argv[0], QLatin1String("Wrong argument"));
  73. return EXIT_FAILURE;
  74. }
  75. if (argc == 4)
  76. {
  77. if (QString(argv[2]).compare("-paths")!=0)
  78. {
  79. displayError(argv[0], QString("Wrong argument: %1").arg(argv[2]));
  80. return EXIT_FAILURE;
  81. }
  82. label = QLatin1String(argv[3]);
  83. outputTopologicalOrder = false;
  84. outputPath = true;
  85. if (verbose)
  86. {
  87. qDebug() << "label:" << label;
  88. }
  89. }
  90. QString filepath = QString::fromLatin1(argv[1]);
  91. if (!QFile::exists(filepath))
  92. {
  93. displayError(argv[0], QString("File '%1' doesn't exists !").arg(filepath));
  94. return EXIT_FAILURE;
  95. }
  96. QFile data(filepath);
  97. if (!data.open(QFile::ReadOnly))
  98. {
  99. displayError(argv[0], QString("Failed to open file '%1' !").arg(filepath));
  100. return EXIT_FAILURE;
  101. }
  102. QTextStream in(&data);
  103. QString header = in.readLine();
  104. if (header.isNull())
  105. {
  106. displayError(argv[0], QString("Failed to read Header line in file '%1' !").arg(filepath));
  107. return EXIT_FAILURE;
  108. }
  109. // Regular expression to extract two integers
  110. QRegExp twoint_re("^([0-9]+)\\s+([0-9]+)");
  111. // Extract numberOfVertices and numberOfEdges
  112. int pos = twoint_re.indexIn(header.trimmed());
  113. if (pos != 0)
  114. {
  115. displayError(argv[0], QString("Error in file '%1' - First line should look like: <#Vertices> <#Edges>")
  116. .arg(filepath));
  117. return EXIT_FAILURE;
  118. }
  119. QStringList list = twoint_re.capturedTexts();
  120. Q_ASSERT(list.size() == 3);
  121. int numberOfVertices = list[1].toInt();
  122. int numberOfEdges = list[2].toInt();
  123. if (verbose)
  124. {
  125. qDebug() << "#Vertices:" << numberOfVertices << "#Edges:" << numberOfEdges;
  126. }
  127. // Init
  128. ctkDependencyGraph mygraph(numberOfVertices);
  129. mygraph.setVerbose(verbose);
  130. // Map between vertex label and vertex id
  131. QHash<int, QString> vertexIdToLabel;
  132. QHash<QString, int> vertexLabelToId;
  133. // Regular expression to extract two label
  134. QRegExp twolabel_re("^(.+)\\s+(.+)");
  135. // Read vertex connection
  136. int lineNumber = 2;
  137. QString line = in.readLine();
  138. do
  139. {
  140. // Skip empty line or commented line
  141. if (line.isEmpty() || line.startsWith("#"))
  142. {
  143. continue;
  144. }
  145. // Extract vertex points
  146. int pos = twolabel_re.indexIn(line.trimmed());
  147. if (pos != 0)
  148. {
  149. displayError(argv[0], QString("Error in file '%1' - line:%2 - Expected format is: <label> <label>")
  150. .arg(filepath).arg(lineNumber));
  151. return EXIT_FAILURE;
  152. }
  153. lineNumber++;
  154. QStringList list = twolabel_re.capturedTexts();
  155. Q_ASSERT(list.size() == 3);
  156. int from = getOrGenerateId(vertexIdToLabel, vertexLabelToId, list[1]);
  157. int to = getOrGenerateId(vertexIdToLabel, vertexLabelToId, list[2]);
  158. // Insert edge
  159. mygraph.insertEdge(from, to);
  160. line = in.readLine();
  161. }
  162. while (!line.isNull());
  163. Q_ASSERT(numberOfEdges == mygraph.numberOfEdges());
  164. if (verbose)
  165. {
  166. mygraph.printGraph();
  167. qDebug() << "> Check for cycle ...";
  168. }
  169. mygraph.checkForCycle();
  170. if (mygraph.cycleDetected())
  171. {
  172. std::cerr << "Cycle detected !" << std::endl;
  173. QList<int> path;
  174. mygraph.findPath(mygraph.cycleOrigin(), mygraph.cycleEnd(), path);
  175. for(int i = 0; i < path.size(); ++i)
  176. {
  177. std::cerr << vertexIdToLabel[path[i]].toStdString();
  178. if (i != path.size() - 1)
  179. {
  180. std::cerr << " -> ";
  181. }
  182. }
  183. std::cerr << std::endl;
  184. path.clear();
  185. mygraph.findPath(mygraph.cycleEnd(), mygraph.cycleOrigin(), path);
  186. for(int i = 0; i < path.size(); ++i)
  187. {
  188. std::cerr << vertexIdToLabel[path[i]].toStdString();
  189. if (i != path.size() - 1)
  190. {
  191. std::cerr << " -> ";
  192. }
  193. }
  194. std::cerr << std::endl;
  195. return EXIT_FAILURE;
  196. }
  197. if (outputTopologicalOrder)
  198. {
  199. if (verbose)
  200. {
  201. qDebug() << "> Topological order ...";
  202. }
  203. QList<int> out;
  204. if (mygraph.topologicalSort(out))
  205. {
  206. for(int i=out.size() - 1; i >= 0; --i)
  207. {
  208. std::cout << vertexIdToLabel[out[i]].toStdString();
  209. if (i != 0)
  210. {
  211. std::cout << " ";
  212. }
  213. }
  214. std::cout << std::endl;
  215. }
  216. }
  217. if (outputPath)
  218. {
  219. // TODO Make sure label is valid
  220. QList<int> out;
  221. if (mygraph.topologicalSort(out))
  222. {
  223. // Assume all targets depend on the first lib
  224. int rootId = out.last();
  225. int labelId = vertexLabelToId[label];
  226. QList<QList<int>*> paths;
  227. mygraph.findPaths(labelId, rootId, paths);
  228. for(int i=0; i < paths.size(); i++)
  229. {
  230. QList<int>* p = paths[i];
  231. Q_ASSERT(p);
  232. for(int j=0; j < p->size(); j++)
  233. {
  234. int id = p->at(j);
  235. std::cout << vertexIdToLabel[id].toStdString();
  236. if (j != p->size() - 1)
  237. {
  238. std::cout << " ";
  239. }
  240. }
  241. if (i != paths.size() - 1)
  242. {
  243. std::cout << ";";
  244. }
  245. }
  246. }
  247. }
  248. return EXIT_SUCCESS;
  249. }