Guest User

Untitled

a guest
Nov 14th, 2017
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.70 KB | None | 0 0
  1. /*
  2.  
  3. The MIT License (MIT)
  4.  
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11.  
  12. The above copyright notice and this permission notice shall be included in
  13. all copies or substantial portions of the Software.
  14.  
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. THE SOFTWARE.
  22. */
  23.  
  24. #include <stdio.h>
  25. #include <math.h>
  26. #include <stdlib.h>
  27.  
  28.  
  29. /*
  30.  
  31. NOTE:
  32.  
  33. The most important part of the code are the lines 105 to 121. Here the Gauss-Seidel method is implemented.
  34. */
  35.  
  36. #include <set>
  37. #include <vector>
  38.  
  39. const int N = 100;
  40. const float SHRINKING_FACTOR = 7.5f;
  41. const int NO_PROGRESS_STREAK_THRESHOLD = 100;
  42. const float EPS = 0.00001f;
  43. typedef std::vector<int> Partition;
  44.  
  45. // vector of dimension Nx1
  46. class Vec {
  47. public:
  48. float v[N];
  49.  
  50. Vec() {
  51. for (int i = 0; i < N; ++i) {
  52. v[i] = 0.0f;
  53. }
  54. }
  55.  
  56. void print(char* s) {
  57. printf("%s ", s);
  58. for (int i = 0; i < N; ++i) {
  59. printf("%f, ", v[i]);
  60. }
  61. printf("\n");
  62. }
  63. };
  64.  
  65. // matrix of dimension NxN.
  66. class Mat {
  67. public:
  68. float m[N][N];
  69.  
  70. Mat() {
  71. for (int i = 0; i < N; ++i) {
  72. for (int j = 0; j < N; ++j) {
  73. m[i][j] = 0.0f;
  74. }
  75. }
  76. }
  77.  
  78. void print(char* s) {
  79. printf("%s ", s);
  80. for (int i = 0; i < N; ++i) {
  81.  
  82. for (int j = 0; j < N; ++j) {
  83. printf("%f, ", m[i][j]);
  84. }
  85. printf("\n");
  86. }
  87. printf("\n");
  88. }
  89.  
  90. Vec mult(const Vec& v) const {
  91. Vec r;
  92.  
  93. for (int row = 0; row < N; ++row) {
  94. for (int col = 0; col < N; ++col) {
  95. r.v[row] += this->m[row][col] * v.v[col];
  96. }
  97. }
  98. return r;
  99. }
  100.  
  101. static int gauss_seidel(Vec& x, const Vec& b, const Mat& m, float tol, int maxiter, const std::vector<Partition>& partitions) {
  102.  
  103. int iter;
  104. for (iter = 0; iter < maxiter; ++iter) {
  105. for (Partition partition : partitions) {
  106. // we do a gauss-seidel step for this partition.
  107. // every partition stores a set of variables that will be solved for.
  108. // and these variables can be solved for independently of each other.
  109. // thus, the below loop can easily be parallelized.
  110. // note that this code is very similar to the Gauss-Seidel method implemented
  111. // in the previous article. It's just that the variables are solved for in a different order.
  112. for (int variable : partition) {
  113. float s = 0.0f;
  114. for (int j = 0; j < N; ++j) {
  115. if (j != variable) {
  116. s += m.m[variable][j] * x.v[j];
  117. }
  118. }
  119. x.v[variable] = (1.0f / m.m[variable][variable]) * (b.v[variable] - s);
  120. }
  121. }
  122.  
  123. Vec mx = m.mult(x);
  124.  
  125. float norm = 0.0f;
  126. for (int i = 0; i < N; ++i) {
  127. float a = mx.v[i] - b.v[i];
  128. norm += a*a;
  129. }
  130. norm = sqrt(norm);
  131.  
  132. if (norm < tol) {
  133. break;
  134. }
  135. }
  136.  
  137. return iter;
  138. }
  139. };
  140.  
  141. std::vector<Partition> randomized_graph_coloring(const Mat& m) {
  142. std::set<int> neighbours[N];
  143.  
  144. int node_colors[N]; // colors assigned to the nodes.
  145. int next_color[N]; // next color of every node, in case the palette runs out.
  146. std::set<int> node_palettes[N]; // palettes of the nodes.
  147. std::set<int> U;
  148.  
  149. /*
  150. Every node needs to know about it's neighbours. so find that.
  151.  
  152. There is an edge between two nodes i and j, if the matrix coefficient at row i, column j is non-zero.
  153. */
  154. for (int i = 0; i < N; ++i) {
  155. for (int j = 0; j < N; ++j) {
  156. if (i != j && fabs(m.m[i][j]) > EPS) {
  157.  
  158. // if necessary, make j a neighbour of i.
  159. if (neighbours[i].find(j) == neighbours[i].end()) {
  160. neighbours[i].insert(j);
  161. }
  162.  
  163. // if necessary, make i a neighbour of j.
  164. if (neighbours[j].find(i) == neighbours[j].end()) {
  165. neighbours[j].insert(i);
  166. }
  167. }
  168. }
  169. }
  170.  
  171. // calculate max degree of a single node.
  172. int delta_v = 0;
  173. for (int i = 0; i < N; ++i) {
  174. if ((int)neighbours[i].size() > delta_v) {
  175. delta_v = neighbours[i].size();
  176. }
  177. }
  178.  
  179. // initially, every node has a palette of size delta_v/shrinking_factor.
  180. // the maximum number of colors necessary for a graph coloring is delta_v, but many
  181. // graphs won't need that many colors. therefore, we choose to shrink delta_v by a shrinking factor.
  182. // if the shrinking factor is too big, so that the problem is unsolvable, then more colors will be added on the fly.
  183. int max_color = int((float)delta_v / SHRINKING_FACTOR);
  184. if (max_color <= 0) {
  185. max_color = 1;
  186. }
  187. max_color = 2;
  188.  
  189. // initialize the palettes for all the node.
  190. // the colors in the palette will be chosen randomly from, for all the remaining nodes in U.
  191. for (int iv = 0; iv < N; ++iv) {
  192. for (int ic = 0; ic < max_color; ++ic) {
  193. node_palettes[iv].insert(ic);
  194. }
  195. next_color[iv] = max_color;
  196. }
  197.  
  198. for (int iv = 0; iv < N; ++iv) {
  199. U.insert(iv);
  200. }
  201.  
  202. // keep track of the number of iterations with no progress.
  203. int no_progress_streak = 0;
  204.  
  205. /*
  206. If a node has found a color that solves the graph coloring for that node, then remove from U.
  207. Once U is empty, the graph coloring problem is done.
  208. */
  209. while (U.size()) {
  210.  
  211. // all remaining nodes in U are given a random color.
  212. for (int iv : U) {
  213. // get random color from palette, and assign it.
  214. int m = rand() % node_palettes[iv].size();
  215. auto setIt = node_palettes[iv].begin();
  216. advance(setIt, m);
  217.  
  218. node_colors[iv] = *setIt;
  219. }
  220.  
  221. std::set<int> temp;
  222.  
  223.  
  224. /*
  225. Now let's find all the nodes whose colors are different from all their neighbours.
  226. Those nodes will be removed from U, because they are done, with respect to the graph coloring problem.
  227. */
  228. for (int iv : U) {
  229.  
  230. int icolor = node_colors[iv];
  231.  
  232. /*
  233. Check if graph coloring property is solved for node.
  234. */
  235. bool different_from_neighbours = true;
  236. for (int neighbour : neighbours[iv]) {
  237.  
  238. if (node_colors[neighbour] == icolor) {
  239. different_from_neighbours = false;
  240. break;
  241. }
  242. }
  243.  
  244. if (different_from_neighbours) {
  245. // found the right color for this one.
  246. // so remove from U.
  247.  
  248. // also, the neighbours of iv can't use this color anymore.
  249. // so remove it from their palettes.
  250. for (int neighbour : neighbours[iv]) {
  251. node_palettes[neighbour].erase(icolor);
  252. }
  253.  
  254. }
  255. else {
  256. // not a correct color. don't remove from U.
  257. temp.insert(iv);
  258. }
  259.  
  260. // feed the hungry!
  261. // if palette empty, we add more colors on the fly.
  262. // if we don't do this, the algorithm will get stuck in a loop.
  263. if (node_palettes[iv].empty()) {
  264. node_palettes[iv].insert(next_color[iv]++);
  265. }
  266.  
  267. }
  268.  
  269. if (U.size() == temp.size()) {
  270. no_progress_streak++;
  271.  
  272. // if no progress for too many iterations, we have no choice but to feed a random node.
  273. if (no_progress_streak > NO_PROGRESS_STREAK_THRESHOLD) {
  274. int m = rand() % U.size();
  275. auto setIt = U.begin();
  276. advance(setIt, m);
  277.  
  278. node_palettes[*setIt].insert(next_color[*setIt]++);
  279.  
  280. no_progress_streak = 0;
  281. }
  282. }
  283.  
  284. U = temp;
  285. }
  286.  
  287. // find the number of colors used in our solution.
  288. // this is also the number of partitions.
  289. int num_colors = 0;
  290. for (int i = 0; i < N; ++i) {
  291. if (next_color[i] > num_colors) {
  292. num_colors = next_color[i];
  293. }
  294. }
  295.  
  296. /*
  297. Finally, we collect all the partitions then.
  298. */
  299. std::vector<Partition> partitions;
  300. for (int ic = 0; ic < num_colors; ++ic) {
  301. Partition partition;
  302.  
  303. /*
  304. The first partition is all nodes that use color 0,
  305. the second partition use color 1, and so on.
  306. */
  307. for (int inode = 0; inode < N; ++inode) {
  308. if (node_colors[inode] == ic) {
  309. partition.push_back(inode);
  310. }
  311. }
  312.  
  313. partitions.push_back(partition);
  314. }
  315.  
  316. return partitions;
  317. }
  318.  
  319.  
  320. Mat get_diagonally_dominant_matrix() {
  321. Mat m;
  322.  
  323. /*
  324. generate random matrix entries
  325. */
  326. for (int i = 0; i < N; ++i) {
  327. for (int j = i; j < N; ++j) {
  328. if (rand() % 9 == 0) {
  329. m.m[i][j] = float(rand() % 10);
  330. m.m[j][i] = m.m[i][j];
  331. }
  332. }
  333. }
  334.  
  335. /*
  336. Now we iterate over every row, and modify the matrix to make sure it's diagonally dominant.
  337. */
  338. for (int i = 0; i < N; ++i) {
  339. float diag = fabs(m.m[i][i]);
  340. float row_sum = 0.0f;
  341.  
  342. for (int j = 0; j < N; ++j) {
  343. if (i != j) {
  344. row_sum += fabs(m.m[i][j]);
  345. }
  346. }
  347.  
  348. /*
  349. Not diagonally dominant. So increase the diagonal value to fix that.
  350. */
  351. if (!(diag >= row_sum)) {
  352. m.m[i][i] += (row_sum - diag);
  353. }
  354.  
  355. if (fabs(m.m[i][i]) < EPS) {
  356. m.m[i][i] += 1.0f;
  357. }
  358. }
  359.  
  360. return m;
  361. }
  362.  
  363. int main() {
  364. srand(13000);
  365.  
  366. Mat m = get_diagonally_dominant_matrix();
  367.  
  368. int nonZeros = 0;
  369. for (int i = 0; i < N; ++i) {
  370. for (int j = i; j < N; ++j) {
  371. if (fabs(m.m[i][j]) > EPS) {
  372. nonZeros++;
  373. }
  374. }
  375. }
  376. printf("percent of non-zeros of M: %d%%\n", int(100.0f * float(nonZeros) / float(N*N)));
  377.  
  378. Vec expected_solution;
  379. for (int i = 0; i < N; ++i) {
  380. expected_solution.v[i] = 8.0f * float(rand() % 100) / 100.0f - 4.0f;
  381. }
  382.  
  383. Vec b = m.mult(expected_solution);
  384.  
  385. /*
  386. With that, we have generated a linear system
  387. M*x = b.
  388. Now let's solve it!
  389. */
  390.  
  391. Vec x;
  392. for (int i = 0; i < N; ++i) {
  393. x.v[i] = 0.0f;
  394. }
  395.  
  396. printf("solving linear system where N = %d\n\n\n", N);
  397.  
  398. expected_solution.print("expected solution:\n");
  399. printf("\n");
  400.  
  401. // graph coloring to partition the problem.
  402. std::vector<Partition> partitions = randomized_graph_coloring(m);
  403.  
  404. int iter = Mat::gauss_seidel(x, b, m, 0.001f, 10000, partitions);
  405. printf("number of partitions: %d\n", partitions.size());
  406. x.print("gauss-seidel method solution:\n");
  407. printf("number of iterations: %d\n", iter);
  408.  
  409. system("pause");
  410. }
Add Comment
Please, Sign In to add comment