From 556fea05affe6fe8866557d42b6c1ef6559d7880 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Sat, 7 Nov 2026 06:20:46 +0300 Subject: publish --- src/config.h | 66 +++ src/distribution-test.c | 63 +++ src/distribution.c | 57 +++ src/distribution.h | 22 + src/dynamic-array.h | 74 +++ src/graph.c | 1311 +++++++++++++++++++++++++++++++++++++++++++++++ src/graph.h | 71 +++ src/main.c | 580 +++++++++++++++++++++ src/utils.c | 108 ++++ src/utils.h | 33 ++ 10 files changed, 2385 insertions(+) create mode 100644 src/config.h create mode 100644 src/distribution-test.c create mode 100644 src/distribution.c create mode 100644 src/distribution.h create mode 100644 src/dynamic-array.h create mode 100644 src/graph.c create mode 100644 src/graph.h create mode 100644 src/main.c create mode 100644 src/utils.c create mode 100644 src/utils.h (limited to 'src') diff --git a/src/config.h b/src/config.h new file mode 100644 index 0000000..fa04908 --- /dev/null +++ b/src/config.h @@ -0,0 +1,66 @@ +#ifndef INCLUDED_CONFIG_H +#define INCLUDED_CONFIG_H + +#define INITIAL_SCREEN_WIDTH 500 +#define INITIAL_SCREEN_HEIGHT 500 +#define WINDOW_TITLE "Graph visualization" + +// // TODO(cmmm): compute +#define BUTTON_HEIGHT 30 +#define BUTTON_WIDTH 300 +#define PADDING 10 + +#define VERTEX_RADIUS 20 +#define BASE_LINE_THICKNESS 6 + +#define FONT_SIZE 20 +#define TEXT_SPACING 1 + +#define INITIAL_VERTEX_COUNT 8 + +#define MAX_VERTEX_COUNT ((size_t) 40) +#define MAX_WEIGHT ((double) 10) +#define MAX_CAPACITY ((double) MAX_WEIGHT) + +#define DIST_N 10 +#define DIST_B 20 +#define DIST_R 1 +#define DIST_C 10 + +#define MODEL_L ((double) 1.0) +#define MODEL_C_REP ((double) 1.0) +#define MODEL_C_SPRING ((double) 10.0) +#define MODEL_COOLING_FACTOR ((double) 0.9) + +#define DARK_THEME +#if defined (LIGHT_THEME) +#define BACKGROUND_COLOR WHITE +#define VERTEX_COLOR RED +#define VERTEX_OUTLINE_COLOR MAROON +#define VERTEX_OUTLINE_HIGHLIGHTED_COLOR BLACK +#define VERTEX_TEXT_COLOR WHITE +#define EDGE_TEXT_COLOR BLACK +#define BUTTON_COLOR LIGHTGRAY +#define BUTTON_OUTLINE_COLOR GRAY +#define BUTTON_HOVER_COLOR MAROON +#define BUTTON_HOVER_OUTLINE_COLOR RED +#define BUTTON_TEXT_COLOR BLACK +#define BUTTON_TEXT_HOVER_COLOR WHITE +#elif defined (DARK_THEME) +#define BACKGROUND_COLOR BLACK +// #define EDGE_MIN_COLOR WHITE +// #define EDGE_MAX_COLOR WHITE +#define EDGE_TEXT_COLOR WHITE +#define VERTEX_COLOR RED +#define VERTEX_OUTLINE_COLOR MAROON +#define VERTEX_OUTLINE_HIGHLIGHTED_COLOR WHITE +#define VERTEX_TEXT_COLOR WHITE +#define BUTTON_COLOR DARKGRAY +#define BUTTON_OUTLINE_COLOR GRAY +#define BUTTON_HOVER_COLOR MAROON +#define BUTTON_HOVER_OUTLINE_COLOR RED +#define BUTTON_TEXT_COLOR LIGHTGRAY +#define BUTTON_TEXT_HOVER_COLOR LIGHTGRAY +#endif + +#endif diff --git a/src/distribution-test.c b/src/distribution-test.c new file mode 100644 index 0000000..178bf73 --- /dev/null +++ b/src/distribution-test.c @@ -0,0 +1,63 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include + +#include "distribution.h" + +int +main (void) +{ + const int screen_padding = 10; + const int notation_height = 20; + + int screen_width = 800; + int screen_height = 450; + + SetConfigFlags (FLAG_MSAA_4X_HINT | + FLAG_WINDOW_RESIZABLE | + FLAG_VSYNC_HINT | + FLAG_WINDOW_UNDECORATED); + InitWindow (screen_width, screen_height, "graph"); + SetTargetFPS (60); + + srand (time (NULL)); + struct distribution dist; + // distribution_init (&dist, 20, 20, 1, 10); + distribution_init (&dist, 11, 20, 1, 10); + + int arr[dist.n - 1]; + memset (arr, 0, sizeof (arr)); + int iterrations = 10000; + for (int i = 0; i < iterrations; ++i) + arr[distribution_rand (&dist)] += 1; + + while (!WindowShouldClose ()) { + BeginDrawing (); + ClearBackground (WHITE); + + screen_width = GetScreenWidth (); + screen_height = GetScreenHeight (); + + const int rect_width = (screen_width - screen_padding)/(dist.n - 1) - screen_padding; + const int rect_max_height = screen_height - 2*screen_padding - notation_height; + for (int i = 0; i < dist.n - 1; ++i) { + const int rect_height = rect_max_height*arr[i]/iterrations; + DrawRectangle ((i + 1)*screen_padding + i*rect_width, + screen_padding + rect_max_height - rect_height, + rect_width, rect_height, BLACK); + + char *perc; + asprintf (&perc, "%2d%%", arr[i]*100/iterrations); + DrawText (perc, (i + 1)*screen_padding + i*rect_width + rect_width/4, screen_height - screen_padding - 3*notation_height/4, notation_height, BLACK); + } + + EndDrawing (); + } + + CloseWindow (); + + return EXIT_SUCCESS; +} diff --git a/src/distribution.c b/src/distribution.c new file mode 100644 index 0000000..7887ba3 --- /dev/null +++ b/src/distribution.c @@ -0,0 +1,57 @@ +#define _GNU_SOURCE +#include +#include +#include + +#include "distribution.h" + +void +distribution_init (DISTRIBUTION dist, + unsigned int n, + unsigned int b, + unsigned int r, + int c) +{ + assert (n > 0); + assert (b > 0); + assert (r > 0); + assert (b + r + c*(n - 1) > 0); + + dist->n = n; + dist->b = b; + dist->r = r; + dist->c = c; + dist->p0 = r/(float)(b + r); + for (int i = 1; i < n; ++i) { + dist->p0 *= (r + i*c)/(float)(b + r + i*c); + } +} + +int +distribution_rand (DISTRIBUTION dist) +{ + for (;;) { + double p = dist->p0; + double r = rand ()/(double) RAND_MAX; + // printf ("r = %f, p = %f\n", r, p); + unsigned int x = 0; + + while (x < dist->n - 1) { + r -= p; + if (r < 0) + return x; + x += 1; + p *= ((dist->n - 1 - x) * + (dist->b + (x - 1)*dist->c) /(double) + (x*(dist->r + (dist->n - x)*dist->c))); + // printf ("p = %f\n", p); + } // putchar ('\n'); + } + // return dist->n; +} + +double +distribution_nrand (DISTRIBUTION dist) +{ + return distribution_rand (dist)/(double) (dist->n - 2); +} diff --git a/src/distribution.h b/src/distribution.h new file mode 100644 index 0000000..c4b20b9 --- /dev/null +++ b/src/distribution.h @@ -0,0 +1,22 @@ +#ifndef INCLUDED_DISTRIBUTION_H +#define INCLUDED_DISTRIBUTION_H + +// Multivariate Pólya distribution +typedef struct distribution +{ + unsigned int n; + unsigned int b; + unsigned int r; + int c; + double p0; +}* DISTRIBUTION; + +void distribution_init (DISTRIBUTION dist, + unsigned int n, + unsigned int b, + unsigned int r, + int c); +int distribution_rand (DISTRIBUTION dist); +double distribution_nrand (DISTRIBUTION dist); + +#endif diff --git a/src/dynamic-array.h b/src/dynamic-array.h new file mode 100644 index 0000000..bd470d5 --- /dev/null +++ b/src/dynamic-array.h @@ -0,0 +1,74 @@ +#ifndef INCLUDED_DYNAMIC_ARRAY_H +#define INCLUDED_DYNAMIC_ARRAY_H + +#include "utils.h" + +#ifndef DYNAMIC_ARRAY_INIT_CAP +#define DYNAMIC_ARRAY_INIT_CAP 256 +#endif + +#define DYNAMIC_ARRAY_ENSURE_CAPACITY(DYNAMIC_ARRAY, COUNT) \ + ({ \ + if ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) { \ + if ((DYNAMIC_ARRAY).capacity == 0) \ + (DYNAMIC_ARRAY).capacity = DYNAMIC_ARRAY_INIT_CAP; \ + while ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) \ + (DYNAMIC_ARRAY).capacity *= 2; \ + (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \ + (DYNAMIC_ARRAY).capacity * \ + sizeof (*(DYNAMIC_ARRAY).items)); \ + ASSERT((DYNAMIC_ARRAY).items); \ + } \ + }) + +#define DYNAMIC_ARRAY_SHRINK(DYNAMIC_ARRAY) \ + ({ \ + (DYNAMIC_ARRAY).capacity = (DYNAMIC_ARRAY).count; \ + (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \ + (DYNAMIC_ARRAY).capacity * \ + sizeof (*(DYNAMIC_ARRAY).items)); \ + ASSERT((DYNAMIC_ARRAY).items); \ + \ + }) + +#define DYNAMIC_ARRAY_APPEND(DYNAMIC_ARRAY, ITEM) \ + ({ \ + DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), 1); \ + (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count++] = (ITEM); \ + }) + +#define DYNAMIC_ARRAY_APPEND_MANY(DYNAMIC_ARRAY, NEW_ITEMS, NEW_ITEMS_COUNT) \ + ({ \ + DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), (NEW_ITEMS_COUNT)); \ + memcpy ((DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count, (NEW_ITEMS), \ + (NEW_ITEMS_COUNT)*sizeof (*(DYNAMIC_ARRAY).items)); \ + (DYNAMIC_ARRAY).count += (NEW_ITEMS_COUNT); \ + }) + +#define DYNAMIC_ARRAY_APPEND_OTHER(DYNAMIC_ARRAY, OTHER) \ + DYNAMIC_ARRAY_APPEND_MANY ((DYNAMIC_ARRAY), (OTHER).items, (OTHER).count) + +#define DYNAMIC_ARRAY_COPY_OTHER(DYNAMIC_ARRAY, OTHER) \ + ({ \ + DYNAMIC_ARRAY_RESET ((DYNAMIC_ARRAY)); \ + DYNAMIC_ARRAY_APPEND_OTHER ((DYNAMIC_ARRAY), (OTHER)); \ + }) + +#define DYNAMIC_ARRAY_ERASE(DYNAMIC_ARRAY, IDX) \ + ({ \ + memmove (&(DYNAMIC_ARRAY).items[(IDX) + 0], \ + &(DYNAMIC_ARRAY).items[(IDX) + 1], \ + ((DYNAMIC_ARRAY).count - (IDX) - 1) \ + * sizeof (*(DYNAMIC_ARRAY).items)); \ + (DYNAMIC_ARRAY).count -= 1; \ + }) + +#define DYNAMIC_ARRAY_RESET(DYNAMIC_ARRAY) ({ (DYNAMIC_ARRAY).count = 0; }) + +#define DYNAMIC_ARRAY_FREE(DYNAMIC_ARRAY) FREE((DYNAMIC_ARRAY).items) + +#define DYNAMIC_ARRAY_FOREACH(ITEM, DYNAMIC_ARRAY) for ( \ + typeof ((DYNAMIC_ARRAY).items) ITEM = (DYNAMIC_ARRAY).items; \ + ITEM < (DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count; ++ITEM) + +#endif diff --git a/src/graph.c b/src/graph.c new file mode 100644 index 0000000..dd7058b --- /dev/null +++ b/src/graph.c @@ -0,0 +1,1311 @@ +#include "graph.h" +#include "config.h" +#include "utils.h" +#include "dynamic-array.h" +#include +#include +#include +#include + +#define ALLOC_SQUARE_GSL_MATRIX(n) gsl_matrix_calloc ((n), (n)) + +gsl_matrix * +shimbell_method (GRAPH g, size_t edge_count, bool max) +{ + size_t n = g->vertex_count; + gsl_matrix *adj = g->weight_matrix; + gsl_matrix *shimbell = ALLOC_SQUARE_GSL_MATRIX (n); + + gsl_matrix_memcpy (shimbell, adj); + if (n == 1) + return shimbell; + + gsl_matrix *tmp = ALLOC_SQUARE_GSL_MATRIX (n); + for (size_t l = 0; l < edge_count; ++l) { + gsl_matrix_memcpy (tmp, shimbell); + for (size_t i = 0; i < n; ++i) { + for (size_t j = 0; j < n; ++j) { + double bestval = max ? 0 : INFINITY; + for (size_t k = 0; k < n; ++k) { + double a = gsl_matrix_get (tmp, k, j); + double b = gsl_matrix_get (adj, i, k); + if (a == 0 || b == 0) + continue; + double val = a + b; + if (max ? val > bestval + : val < bestval) { + bestval = val; + } + } gsl_matrix_set (shimbell, i, j, bestval); + } + } + } gsl_matrix_free (tmp); + + return shimbell; +} + +size_t +graph_count_routes (GRAPH g, size_t from, size_t to) +{ + size_t n = g->vertex_count; + gsl_matrix *adj = g->adjecency_matrix; + gsl_matrix *con = ALLOC_SQUARE_GSL_MATRIX(n); + gsl_matrix *pow = ALLOC_SQUARE_GSL_MATRIX(n); + gsl_matrix *tmp = ALLOC_SQUARE_GSL_MATRIX(n); + + for (size_t e = 0; e < n*n; ++e) + con->data[e] = adj->data[e] != 0 ? 1 : 0; + gsl_matrix_memcpy (pow, con); + gsl_matrix_memcpy (tmp, con); + + size_t count = gsl_matrix_get (pow, from, to); + for (size_t k = 0; k < n - 2; ++k) { + gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, + 1.0, tmp, con, + 0.0, pow); + count += gsl_matrix_get (pow, from, to); + gsl_matrix *swap = tmp; + tmp = pow; + pow = swap; + } + + gsl_matrix_free (con); + gsl_matrix_free (tmp); + gsl_matrix_free (pow); + + return count; +} + +static inline void +is_graph_connected_implementation (gsl_matrix *adj, bool *visited, size_t v) +{ + size_t n = adj->size1; + visited[v] = true; + for (size_t i = 0; i < n; ++i) { + if (!visited[i] && + (gsl_matrix_get(adj, v, i) || + gsl_matrix_get(adj, i, v))) { + is_graph_connected_implementation (adj, visited, i); + } + } +} + +bool +is_graph_connected (GRAPH g) +{ + size_t n = g->vertex_count; + bool visited[n]; + memset (visited, 0, sizeof (visited)); + is_graph_connected_implementation (g->adjecency_matrix, visited, 0); + for (size_t i = 0; i < n; ++i) { + if (!visited[i]) return false; + } return true; +} + +bool +is_graph_algebraically_connected (gsl_matrix *adj) +{ + size_t n = adj->size1; + + gsl_matrix *laplacian = gsl_matrix_alloc (n, n); + for (size_t i = 0; i < n; ++i) { + double deg = 0; + for (size_t j = i + 1; j < n; ++j) { + double val = gsl_matrix_get (adj, i, j); + gsl_matrix_set (laplacian, j, i, val == 0.0 ? 0.0 : -val); + deg += gsl_matrix_get (adj, i, j); + } gsl_matrix_set (laplacian, i, i, deg); + } + + gsl_vector *eval = gsl_vector_alloc (n); + gsl_eigen_symm_workspace *w = gsl_eigen_symm_alloc (n); + gsl_eigen_symm (laplacian, eval, w); + gsl_sort_vector (eval); + double fiedler = gsl_vector_get (eval, 1); + + gsl_eigen_symm_free (w); + gsl_vector_free (eval); + gsl_matrix_free (laplacian); + + return fiedler > 1e-12 ? true : false; +} + +void +generate_graph (GRAPH g, DISTRIBUTION dist, + size_t vertex_count, enum graph_type type) +{ + g->vertex_count = vertex_count; + g->type = type; + + size_t n = vertex_count; + // size_t m = n - 1; + size_t m = MIN (n*3/2, (n*n - n)/2); + + g -> adjecency_matrix = ALLOC_SQUARE_GSL_MATRIX(n); + g -> weight_matrix = ALLOC_SQUARE_GSL_MATRIX(n); + g -> capacity_matrix = ALLOC_SQUARE_GSL_MATRIX(n); + + // for (size_t i = 0; i < n - 1; ++i) { + // size_t max_degree = n - i - 1; + // size_t degree = floor (distribution_nrand (dist)*(max_degree - 1)) + 1; + + // for (size_t j = 0; j < degree; ++j) { + // double weight = floor ((MAX_WEIGHT - 1)*distribution_nrand (dist)) + 1; + // if (g->type == GRAPH_TYPE_POSITIVE_NEGATIVE && rand () % 2) + // weight = -weight; + // double capacity = floor (MAX_CAPACITY*distribution_nrand (dist)); + // gsl_matrix_set (g -> adjecency_matrix, i, j + i + 1, 1); + // gsl_matrix_set (g -> weight_matrix, i, j + i + 1, weight); + // gsl_matrix_set (g -> capacity_matrix, i, j + i + 1, capacity); + // } + // } + + for (size_t k = 0; k < m || !is_graph_connected (g); ++k) { + size_t r = floor (n*n*distribution_nrand (dist)) + 1; + // size_t r = floor (n*n*(rand ()/(double) RAND_MAX)) + 1; + ssize_t i = floor ((r - 1)/(double) n); + ssize_t j = (r - 1) % n; + // printf ("%2zu %zd %zd\n", r, i, j); + + if (i < j && !gsl_matrix_get (g->adjecency_matrix, i, j)) { + double weight = floor ((MAX_WEIGHT - 1)*distribution_nrand (dist)) + 1; + if (g->type == GRAPH_TYPE_POSITIVE_NEGATIVE && rand () % 2) + weight = -weight; + double capacity = floor (MAX_CAPACITY*distribution_nrand (dist)); + gsl_matrix_set (g -> adjecency_matrix, i, j, 1); + gsl_matrix_set (g -> weight_matrix, i, j, weight); + gsl_matrix_set (g -> capacity_matrix, i, j, capacity); + } else m += 1; + } +} + +size_t * +dijkstra_positive (GRAPH g, size_t from, size_t to, bool max) +{ + struct dijkstra_node + { + double distance; + size_t previous; + bool visited; + }; + + size_t n = g->vertex_count; + + double cost[MAX_VERTEX_COUNT][MAX_VERTEX_COUNT]; + for (size_t i = 0; i < n; ++i) { + for (size_t j = 0; j < n; ++j) { + double val = gsl_matrix_get (g->weight_matrix, i, j); + if (val == 0) + cost[i][j] = max ? -INFINITY : INFINITY; + else + cost[i][j] = val; + } + } + + struct dijkstra_node nodes[MAX_VERTEX_COUNT]; + for (size_t i = 0; i < n; ++i) { + nodes[i] = (struct dijkstra_node) { + .distance = cost[from][i], + .previous = from, + .visited = false, + }; + } + nodes[from].distance = 0; + nodes[from].visited = true; + + for (size_t count = 1; count < n - 1; ++count) { + size_t next; + double best_distance = max ? -INFINITY : INFINITY; + for (size_t i = 0; i < n; i++) { + if ((max ? nodes[i].distance > best_distance + : nodes[i].distance < best_distance) + && !nodes[i].visited) { + best_distance = nodes[i].distance; + next = i; + } + } + + nodes[next].visited = true; + for (size_t i = 0; i < n; ++i) { + if (!nodes[i].visited) { + double distance = best_distance + cost[next][i]; + if ((max ? distance > nodes[i].distance + : distance < nodes[i].distance)) { + nodes[i].distance = distance; + nodes[i].previous = next; + } + } + } + } + + printf ("DISTANCE VECTOR: (%.f", nodes[0].distance); + for (size_t i = 0; i < n; ++i) { + printf (" %.f", nodes[i].distance); + } puts (")"); + + if (nodes[to].distance == (max ? -INFINITY : INFINITY)) { + printf ("NO PATH FROM %zu TO %zu\n", from, to); + return NULL; + } + + size_t len = 1; + for (size_t i = to; i != from; i = nodes[i].previous) + len += 1; + + size_t *path = malloc ((len + 1)*sizeof (*path)); + size_t v = len; + path[v--] = n; + for (size_t i = to; i != from; i = nodes[i].previous) + path[v--] = i; + path[v] = from; + + printf ("PATH: %zu", path[0]); + for (size_t i = 1; path[i] != n; ++i) + printf (" -> %zu", path[i]); + putchar ('\n'); + + return path; +} + +size_t * +floyd_warshall (GRAPH g, size_t from, size_t to, bool max) +{ + const size_t n = g->vertex_count; + double dist[MAX_VERTEX_COUNT][MAX_VERTEX_COUNT]; + size_t next[MAX_VERTEX_COUNT][MAX_VERTEX_COUNT]; + + // initialize dist and next + for (size_t u = 0; u < n; ++u) { + for (size_t v = 0; v < n; ++v) { + if (gsl_matrix_get (g->weight_matrix, u, v) == 0) { + dist[u][v] = max ? -INFINITY : INFINITY; + next[u][v] = n; + } else { + dist[u][v] = gsl_matrix_get (g->weight_matrix, u, v); + next[u][v] = v; + } + dist[v][v] = 0; + next[v][v] = v; + } + } + + // compute dist and next + for (size_t k = 0; k < n; ++k) { + for (size_t i = 0; i < n; ++i) { + for (size_t j = 0; j < n; ++j) { + if (max ? dist[i][j] < dist[i][k] + dist[k][j] + : dist[i][j] > dist[i][k] + dist[k][j]) { + dist[i][j] = dist[i][k] + dist[k][j]; + next[i][j] = next[i][k]; + } + } + } + } + + puts ("DISTANCE MATRIX:"); + printf (" "); + for (size_t j = 0; j < n; j++) + printf (" [%zu]", j); + putchar ('\n'); + for (size_t i = 0; i < n; i++) { + printf ("[%zu]", i); + for (size_t j = 0; j < n; j++) + printf ("%4g", dist[i][j]); + putchar ('\n'); + } + + // find path + if (next[from][to] == n) { + printf ("NO PATH FROM %zu TO %zu\n", from, to); + return NULL; + } + + size_t len = 1; + for (size_t v = from; v != to; v = next[v][to]) + len += 1; + + size_t *path = malloc ((len + 1)*sizeof (*path)); + size_t e = 0; + for (size_t v = from; v != to; v = next[v][to]) + path[e++] = v; + path[e++] = to; + path[e] = n; + + printf ("PATH: %zu", path[0]); + for (size_t i = 1; path[i] != n; ++i) + printf (" -> %zu", path[i]); + putchar ('\n'); + + return path; +} + +void +graph_unhighlight (GRAPH g) +{ + free (g->highlighted_path); + g->highlighted_path = NULL; + DYNAMIC_ARRAY_RESET (g->highlighted_edges); +} + +void +graph_edge_set (GRAPH g, size_t from, size_t to, + double weight, double capacity) +{ + gsl_matrix_set (g -> adjecency_matrix, from, to, weight && capacity); + gsl_matrix_set (g -> weight_matrix, from, to, weight); + gsl_matrix_set (g -> capacity_matrix, from, to, capacity); +} + +void +print_graph (GRAPH g) +{ + puts ("ADJECENCY_MATRIX:"); + print_gsl_matrix (g->adjecency_matrix); + puts ("WEIGHT/COST_MATRIX:"); + print_gsl_matrix (g->weight_matrix); + puts ("CAPACITY_MATRIX:"); + print_gsl_matrix (g->capacity_matrix); +} + +bool +are_vertices_connected (gsl_matrix *g, size_t from, size_t to) +{ + size_t n = g->size1; + struct stack { + size_t *items; + size_t count; + size_t capacity; + }; + + struct stack stack1 = {0}; DYNAMIC_ARRAY_ENSURE_CAPACITY (stack1, n); + struct stack stack2 = {0}; DYNAMIC_ARRAY_ENSURE_CAPACITY (stack2, n); + struct stack *front_stack = &stack1; + struct stack *back_stack = &stack2; + DYNAMIC_ARRAY_APPEND (*front_stack, from); + while (front_stack->count) { + DYNAMIC_ARRAY_RESET (*back_stack); + DYNAMIC_ARRAY_FOREACH (v, *front_stack) { + size_t vertex = *v; + for (size_t i = 0; i < n; ++i) { + if (gsl_matrix_get (g, vertex, i)) { + if (to == i) return true; + DYNAMIC_ARRAY_APPEND (*back_stack, i); + } + } + } SWAP (front_stack, back_stack); + } + + return false; +} + +void +highlight_graph (GRAPH g, const gsl_matrix *m) +{ + DYNAMIC_ARRAY_RESET (g->highlighted_edges); + size_t n = g->vertex_count; + for (size_t i = 0; i < n; ++i) { + for (size_t j = 0; j < n; ++j) { + if (gsl_matrix_get (m, i, j)) + DYNAMIC_ARRAY_APPEND (g->highlighted_edges, ((struct edge) {i, j})); + } + } +} + +// https://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm +// https://algorithms.discrete.ma.tum.de/graph-algorithms/flow-ford-fulkerson/index_en.html +double +max_flow_ford_fulkerson (GRAPH g, size_t source, size_t sink) +{ + size_t n = g->vertex_count; + size_t parents[MAX_VERTEX_COUNT]; + for (size_t i = 0; i < MAX_VERTEX_COUNT; ++i) + parents[i] = n; + + gsl_matrix *residual_capacity_matrix = gsl_matrix_alloc (n, n); + gsl_matrix_memcpy (residual_capacity_matrix, g->capacity_matrix); + double max_flow = 0; + + struct stack { + size_t *items; + size_t count; + size_t capacity; + }; + + DYNAMIC_ARRAY_RESET (g->highlighted_edges); + struct stack stack1 = {0}; DYNAMIC_ARRAY_ENSURE_CAPACITY (stack1, n); + struct stack stack2 = {0}; DYNAMIC_ARRAY_ENSURE_CAPACITY (stack2, n); + struct stack *front_stack = &stack1; + struct stack *back_stack = &stack2; + for (;;) { + bool visited[MAX_VERTEX_COUNT] = { false }; + DYNAMIC_ARRAY_RESET (*front_stack); + DYNAMIC_ARRAY_APPEND (*front_stack, source); + visited[source] = true; + while (front_stack->count) { + DYNAMIC_ARRAY_RESET (*back_stack); + DYNAMIC_ARRAY_FOREACH (v, *front_stack) { + size_t vertex = *v; + for (size_t i = 0; i < n; ++i) { + if (!visited[i] && + gsl_matrix_get (residual_capacity_matrix, vertex, i) > 0) { + parents[i] = vertex; + if (sink == i) goto found; + DYNAMIC_ARRAY_APPEND (*back_stack, i); + visited[i] = true; + } + } + } SWAP(front_stack, back_stack); + } + break; + + found: { + double path_flow = INFINITY; + for (size_t v = sink; v != source; v = parents[v]) { + size_t u = parents[v]; + DYNAMIC_ARRAY_APPEND (g->highlighted_edges, ((struct edge) {u, v})); + path_flow = fmin (path_flow, gsl_matrix_get (residual_capacity_matrix, + u, v)); + } + + for (size_t v = sink; v != source; v = parents[v]) { + size_t u = parents[v]; + *gsl_matrix_ptr (residual_capacity_matrix, u, v) -= path_flow; + *gsl_matrix_ptr (residual_capacity_matrix, v, u) += path_flow; + } + + max_flow += path_flow; + } + } + + gsl_matrix_free (residual_capacity_matrix); + + return max_flow; +} + +// https://tema.spbstu.ru/userfiles/files/courses/2019-theory_graph/TG9.pdf +double +min_cost_flow (GRAPH g, size_t s, size_t t, double required_flow) +{ + size_t n = g->vertex_count; + gsl_matrix *residual_capacity_matrix = gsl_matrix_alloc (n, n); + gsl_matrix_memcpy (residual_capacity_matrix, g->capacity_matrix); + gsl_matrix *residual_cost_matrix = gsl_matrix_alloc (n, n); + gsl_matrix_memcpy (residual_cost_matrix, g->weight_matrix); + gsl_matrix *result_flow_matrix = gsl_matrix_calloc (n, n); + double costs[MAX_VERTEX_COUNT]; + size_t parents[MAX_VERTEX_COUNT]; + double flow; + double min_cost; + + DYNAMIC_ARRAY_RESET (g->highlighted_edges); + while (flow < required_flow) { + // Bellman-Ford + for (size_t i = 0; i < n; ++i) { + costs[i] = INFINITY; + parents[i] = n; + } costs[s] = 0; + for (size_t i = 0; i < n - 1; ++i) { + for (size_t u = 0; u < n; ++u) { + for (size_t v = 0; v < n; ++v) { + if (!gsl_matrix_get (g->adjecency_matrix, u, v)) continue; + double cost = gsl_matrix_get (residual_cost_matrix, u, v); + if (costs[u] != INFINITY && + cost != INFINITY && + costs[u] + cost < costs[v]) { + costs[v] = costs[u] + cost; + parents[v] = u; + } + } + } + } + + // If no path + if (parents[t] == n) return NAN; + + // Find max flow + double path_flow = INFINITY; + for (size_t v = t; v != s; v = parents[v]) { + size_t u = parents[v]; + path_flow = fmin (path_flow, + gsl_matrix_get (residual_capacity_matrix, u, v)); + } + + // Apply flow constraint + path_flow = fmin (path_flow, required_flow - flow); + + // Update costs and capacities + for (int v = t; v != s; v = parents[v]) { + int u = parents[v]; + DYNAMIC_ARRAY_APPEND (g->highlighted_edges, ((struct edge) {u, v})); + *gsl_matrix_ptr (residual_capacity_matrix, u, v) -= path_flow; + *gsl_matrix_ptr (result_flow_matrix, u, v) += path_flow; + min_cost += path_flow*gsl_matrix_get (residual_cost_matrix, u, v); + + if (gsl_matrix_get (residual_capacity_matrix, u, v) == 0) + gsl_matrix_set (residual_cost_matrix, u, v, INFINITY); + } + + flow += path_flow; + } + + puts ("FLOW_MATRIX:"); + print_gsl_matrix (result_flow_matrix); + + gsl_matrix_free (residual_capacity_matrix); + gsl_matrix_free (residual_cost_matrix); + gsl_matrix_free (result_flow_matrix); + + return min_cost; +} + +size_t +count_spanning_trees (GRAPH g) +{ + size_t n = g->vertex_count; + gsl_matrix *kirchhoff_matrix = gsl_matrix_calloc (n, n); + + for (size_t i = 0; i < n; i++) { + for (size_t j = i; j < n; j++) { + if (gsl_matrix_get (g->adjecency_matrix, i, j) || + gsl_matrix_get (g->adjecency_matrix, j, i)) { + *gsl_matrix_ptr (kirchhoff_matrix, i, i) += 1; + *gsl_matrix_ptr (kirchhoff_matrix, j, j) += 1; + *gsl_matrix_ptr (kirchhoff_matrix, i, j) = -1; + *gsl_matrix_ptr (kirchhoff_matrix, j, i) = -1; + } + } + } + + printf ("KIRCHHOFF_MATRIX:\n"); + print_gsl_matrix (kirchhoff_matrix); + + size_t count = gsl_matrix_cofactor (kirchhoff_matrix, 0, 0); + gsl_matrix_free (kirchhoff_matrix); + + return count; +} + +// https://en.wikipedia.org/wiki/Prim%27s_algorithm +gsl_matrix * +min_weight_spannig_tree_prim (GRAPH g) +{ + size_t count = 0; + double total_weight = 0; + size_t n = g->vertex_count; + gsl_matrix *remaining_graph = gsl_matrix_alloc (n, n); + + for (size_t i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + double weight = gsl_matrix_get (g->weight_matrix, i, j); + gsl_matrix_set (remaining_graph, i, j, weight == 0 ? INFINITY : weight); + } + } + + gsl_matrix *spanning_tree = gsl_matrix_calloc (n, n); + bool visited[MAX_VERTEX_COUNT] = {0}; + size_t spanning_tree_vertex_count = 0; + while (spanning_tree_vertex_count < g->vertex_count) { + double minimum_weight = INFINITY; + size_t a; + size_t b; + for (size_t i = 0 ; i < n; ++i) { + for (size_t j = 0; j < n; ++j) { + count += 1; + double weight = gsl_matrix_get (remaining_graph, i, j); + if (weight < minimum_weight && + ((visited[i] != visited[j]) || + spanning_tree_vertex_count == 0)) { + minimum_weight = weight; + a = i; + b = j; + } + } + } + + if (!visited[a] || !visited[b]) { + if (!visited[a]) { + spanning_tree_vertex_count += 1; + visited[a] = true; + } + + if (!visited[b]) { + spanning_tree_vertex_count += 1; + visited[b] = true; + } + + total_weight += minimum_weight; + } + + gsl_matrix_set (remaining_graph, a, b, INFINITY); + gsl_matrix_set (remaining_graph, b, a, INFINITY); + gsl_matrix_set (spanning_tree, a, b, minimum_weight); + gsl_matrix_set (spanning_tree, b, a, minimum_weight); + printf ("%zu %zu = %f\n", a, b, minimum_weight); + } gsl_matrix_free (remaining_graph); + + printf ("MINIMUM_SPANNING_TREE_WEIGHTS:\n"); + print_gsl_matrix (spanning_tree); + printf ("TOTAL_WEIGHT: %.0lf\n", total_weight); + printf ("ITERATION_COUNT: %zu\n", count); + + return spanning_tree; +} + +// https://en.wikipedia.org/wiki/Bor%C5%AFvka's_algorithm +gsl_matrix * +min_weight_spannig_tree_boruvka (GRAPH g) +{ + size_t n = g->vertex_count; + gsl_matrix *spanning_tree = gsl_matrix_calloc (n, n); + + struct edge_weight { + size_t from; + size_t to; + double weight; + }; + + size_t number_of_components = g->vertex_count; + struct edge_weight lightest_edges[MAX_VERTEX_COUNT]; + size_t parent_components[MAX_VERTEX_COUNT]; + size_t next_components[MAX_VERTEX_COUNT]; + + for (size_t i = 0; i < n; ++i) + parent_components[i] = i; + + size_t count = 0; + double min_weight = 0; + while (number_of_components > 1) { + for (size_t i = 0; i < n; ++i) + lightest_edges[i] = (struct edge_weight) { 0, 0, .weight = INFINITY }; + + for (size_t u = 0; u < n; ++u) { + for (size_t v = 0; v < n; ++v) { + if (!gsl_matrix_get (g->adjecency_matrix, u, v)) continue; + count += 1; + double weight = + gsl_matrix_get (g->weight_matrix, u, v) + + gsl_matrix_get (g->weight_matrix, v, u); + + if (parent_components[u] != parent_components[v]) { + if (lightest_edges[parent_components[u]].weight > weight) { + lightest_edges[parent_components[u]].weight = weight; + lightest_edges[parent_components[u]].from = u; + lightest_edges[parent_components[u]].to = v; + } + if (lightest_edges[parent_components[v]].weight > weight) { + lightest_edges[parent_components[v]].weight = weight; + lightest_edges[parent_components[v]].from = u; + lightest_edges[parent_components[v]].to = v; + } + } + } + } + + // Adding selected edges and combining components + for (size_t i = 0; i < number_of_components; ++i) { + count++; + + double weight = lightest_edges[i].weight; + size_t u = lightest_edges[i].from; + size_t v = lightest_edges[i].to; + + if (weight == INFINITY) continue; + + if (!gsl_matrix_get (spanning_tree, u, v)) { + min_weight += weight; + gsl_matrix_set (spanning_tree, u, v, weight); + gsl_matrix_set (spanning_tree, v, u, weight); + } + + // Do the join + if (parent_components[u] != parent_components[v]) { + number_of_components -= 1; + size_t component_to_remove = parent_components[v]; + for (size_t j = 0; j < n; j++) { + if (parent_components[j] == component_to_remove) { + parent_components[j] = parent_components[u]; + } + } + } + } + } + + printf ("MINIMUM_SPANNING_TREE_WEIGHTS:\n"); + print_gsl_matrix (spanning_tree); + printf ("TOTAL_WEIGHT: %.0lf\n", min_weight); + printf ("ITERATION_COUNT: %zu\n", count); + + return spanning_tree; +} + +void +prufer_code (gsl_matrix *spanning_tree_matrix) +{ + size_t n = spanning_tree_matrix->size1; + + gsl_matrix *tree = gsl_matrix_alloc (n, n); + gsl_matrix_memcpy (tree, spanning_tree_matrix); + struct { + size_t *items; + size_t count; + size_t capacity; + } prufer = {0}; + struct { + size_t *items; + size_t count; + size_t capacity; + } weights = {0}; + + for (size_t i = 0; i < n - 1; ++i) { + // Find hanging vertex with the lowest number + size_t v, u; + for (size_t j = 0; j < n; ++j) { + size_t deg = 0; + for (size_t k = 0; k < n; ++k) { + if (gsl_matrix_get (tree, j, k) > 0) { + deg += 1; + u = k; + } + } + + if (deg == 1) { + v = j; + break; + } + } + + // Encode the only vertex neighbouring `v' + DYNAMIC_ARRAY_APPEND (prufer, u); + DYNAMIC_ARRAY_APPEND (weights, gsl_matrix_get (tree, u, v)); + + // "Pop" + gsl_matrix_set (tree, u, v, 0); + gsl_matrix_set (tree, v, u, 0); + } + + printf ("MINIMAL_SPANNING_TREE:\n"); + print_gsl_matrix (spanning_tree_matrix); + + printf ("PRUFER_CODE: "); + DYNAMIC_ARRAY_FOREACH (p, prufer) + printf ("%zu ", *p); + printf ("\n"); + + printf ("SAVED_WEIGHTS: "); + DYNAMIC_ARRAY_FOREACH (w, weights) + printf ("%zu ", *w); + printf ("\n"); + + // Decoding + gsl_matrix *decoded_tree = gsl_matrix_calloc (n, n); + + struct { + size_t *items; + size_t count; + size_t capacity; + } not_used_vertices = {0}; + for (size_t i = 0; i < n; ++i) + DYNAMIC_ARRAY_APPEND (not_used_vertices, i); + + for (size_t i = 0; i < n - 1; ++i) { + // Picking unused vertex v with the lowest number not in the rest + // of the Prufer code + size_t v; + for (size_t j = 0; j < not_used_vertices.count; ++j) { + bool met = false; + for (size_t k = i; k < n - 1; ++k) { + if (not_used_vertices.items[j] == prufer.items[k]) { + met = true; + break; + } + } + + if (!met) { + v = not_used_vertices.items[j]; + + // Remove now used + DYNAMIC_ARRAY_ERASE (not_used_vertices, j); + break; + } + } + + // Add edge + gsl_matrix_set (decoded_tree, v, prufer.items[i], weights.items[i]); + gsl_matrix_set (decoded_tree, prufer.items[i], v, weights.items[i]); + } + + printf ("DECODED_MINIMAL_SPANNING_TREE:\n"); + print_gsl_matrix (decoded_tree); + + for (size_t i = 0; i < n; ++i) { + for (size_t j = 0; j < n; ++j) { + if (gsl_matrix_get (spanning_tree_matrix, i, j) != + gsl_matrix_get (decoded_tree, i, j)) { + printf ("Error, matrices are not the same!\n"); + return; + } + } + } + printf("Success, matrices the same!\n"); + + gsl_matrix_free (tree); + gsl_matrix_free (decoded_tree); +} + +bool +is_graph_eulerian (GRAPH g) +{ + size_t n = g->vertex_count; + + if (n <= 2) + return false; + + // Check if degree of all vertices is even + for (size_t i = 0; i < n; ++i) { + size_t degree = 0; + for (size_t j = 0; j < n; ++j) { + if (gsl_matrix_get (g->adjecency_matrix, i, j) || + gsl_matrix_get (g->adjecency_matrix, j, i)) + degree += 1; + } + + if (degree % 2 != 0) + return false; + } + + return true; +} + +// https://tema.spbstu.ru/userfiles/files/courses/2019-theory_graph/TG12.pdf +// page 33 +bool +is_graph_hamiltonian (GRAPH g) +{ + size_t n = g->vertex_count; + + // Find neighbours + struct { + size_t *items; + size_t count; + size_t capacity; + } neighbours[MAX_VERTEX_COUNT] = {0}; + for (size_t i = 0; i < n; ++i) { + for (size_t j = 0; j < n; ++j) { + if (gsl_matrix_get (g->adjecency_matrix, i, j) || + gsl_matrix_get (g->adjecency_matrix, j, i)) { + DYNAMIC_ARRAY_APPEND (neighbours[i], j); + } + } + } + + struct { + size_t *items; + size_t count; + size_t capacity; + } not_visited_neighbours[MAX_VERTEX_COUNT] = {0}; + + struct { + size_t *items; + size_t count; + size_t capacity; + } path = {0}; + + size_t a = 0; + DYNAMIC_ARRAY_APPEND (path, a); + DYNAMIC_ARRAY_COPY_OTHER (not_visited_neighbours[a], neighbours[a]); + + while (path.count) { + size_t x = path.items[path.count - 1]; + + if (not_visited_neighbours[x].count) { + size_t y = not_visited_neighbours[x].items[not_visited_neighbours[x].count - 1]; + not_visited_neighbours[x].count -= 1; + + bool y_in_path = false; + DYNAMIC_ARRAY_FOREACH(p, path) { + if (*p == y) { + y_in_path = true; + break; + } + } + + if (!y_in_path) { + DYNAMIC_ARRAY_APPEND (path, y); + DYNAMIC_ARRAY_COPY_OTHER (not_visited_neighbours[y], neighbours[y]); + if (path.count == n && + (gsl_matrix_get (g->adjecency_matrix, a, y) || + gsl_matrix_get (g->adjecency_matrix, y, a))) { + return true; + } + } + } else { + path.count -= 1; // pop back + } + } + + return false; +} + +void +graph_ensure_eulerian (GRAPH g) +{ + size_t n = g->vertex_count; + + if (n <= 2) { + printf ("Not enough vertices for an Euler cycle (<3)\n"); + return; + } + + if (is_graph_eulerian (g)) { + printf ("Graph is Eulerian, no modifications needed\n"); + } else { + // Find vertices with odd degrees + struct { + size_t *items; + size_t count; + size_t capacity; + } odd_degree_vertices = {0}; + for (size_t i = 0; i < n; ++i) { + size_t degree = 0; + for (size_t j = 0; j < n; ++j) { + if (gsl_matrix_get (g->adjecency_matrix, i, j) || + gsl_matrix_get (g->adjecency_matrix, j, i)) + degree += 1; + } + if (degree % 2 != 0) + DYNAMIC_ARRAY_APPEND (odd_degree_vertices, i); + } + + size_t first; + + // Join vertices with odd degrees + add_edge: + if (odd_degree_vertices.count) + first = odd_degree_vertices.items[0]; + + // Find pair + for (size_t second_index = 1; second_index < odd_degree_vertices.count; ++second_index) { + size_t second = odd_degree_vertices.items[second_index]; + + // Help keep acyclic + size_t i = first < second ? first : second; + size_t j = first > second ? first : second; + + // Add edge if there isn't + if (gsl_matrix_get (g->adjecency_matrix, i, j) == 0 && + gsl_matrix_get (g->adjecency_matrix, j, i) == 0) { + double new_weight = floor (rand ()/(double) RAND_MAX*(MAX_WEIGHT - 1)) + 1; + double new_capacity = floor (rand ()/(double) RAND_MAX*(MAX_CAPACITY - 1)) + 1; + graph_edge_set (g, i, j, new_weight, new_capacity); + + printf ("Added edge: %zu -> %zu (%.0lf/%.0lf)\n", i, j, new_capacity, new_weight); + + // Update + DYNAMIC_ARRAY_ERASE (odd_degree_vertices, second_index); + DYNAMIC_ARRAY_ERASE (odd_degree_vertices, 0); + + goto add_edge; + } + } + + // If edge addition helped only partially, delete edges + remove_edge: + if (odd_degree_vertices.count) + first = odd_degree_vertices.items[0]; + + for (size_t second_index = 1; second_index < odd_degree_vertices.count; ++second_index) { + size_t second = odd_degree_vertices.items[second_index]; + + size_t i = first < second ? first : second; + size_t j = first > second ? first : second; + + // Don't delete edge if it will make graph unconnected + size_t degree_i = 0; + size_t degree_j = 0; + for (size_t k = 0; k < n; ++k) { + if (gsl_matrix_get (g->adjecency_matrix, i, k) || + gsl_matrix_get (g->adjecency_matrix, k, i)) + degree_i += 1; + if (gsl_matrix_get (g->adjecency_matrix, j, k) || + gsl_matrix_get (g->adjecency_matrix, k, j)) + degree_j += 1; + } + + if (degree_i == 1 && + degree_j == 1) + continue; + + gsl_matrix_set (g -> adjecency_matrix, i, j, 0); + gsl_matrix_set (g -> weight_matrix, i, j, 0); + gsl_matrix_set (g -> capacity_matrix, i, j, 0); + gsl_matrix_set (g -> adjecency_matrix, j, i, 0); + gsl_matrix_set (g -> weight_matrix, j, i, 0); + gsl_matrix_set (g -> capacity_matrix, j, i, 0); + + printf ("Removed edge: %zu -> %zu\n", i, j); + + // Update + DYNAMIC_ARRAY_ERASE (odd_degree_vertices, second_index); + DYNAMIC_ARRAY_ERASE (odd_degree_vertices, 0); + + goto remove_edge; + } + + if (odd_degree_vertices.count) + printf ("Unable to make graph Eulerian\n"); + + printf ("ADJECENCY_MATRIX:\n"); + print_gsl_matrix (g->adjecency_matrix); + } + + // Find Euler cycles + + // Find neighbours + struct { + size_t *items; + size_t count; + size_t capacity; + } neighbours[MAX_VERTEX_COUNT] = {0}; + for (size_t i = 0; i < n; ++i) { + for (size_t j = 0; j < n; ++j) { + if (gsl_matrix_get (g->adjecency_matrix, i, j) || + gsl_matrix_get (g->adjecency_matrix, j, i)) { + DYNAMIC_ARRAY_APPEND (neighbours[i], j); + } + } + } + + // https://tema.spbstu.ru/userfiles/files/courses/2019-theory_graph/TG12.pdf + // Page 27 + struct { + size_t *items; + size_t count; + size_t capacity; + } euler_cycle = {0}; + struct { + size_t *items; + size_t count; + size_t capacity; + } s = {0}; + DYNAMIC_ARRAY_APPEND (s, 0); + + while (s.count) { + size_t v = s.items[s.count - 1]; + + if (!neighbours[v].count) { + s.count -= 1; + DYNAMIC_ARRAY_APPEND (euler_cycle, v); + } else { + size_t u = neighbours[v].items[0]; + DYNAMIC_ARRAY_APPEND (s, u); + + // Removing + DYNAMIC_ARRAY_ERASE (neighbours[v], 0); + for (size_t i = 0; i < neighbours[u].count; ++i) { + if (neighbours[u].items[i] == v) { + DYNAMIC_ARRAY_ERASE (neighbours[u], i); + i -= 1; + } + } + } + } + + printf ("EULER_CYCLE: "); + DYNAMIC_ARRAY_FOREACH (vertex, euler_cycle) { + if (vertex != euler_cycle.items) + printf (" -> "); + printf ("%zu", *vertex); + } printf ("\n"); + DYNAMIC_ARRAY_APPEND (euler_cycle, n); + free (g->highlighted_path); + g->highlighted_path = euler_cycle.items; + + for (size_t i = 0; i < MAX_VERTEX_COUNT; ++i) + DYNAMIC_ARRAY_FREE (neighbours[i]); + DYNAMIC_ARRAY_FREE (s); + // DYNAMIC_ARRAY_FREE (euler_cycle); +} + +void +graph_ensure_hamiltonian (GRAPH g) +{ + size_t n = g->vertex_count; + + if (n <= 2) { + printf ("Not enough vertices for an Hamilton cycle (<3)\n"); + return; + } + + if (is_graph_hamiltonian (g)) { + printf ("Graph is Hamiltonian, no modifications needed\n"); + } else { + struct { + struct vertex_degree { + size_t vertex; + size_t degree; + } *items; + size_t count; + size_t capacity; + } vertex_degree_pairs = {0}; + for (size_t i = 0; i < n; ++i) { + size_t degree = 0; + for (size_t j = 0; j < n; ++j) { + if (gsl_matrix_get (g->adjecency_matrix, i, j) || + gsl_matrix_get (g->adjecency_matrix, j, i)) + degree += 1; + } + + DYNAMIC_ARRAY_APPEND (vertex_degree_pairs, ((struct vertex_degree) {i, degree})); + } + + // Add edges to vertices with low degree + do { + size_t min_idx = 0; + for (size_t i = 1; i < n; ++i) { + if (vertex_degree_pairs.items[i].degree < + vertex_degree_pairs.items[min_idx].degree) + min_idx = i; + } + + size_t vertex1 = vertex_degree_pairs.items[min_idx].vertex; + size_t degree1 = vertex_degree_pairs.items[min_idx].degree; + DYNAMIC_ARRAY_ERASE (vertex_degree_pairs, min_idx); + + for (size_t k = 0; k < n; ++k) { + size_t min_idx = 0; + for (size_t i = 1; i < n; ++i) { + if (vertex_degree_pairs.items[min_idx].vertex != vertex1 && + vertex_degree_pairs.items[i].degree < + vertex_degree_pairs.items[min_idx].degree) + min_idx = i; + } + size_t vertex2 = vertex_degree_pairs.items[min_idx].vertex; + size_t degree2 = vertex_degree_pairs.items[min_idx].degree; + + if (!gsl_matrix_get (g->adjecency_matrix, vertex1, vertex2) && + !gsl_matrix_get (g->adjecency_matrix, vertex2, vertex1)) { + size_t i = vertex1 < vertex2 ? vertex1 : vertex2; + size_t j = vertex1 > vertex2 ? vertex1 : vertex2; + + double new_weight = floor (rand ()/(double) RAND_MAX*(MAX_WEIGHT - 1)) + 1; + double new_capacity = floor (rand ()/(double) RAND_MAX*(MAX_CAPACITY - 1)) + 1; + graph_edge_set (g, i, j, new_weight, new_capacity); + + printf ("Added edge: %zu -> %zu (%.0lf/%.0lf)\n", i, j, new_capacity, new_weight); + + DYNAMIC_ARRAY_ERASE (vertex_degree_pairs, min_idx); + DYNAMIC_ARRAY_APPEND (vertex_degree_pairs, ((struct vertex_degree) {vertex2, degree2 + 1})); + break; + } + } + + DYNAMIC_ARRAY_APPEND (vertex_degree_pairs, ((struct vertex_degree) {vertex1, degree1 + 1})); + } while (!is_graph_hamiltonian(g)); + } + + find_hamiltonian_cycles (g); +} + +struct path { + size_t *items; + size_t count; + size_t capacity; +} typedef *PATH; + +void +find_hamiltonian_recursive (GRAPH g, FILE *fd, size_t *cycle_count, + size_t start, PATH path, + double path_weight, PATH min_path, + double *min_path_weight) +{ + if (*cycle_count >= 1000000) + return; + + // Path is built + if (path->count == g->vertex_count) { + size_t last = path->items[path->count - 1]; + if (gsl_matrix_get (g->adjecency_matrix, last, start) || + gsl_matrix_get (g->adjecency_matrix, start, last)) { + *cycle_count += 1; + + path_weight += + gsl_matrix_get (g->weight_matrix, start, last) + + gsl_matrix_get (g->weight_matrix, last, start); + DYNAMIC_ARRAY_APPEND (*path, start); + if (*min_path_weight > path_weight) { + DYNAMIC_ARRAY_COPY_OTHER (*min_path, *path); + *min_path_weight = path_weight; + } + + for (size_t i = 0; i < path->count; ++i) + fprintf (fd, "%zu ", path->items[i]); + fprintf (fd, "@ %.0lf\n", path_weight); + path->count -= 1; + } + return; + } + + // Continue building + for (size_t i = 0; i < g->vertex_count; ++i) { + size_t last = path->items[path->count - 1]; + if (!gsl_matrix_get (g->adjecency_matrix, last, i) && + !gsl_matrix_get (g->adjecency_matrix, i, last)) + continue; + + bool used = false; + DYNAMIC_ARRAY_FOREACH (v, *path) { + if (*v == i) { + used = true; + break; + } + } if (used) continue; + + double new_weight = path_weight + + gsl_matrix_get (g->weight_matrix, last, i) + + gsl_matrix_get (g->weight_matrix, i, last); + DYNAMIC_ARRAY_APPEND (*path, i); + find_hamiltonian_recursive (g, fd, cycle_count, start, path, new_weight, min_path, min_path_weight); + path->count -= 1; + } +} + +void +find_hamiltonian_cycles (GRAPH g) +{ + const char *filename = "hamiltonian-cycles.txt"; + + if (g->vertex_count > 20) { + printf ("Graph is too large (>20v), iterative algorithm will take too long\n"); + return; + } + + FILE *fd = fopen (filename, "w+"); + + + struct path path = {0}; + struct path min_path = {0}; + size_t cycle_count = 0; + double min_path_weight = INFINITY; + for (size_t i = 0; i < g->vertex_count; ++i) { + DYNAMIC_ARRAY_RESET (path); + DYNAMIC_ARRAY_APPEND (path, i); + find_hamiltonian_recursive (g, fd, &cycle_count, i, &path, 0, &min_path, &min_path_weight); + } + + fclose (fd); + + printf ("CYCLES_TOTAL: %zu\n", cycle_count); + printf ("All cycles are saved here: %s\n", filename); + printf ("Cycle with minimum weight (%.0lf): ", min_path_weight); + DYNAMIC_ARRAY_FOREACH (vertex, min_path) { + if (vertex != min_path.items) + printf (" -> "); + printf ("%zu", *vertex); + } printf ("\n"); + DYNAMIC_ARRAY_APPEND (min_path, g->vertex_count); + free (g->highlighted_path); + g->highlighted_path = min_path.items; + + + DYNAMIC_ARRAY_FREE (path); +} diff --git a/src/graph.h b/src/graph.h new file mode 100644 index 0000000..f55e975 --- /dev/null +++ b/src/graph.h @@ -0,0 +1,71 @@ +#ifndef INCLUDED_GRAPH_H +#define INCLUDED_GRAPH_H + +#include +#include +#include +#include +#include "distribution.h" + +enum graph_type { + GRAPH_TYPE_NONE, + GRAPH_TYPE_POSITIVE = 1 << 0, + GRAPH_TYPE_NEGATIVE = 1 << 1, + GRAPH_TYPE_POSITIVE_NEGATIVE = GRAPH_TYPE_POSITIVE | GRAPH_TYPE_NEGATIVE, +}; + +struct edge { + size_t from; + size_t to; +}; + +struct edges { + struct edge *items; + size_t count; + size_t capacity; +}; + +typedef struct graph { + enum graph_type type; + size_t vertex_count; + gsl_matrix *adjecency_matrix; + gsl_matrix *weight_matrix; + gsl_matrix *capacity_matrix; + size_t *highlighted_path; + struct edges highlighted_edges; +} *GRAPH; + +void generate_graph (GRAPH, DISTRIBUTION, + size_t vertex_count, enum graph_type); +void graph_unhighlight (GRAPH g); +void graph_edge_set (GRAPH, size_t from, size_t to, + double weight, double capacity); +void print_graph (GRAPH); +void highlight_graph (GRAPH, const gsl_matrix *); + +// lab 1 +gsl_matrix *shimbell_method (GRAPH, size_t edge_count, bool max); +size_t graph_count_routes (GRAPH, size_t from, size_t to); + +// lab 2 +size_t *dijkstra_positive (GRAPH, size_t from, size_t to, bool max); +size_t *floyd_warshall (GRAPH, size_t from, size_t to, bool max); + +// lab 3 +double max_flow_ford_fulkerson (GRAPH, size_t from, size_t to); +double min_cost_flow (GRAPH, size_t from, size_t to, double required_flow); + +// lab 4 +size_t count_spanning_trees (GRAPH); +gsl_matrix *min_weight_spannig_tree_prim (GRAPH); +gsl_matrix *min_weight_spannig_tree_boruvka (GRAPH); +void prufer_code (gsl_matrix *); + +// lab 5 +bool is_graph_eulerian (GRAPH); +bool is_graph_hamiltonian (GRAPH); +void graph_ensure_eulerian (GRAPH); +void graph_ensure_hamiltonian (GRAPH); +void find_hamiltonian_cycles (GRAPH); + +#endif diff --git a/src/main.c b/src/main.c new file mode 100644 index 0000000..d297e72 --- /dev/null +++ b/src/main.c @@ -0,0 +1,580 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "config.h" +#include "utils.h" +#include "distribution.h" +#include "graph.h" +#include "dynamic-array.h" + +#define BUTTONS(X, ...) \ + X(__VA_ARGS__, EDIT, "Edit edge" ) \ + X(__VA_ARGS__, NEW_POSITIVE, "New graph+" ) \ + X(__VA_ARGS__, NEW_POSITIVE_NEGATIVE, "New graph±" ) \ + X(__VA_ARGS__, ROUTE_COUNT, "Route count" ) \ + X(__VA_ARGS__, SHIMBELL_MIN, "Min Shimbell" ) \ + X(__VA_ARGS__, SHIMBELL_MAX, "Max Shimbell" ) \ + X(__VA_ARGS__, DIJKSTRA_POSITIVE_MIN, "Min Dijkstra+" ) \ + X(__VA_ARGS__, DIJKSTRA_POSITIVE_MAX, "Max Dijkstra+" ) \ + X(__VA_ARGS__, FLOYD_WARSHALL_MIN, "Min Floyd-Warshall" ) \ + X(__VA_ARGS__, FLOYD_WARSHALL_MAX, "Max Floyd-Warshall" ) \ + X(__VA_ARGS__, MAX_FLOW_FORD_FULKERSON, "Max flow Ford-Fulkerson" ) \ + X(__VA_ARGS__, MIN_COST_FLOW, "Min cost flow" ) \ + X(__VA_ARGS__, COUNT_SPANNING_TREES, "Count spanning trees" ) \ + X(__VA_ARGS__, MIN_WEIGHT_SPANNIG_TREE_PRIM, "Min weight spanning tree Prim" ) \ + X(__VA_ARGS__, MIN_WEIGHT_SPANNIG_TREE_BORUVKA, "Min weight spanning tree Borůvka") \ + X(__VA_ARGS__, ENSURE_EULERIAN, "Ensure Eulerian" ) \ + X(__VA_ARGS__, ENSURE_HAMILTONIAN, "Ensure Hamiltonian" ) \ + +#define ENUM_ENTRY(PREFIX, SYMBOL, ...) PREFIX##_##SYMBOL, +#define ENUM_ENTRY_VALUE(PREFIX, SYMBOL, VALUE, ...) [PREFIX##_##SYMBOL] = VALUE, + +enum { + BUTTONS(ENUM_ENTRY, BUTTON) + BUTTON_COUNT +} button; +#define BUTTON_NONE BUTTON_COUNT + +static const char *button_labels[] = { + BUTTONS(ENUM_ENTRY_VALUE, BUTTON) +}; + +static Font font; +static Rectangle button_recs[BUTTON_COUNT]; +static int button_hover = BUTTON_NONE; +static bool button_pressed = false; +static double start_time; +static Vector2 *model_vertices = NULL; +static struct distribution dist = {0}; +static struct graph g = {0}; +static gsl_matrix *saved_adjecency_matrix = NULL; +static gsl_matrix *saved_weight_matrix = NULL; +static gsl_matrix *saved_capacity_matrix = NULL; + +void +new_graph (size_t vertex_count, enum graph_type type) +{ + distribution_init (&dist, DIST_N*vertex_count, DIST_B, DIST_R, DIST_C); + generate_graph (&g, &dist, vertex_count, type); + print_graph (&g); + start_time = GetTime (); + + // Initialize vertex positions in a circle + model_vertices = realloc (model_vertices, vertex_count*(sizeof *model_vertices)); + for (size_t i = 0; i < vertex_count; ++i) { + model_vertices[i].x = cosf (PI + 2*PI*i/(float)vertex_count); + model_vertices[i].y = sinf (PI + 2*PI*i/(float)vertex_count); + } + + // Print graph in dot format + // puts ("digraph G {"); + // for (int i = 0; i < vertex_count; i++) { + // for (int j = 0; j < vertex_count; j++) { + // if (gsl_matrix_get (m, i, j) == 0) + // continue; + // printf (" %d -> %d [label=\"%g\"]\n", i, j, gsl_matrix_get (m, i, j)); + // } + // } puts ("}"); +} + +void +startup (void) +{ + SetConfigFlags (FLAG_MSAA_4X_HINT | + FLAG_WINDOW_RESIZABLE | + FLAG_VSYNC_HINT | + FLAG_WINDOW_UNDECORATED); + InitWindow (INITIAL_SCREEN_WIDTH, INITIAL_SCREEN_HEIGHT, WINDOW_TITLE); + SetTargetFPS (60); + + const int codepoints_count = 96 + 256 + 2; + int codepoints[codepoints_count]; + for (int i = 0; i < 95; i++) codepoints[ 0 + i] = 0x0020 + i; + for (int i = 0; i < 255; i++) codepoints[96 + i] = 0x0400 + i; + codepoints[codepoints_count - 2] = 0x16f; + codepoints[codepoints_count - 1] = 0x0b1; + + font = LoadFontEx ("./res/iosevka-term-slab-regular.ttf", FONT_SIZE, codepoints, codepoints_count); + SetTextureFilter (font.texture, TEXTURE_FILTER_ANISOTROPIC_16X); + + // srand (time (NULL)); + srand (4); + + // Initialize buttons + for (int i = 0; i < BUTTON_COUNT; ++i) { + Rectangle rec = { + .x = PADDING, + .y = PADDING + i*(BUTTON_HEIGHT + PADDING), + .width = BUTTON_WIDTH, + .height = BUTTON_HEIGHT, + }; + button_recs[i] = rec; + } + + start_time = GetTime (); + + new_graph (INITIAL_VERTEX_COUNT, GRAPH_TYPE_POSITIVE); +} + +static inline size_t +read_vertex (char *label) +{ + size_t v; + for (;;) { + prompt (label, "%zu", &v); + if (v >= g.vertex_count) { + printf ("ERROR: Vertex out of range [0; %zu)!\n", g.vertex_count); + } else return v; + } +} + +static inline size_t +read_vertex_count (void) +{ + size_t vertex_count; + for (;;) { + prompt ("VERTEX_COUNT", "%zu", &vertex_count); + if (vertex_count > MAX_VERTEX_COUNT) { + printf ("ERROR: Vertex count cannot be larger than %zu!\n", MAX_VERTEX_COUNT); + } else return vertex_count; + } +} + +static inline void +handle_buttons (void) +{ + button_hover = BUTTON_NONE; + button_pressed = false; + for (int i = 0; i < BUTTON_COUNT; ++i) { + if (CheckCollisionPointRec (GetMousePosition (), button_recs[i])) { + button_hover = i; + if (IsMouseButtonReleased (MOUSE_BUTTON_LEFT)) + button_pressed = true; + break; + } + } + if (button_pressed) { + if (button_hover != BUTTON_NONE) { + graph_unhighlight (&g); + if (saved_adjecency_matrix) { + gsl_matrix_free (g.adjecency_matrix); + g.adjecency_matrix = saved_adjecency_matrix; + saved_adjecency_matrix = NULL; + start_time = GetTime (); + } + if (saved_weight_matrix) { + gsl_matrix_free (g.weight_matrix); + g.weight_matrix = saved_weight_matrix; + saved_weight_matrix = NULL; + } + if (saved_capacity_matrix) { + gsl_matrix_free (g.capacity_matrix); + g.capacity_matrix = saved_capacity_matrix; + saved_capacity_matrix = NULL; + } + } + switch (button_hover) { + case BUTTON_EDIT: { + size_t from = read_vertex ("FROM"); + size_t to = read_vertex ("TO"); + if (to == from) { + printf("ERROR: Self-loops are not allowed!\n"); + break; + } + + double weight; + for (;;) { + prompt ("WEIGHT", "%lf", &weight); + if (weight > MAX_WEIGHT) { + printf ("ERROR: Weight cannot be larger than %lf!\n", MAX_WEIGHT); + } else if (g.type == GRAPH_TYPE_POSITIVE && weight < 0) { + printf ("ERROR: Weight cannot be negative in a positive graph!\n"); + } else if (g.type == GRAPH_TYPE_POSITIVE_NEGATIVE && weight < -MAX_WEIGHT) { + printf ("ERROR: Weight cannot be less than %lf!\n", -MAX_WEIGHT); + } else break; + } + + double capacity; + for (;;) { + prompt ("CAPACITY", "%lf", &capacity); + if (weight > MAX_WEIGHT) { + printf ("ERROR: Capacity cannot be larger than %lf!\n", MAX_CAPACITY); + } else break; + } + + graph_unhighlight (&g); + graph_edge_set (&g, from, to, weight, capacity); + print_graph (&g); + } break; + + case BUTTON_NEW_POSITIVE: { + new_graph (read_vertex_count (), GRAPH_TYPE_POSITIVE); + } break; + + case BUTTON_NEW_POSITIVE_NEGATIVE: { + new_graph (read_vertex_count (), GRAPH_TYPE_POSITIVE_NEGATIVE); + } break; + + case BUTTON_ROUTE_COUNT: { + size_t from = read_vertex ("FROM"); + size_t to = read_vertex ("TO"); + size_t routes = graph_count_routes (&g, from, to); + if (routes) printf ("ROUTE COUNT FROM %zu TO %zu: %zu\n", from, to, routes); + else printf ("NO ROUTES FROM %zu TO %zu\n", from, to); + } break; + + case BUTTON_SHIMBELL_MIN: { + int edge_count = 0; + do { + printf ("SHIMBELL METHOD EDGE COUNT: "); + scanf ("%d", &edge_count); + while (getchar () != '\n'); + } while (!edge_count); + gsl_matrix *sh = shimbell_method (&g, edge_count, false); + puts ("PATH MATRIX:"); + print_gsl_matrix (sh); + gsl_matrix_free (sh); + } break; + + case BUTTON_SHIMBELL_MAX: { + int edge_count = 0; + do { + printf ("SHIMBELL METHOD EDGE COUNT: "); + scanf ("%d", &edge_count); + while (getchar () != '\n'); + } while (!edge_count); + gsl_matrix *sh = shimbell_method (&g, edge_count, true); + puts ("PATH MATRIX:"); + print_gsl_matrix (sh); + gsl_matrix_free (sh); + } break; + + case BUTTON_DIJKSTRA_POSITIVE_MIN: { + size_t from = read_vertex ("FROM"); + size_t to = read_vertex ("TO"); + g.highlighted_path = dijkstra_positive (&g, from, to, false); + } break; + + case BUTTON_DIJKSTRA_POSITIVE_MAX: { + size_t from = read_vertex ("FROM"); + size_t to = read_vertex ("TO"); + g.highlighted_path = dijkstra_positive (&g, from, to, true); + } break; + + case BUTTON_FLOYD_WARSHALL_MIN: { + size_t from = read_vertex ("FROM"); + size_t to = read_vertex ("TO"); + g.highlighted_path = floyd_warshall (&g, from, to, false); + } break; + + case BUTTON_FLOYD_WARSHALL_MAX: { + size_t from = read_vertex ("FROM"); + size_t to = read_vertex ("TO"); + g.highlighted_path = floyd_warshall (&g, from, to, true); + } break; + + case BUTTON_MAX_FLOW_FORD_FULKERSON: { + size_t from = read_vertex ("FROM"); + size_t to = read_vertex ("TO"); + double max_flow = max_flow_ford_fulkerson (&g, from, to); + printf ("MAX_FLOW: %.0lf\n", max_flow); + } break; + + case BUTTON_MIN_COST_FLOW: { + size_t from = read_vertex ("FROM"); + size_t to = read_vertex ("TO"); + double max_flow = max_flow_ford_fulkerson(&g, from, to); + if (max_flow == 0) { + printf ("NO PATH FROM %zu TO %zu\n", from, to); + break; + } + double required_flow = floor (max_flow*2/3); + printf ("REQUIRED_FLOW: [%.0lf*2/3] = %.0lf\n", max_flow, required_flow); + + double min_cost = min_cost_flow (&g, from, to, required_flow); + printf ("MIN_COST: %.0lf\n", min_cost); + } break; + + case BUTTON_COUNT_SPANNING_TREES: { + double spannig_tree_count = count_spanning_trees (&g); + printf ("SPANNING TREE COUNT %.0lf\n", spannig_tree_count); + } break; + + case BUTTON_MIN_WEIGHT_SPANNIG_TREE_PRIM: { + gsl_matrix *minimal_spanning_tree = min_weight_spannig_tree_prim (&g); + prufer_code (minimal_spanning_tree); + highlight_graph (&g, minimal_spanning_tree); + gsl_matrix_free (minimal_spanning_tree); + } break; + + case BUTTON_MIN_WEIGHT_SPANNIG_TREE_BORUVKA: { + gsl_matrix *minimal_spanning_tree = min_weight_spannig_tree_boruvka (&g); + prufer_code (minimal_spanning_tree); + highlight_graph (&g, minimal_spanning_tree); + gsl_matrix_free (minimal_spanning_tree); + } break; + + case BUTTON_ENSURE_EULERIAN: { + saved_adjecency_matrix = gsl_matrix_alloc (g.vertex_count, g.vertex_count); + gsl_matrix_memcpy (saved_adjecency_matrix, g.adjecency_matrix); + saved_weight_matrix = gsl_matrix_alloc (g.vertex_count, g.vertex_count); + gsl_matrix_memcpy (saved_weight_matrix, g.weight_matrix); + saved_capacity_matrix = gsl_matrix_alloc (g.vertex_count, g.vertex_count); + gsl_matrix_memcpy (saved_capacity_matrix, g.capacity_matrix); + graph_ensure_eulerian (&g); + start_time = GetTime (); + } break; + + case BUTTON_ENSURE_HAMILTONIAN: { + saved_adjecency_matrix = gsl_matrix_alloc (g.vertex_count, g.vertex_count); + gsl_matrix_memcpy (saved_adjecency_matrix, g.adjecency_matrix); + saved_weight_matrix = gsl_matrix_alloc (g.vertex_count, g.vertex_count); + gsl_matrix_memcpy (saved_weight_matrix, g.weight_matrix); + saved_capacity_matrix = gsl_matrix_alloc (g.vertex_count, g.vertex_count); + gsl_matrix_memcpy (saved_capacity_matrix, g.capacity_matrix); + graph_ensure_hamiltonian (&g); + start_time = GetTime (); + } break; + default: break; + } + } +} + +static inline void +draw_buttons (void) +{ + for (int i = 0; i < BUTTON_COUNT; i++) { + DrawRectangleRec (button_recs[i], i == button_hover ? BUTTON_HOVER_COLOR + : BUTTON_COLOR); + DrawRectangleLinesEx (button_recs[i], 2, i == button_hover ? BUTTON_HOVER_OUTLINE_COLOR + : BUTTON_OUTLINE_COLOR); + Vector2 text_center = Vector2Scale ( + MeasureTextEx (font, button_labels[i], + FONT_SIZE, TEXT_SPACING), + 0.5); + Vector2 rect_center = { + .x = button_recs[i].x + button_recs[i].width/2, + .y = button_recs[i].y + button_recs[i].height/2 + 1, + }; + DrawTextEx (font, button_labels[i], Vector2Subtract (rect_center, + text_center), + FONT_SIZE, TEXT_SPACING, i == button_hover ? BUTTON_TEXT_HOVER_COLOR + : BUTTON_TEXT_COLOR); + } +} + +static inline void +progress_model (void) +{ + size_t n = g.vertex_count; + Vector2 force_on_vertices[MAX_VERTEX_COUNT] = {0}; + for (size_t i = 0; i < n; ++i) { + for (size_t j = 0; j < n; ++j) { + if (i == j) + continue; + Vector2 dir = Vector2Normalize (Vector2Subtract (model_vertices[j], + model_vertices[i])); + if (gsl_matrix_get (g.adjecency_matrix, i, j) || + gsl_matrix_get (g.adjecency_matrix, j, i)) { + float distance = Vector2Distance (model_vertices[i], + model_vertices[j]); + float mag = MODEL_C_SPRING*logf (distance/MODEL_L); + force_on_vertices[i] = Vector2Add (force_on_vertices[i], + Vector2Scale (dir, mag)); + } else { + float square_distance = Vector2DistanceSqr (model_vertices[j], + model_vertices[i]); + float mag = MODEL_C_REP/square_distance; + force_on_vertices[i] = Vector2Add (force_on_vertices[i], + Vector2Scale (dir, -mag)); + } + } + } + + float heat = exp ((-1 + MODEL_COOLING_FACTOR)*(GetTime () - start_time))/100; + for (int i = 0; i < n; ++i) { + model_vertices[i] = Vector2Add (model_vertices[i], + Vector2Scale (force_on_vertices[i], heat)); + } +} + +void +draw_edges (Vector2 *vertex_screen_positions) +{ + size_t n = g.vertex_count; + for (size_t i = 0; i < n; ++i) { + for (size_t j = 0; j < n; ++j) { + if (!gsl_matrix_get (g.adjecency_matrix, i, j)) continue; + double capacity = gsl_matrix_get ( + g.capacity_matrix, i, j); + float line_thickness = Remap (capacity, 0, MAX_CAPACITY, 4, 8); + float arrow_side = 3*line_thickness; + float arrow_height = arrow_side*sqrt (3)/2; + + Vector2 dir = Vector2Normalize (Vector2Subtract ( + vertex_screen_positions[j], + vertex_screen_positions[i])); + + Vector2 line_offset = Vector2Scale (dir, 1.5*VERTEX_RADIUS); + Vector2 line_begin = Vector2Add (vertex_screen_positions[i], + line_offset); + Vector2 line_end = Vector2Subtract ( + Vector2Subtract (vertex_screen_positions[j], line_offset), + Vector2Scale (dir, arrow_height)); + + double weight = gsl_matrix_get (g.weight_matrix, i, j); + float brightness = Remap (Normalize (fabs (weight), 0, MAX_WEIGHT), + 0, 1, 0.25, 0.75); + Color line_color = ColorBrightness (BLACK, 1 - brightness); + if (g.type == GRAPH_TYPE_POSITIVE_NEGATIVE) { + if (weight < 0) { + line_color.b = 255/6; + line_color.g = 255/6; + } else { + line_color.r = 255/6; + line_color.b = 255/6; + } + } + if (g.highlighted_path) { + for (size_t v = 0; g.highlighted_path[v] != n; ++v) { + if (g.highlighted_path[v + 0] == i && + g.highlighted_path[v + 1] == j || + g.highlighted_path[v + 0] == j && + g.highlighted_path[v + 1] == i) { + if (g.type == GRAPH_TYPE_POSITIVE_NEGATIVE) { + line_color = weight < 0 ? (Color) { 0xff, 0x00, 0x00, 0xff } + : (Color) { 0x00, 0xff, 0x00, 0xff }; + } else { + line_color = VERTEX_OUTLINE_HIGHLIGHTED_COLOR; + } break; + } + } + } else if (g.highlighted_edges.count) { + for (size_t v = 0; v < g.highlighted_edges.count; ++v) { + if (g.highlighted_edges.items[v].from == i && + g.highlighted_edges.items[v].to == j) { + if (g.type == GRAPH_TYPE_POSITIVE_NEGATIVE) { + line_color = weight < 0 ? (Color) { 0xff, 0x00, 0x00, 0xff } + : (Color) { 0x00, 0xff, 0x00, 0xff }; + } else { + line_color = VERTEX_OUTLINE_HIGHLIGHTED_COLOR; + } break; + } + } + } + + const Vector2 side = Vector2Scale (dir, -arrow_side/2); + DrawLineEx (line_begin, line_end, line_thickness, line_color); + DrawTriangle ( + Vector2Add (line_end, Vector2Scale (dir, arrow_height)), + Vector2Add (line_end, Vector2Rotate (side, PI/2)), + Vector2Add (line_end, Vector2Rotate (side, -PI/2)), + line_color); + + char *anot; + asprintf (&anot, "%.0lf/%.0lf", capacity, weight); + Vector2 center = Vector2Scale ( + MeasureTextEx (font, anot, FONT_SIZE, TEXT_SPACING), 0.5); + Vector2 midpoint = Vector2Lerp(line_begin, line_end, 0.5); + Rectangle bounding_box = { + .x = midpoint.x - center.x - 4, + .y = midpoint.y - center.y, + .width = 2*(center.x + 4), + .height = 2*center.y, + }; + DrawRectangleRounded(bounding_box, 0.5, 16, ColorAlpha (BACKGROUND_COLOR, 0.75)); + DrawTextEx (font, anot, + Vector2Subtract (midpoint, center), + FONT_SIZE, TEXT_SPACING, EDGE_TEXT_COLOR); + free (anot); + } + } +} + +void +draw_vertices (Vector2 *vertex_screen_positions) +{ + for (size_t i = 0; i < g.vertex_count; ++i) { + Color outline_color = VERTEX_OUTLINE_COLOR; + + if (g.highlighted_path) { + for (size_t v = 0; g.highlighted_path[v] != g.vertex_count; ++v) { + if (g.highlighted_path[v] == i) + outline_color = VERTEX_OUTLINE_HIGHLIGHTED_COLOR; + } + } else if (g.highlighted_edges.count) { + for (size_t v = 0; v < g.highlighted_edges.count; ++v) { + if (g.highlighted_edges.items[v].from == i || + g.highlighted_edges.items[v].to == i) { + outline_color = VERTEX_OUTLINE_HIGHLIGHTED_COLOR; + } + } + } + + DrawCircleV (vertex_screen_positions[i], 1.2*VERTEX_RADIUS, outline_color); + DrawCircleV (vertex_screen_positions[i], VERTEX_RADIUS, VERTEX_COLOR); + char *anot; + asprintf (&anot, "%zu", i); + Vector2 center = Vector2Scale ( + MeasureTextEx (font, anot, FONT_SIZE, TEXT_SPACING), + 0.5); + DrawTextEx (font, anot, + Vector2Subtract (vertex_screen_positions[i], center), + FONT_SIZE, TEXT_SPACING, VERTEX_TEXT_COLOR); + free (anot); + } +} + +int +main (void) +{ + startup (); + while (!WindowShouldClose ()) { + if (IsKeyDown (KEY_SPACE)) + start_time = GetTime (); + handle_buttons (); + progress_model (); + + // Find model space position supremums + Vector2 pos_max = { -INFINITY, -INFINITY }; + Vector2 pos_min = { INFINITY, INFINITY }; + for (size_t i = 0; i < g.vertex_count; ++i) { + if (model_vertices[i].x > pos_max.x) pos_max.x = model_vertices[i].x; + if (model_vertices[i].y > pos_max.y) pos_max.y = model_vertices[i].y; + if (model_vertices[i].x < pos_min.x) pos_min.x = model_vertices[i].x; + if (model_vertices[i].y < pos_min.y) pos_min.y = model_vertices[i].y; + } + + // Remap model space positions to screen space + Vector2 vertex_screen_positions[g.vertex_count]; + for (size_t i = 0; i < g.vertex_count; ++i) { + vertex_screen_positions[i] = (Vector2) { + .x = Remap (model_vertices[i].x, pos_min.x, pos_max.x, 2*VERTEX_RADIUS + BUTTON_WIDTH + PADDING, GetScreenWidth () - 2*VERTEX_RADIUS), + .y = Remap (model_vertices[i].y, pos_min.y, pos_max.y, 2*VERTEX_RADIUS, GetScreenHeight () - 2*VERTEX_RADIUS), + }; + } + + BeginDrawing (); + ClearBackground (BACKGROUND_COLOR); + draw_buttons (); + draw_edges (vertex_screen_positions); + draw_vertices (vertex_screen_positions); + // DrawFPS (2, 0); + EndDrawing (); + } CloseWindow (); + + return EXIT_SUCCESS; +} diff --git a/src/utils.c b/src/utils.c new file mode 100644 index 0000000..d96c3b6 --- /dev/null +++ b/src/utils.c @@ -0,0 +1,108 @@ +#include "utils.h" +#include + +void +print_gsl_matrix (const gsl_matrix *m) +{ + int pad = 2; + + for (size_t i = 0; i < log10sz (m->size1) + 3; i++) + putchar (' '); + for (size_t j = 0; j < m->size2; j++) + printf ("[%0*zu]", log10sz (m->size2) + 1 + pad, j); + putchar ('\n'); + for (size_t i = 0; i < m->size1; i++) { + printf ("[%0*zu]", log10sz (m->size1) + 1, i); + for (size_t j = 0; j < m->size2; j++) + printf (" %*.0f ", log10sz (m->size2) + 1 + pad, gsl_matrix_get (m, i, j)); + putchar ('\n'); + } +} + +void +prompt (char *label, char *fmt, void *where) +{ + printf ("%s: ", label); + scanf (fmt, where); + while (getchar () != '\n'); +} + +int +log10sz (size_t sz) +{ + return ((sz >= 10000000000000000000lu) ? 19 : + (sz >= 1000000000000000000lu) ? 18 : + (sz >= 100000000000000000lu) ? 17 : + (sz >= 10000000000000000lu) ? 16 : + (sz >= 1000000000000000lu) ? 15 : + (sz >= 100000000000000lu) ? 14 : + (sz >= 10000000000000lu) ? 13 : + (sz >= 1000000000000lu) ? 12 : + (sz >= 100000000000lu) ? 11 : + (sz >= 1000000000lu) ? 9 : + (sz >= 100000000lu) ? 8 : + (sz >= 10000000lu) ? 7 : + (sz >= 1000000lu) ? 6 : + (sz >= 100000lu) ? 5 : + (sz >= 10000lu) ? 4 : + (sz >= 1000lu) ? 3 : + (sz >= 100lu) ? 2 : + (sz >= 10lu) ? 1 : 0u); +} + +gsl_matrix *gsl_matrix_minor (const gsl_matrix *m, size_t row, size_t col) { + int n = m->size1 > m->size2 ? m->size1 : m->size2; + gsl_matrix *minor = gsl_matrix_alloc (n - 1, n - 1); + + for (size_t i = 0; i < n; ++i) { + if (i == row) continue; + for (size_t j = 0; j < n; ++j) { + if (j == col) continue; + gsl_matrix_set (minor, + i < row ? i : i - 1, + j < col ? j : j - 1, + gsl_matrix_get (m, i, j)); + } + } + + return minor; +} + +double +gsl_matrix_determinant (const gsl_matrix *m) +{ + size_t n = m->size1; + + if (n == 1) + return gsl_matrix_get (m, 0, 0); + if (n == 2) { + return + gsl_matrix_get (m, 0, 0)*gsl_matrix_get (m, 1, 1) - + gsl_matrix_get (m, 0, 1)*gsl_matrix_get (m, 1, 0); + } + + double determinant = 0; + for (size_t i = 0; i < n; ++i) { + gsl_matrix *minor = gsl_matrix_minor (m, 0, i); + + double minor_determinant = gsl_matrix_determinant(minor); + gsl_matrix_free (minor); + + determinant += (i % 2 == 0 ? 1 : -1) * + gsl_matrix_get (m, 0, i) * + minor_determinant; + } + + return determinant; +} + +double +gsl_matrix_cofactor (const gsl_matrix *m, size_t i, size_t j) +{ + gsl_matrix *minor = gsl_matrix_minor (m, i, j); + + double minor_determinant = gsl_matrix_determinant (minor); + + return (i + j) % 2 == 0 ? +minor_determinant + : -minor_determinant; +} diff --git a/src/utils.h b/src/utils.h new file mode 100644 index 0000000..6883a16 --- /dev/null +++ b/src/utils.h @@ -0,0 +1,33 @@ +#ifndef INCLUDED_UTILS_H +#define INCLUDED_UTILS_H + +#include +#include +#include +#include + +#define MALLOC malloc +#define REALLOC realloc +#define FREE free +#define ASSERT assert + +#define MIN(A, B) ({ \ + A < B ? A : B; \ +}) + +#define SWAP(A, B) ({ \ + typeof (A) tmp = (A); \ + (A) = (B); \ + (B) = tmp; \ + }) + +#define PRINT_EXP(EXP, FMT) printf (#EXP" = "FMT"\n", EXP) + +extern void print_gsl_matrix (const gsl_matrix *); +extern void prompt (char *label, char *fmt, void *where); +extern int log10sz (size_t sz); + +double gsl_matrix_determinant (const gsl_matrix *); +double gsl_matrix_cofactor (const gsl_matrix *, size_t i, size_t j); + +#endif -- cgit v1.3.1