liquid_feedback_core

view lf_update_suggestion_order.c @ 362:6b59cf46f772

Help output of "lf_update" and "lf_update_suggestion_order" either to stdout or stderr, depending on invocation
author jbe
date Sun Mar 17 12:17:36 2013 +0100 (2013-03-17)
parents 3bb60d324a22
children d11a5c013df9
line source
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <string.h>
4 #include <libpq-fe.h>
5 #include <search.h>
7 static char *escapeLiteral(PGconn *conn, const char *str, size_t len) {
8 // provides compatibility for PostgreSQL versions prior 9.0
9 // in future: return PQescapeLiteral(conn, str, len);
10 char *res;
11 size_t res_len;
12 res = malloc(2*len+3);
13 if (!res) return NULL;
14 res[0] = '\'';
15 res_len = PQescapeStringConn(conn, res+1, str, len, NULL);
16 res[res_len+1] = '\'';
17 res[res_len+2] = 0;
18 return res;
19 }
21 static void freemem(void *ptr) {
22 // to be used for "escapeLiteral" function
23 // provides compatibility for PostgreSQL versions prior 9.0
24 // in future: PQfreemem(ptr);
25 free(ptr);
26 }
28 #define COL_MEMBER_ID 0
29 #define COL_WEIGHT 1
30 #define COL_PREFERENCE 2
31 #define COL_SUGGESTION_ID 3
33 struct candidate {
34 char *key;
35 double score_per_step;
36 int reaches_score;
37 double score;
38 int seat;
39 };
41 static int compare_candidate(struct candidate *c1, struct candidate *c2) {
42 return strcmp(c1->key, c2->key);
43 }
45 static int candidate_count;
46 static struct candidate *candidates;
48 static void register_candidate(char **candidate_key, VISIT visit, int level) {
49 if (visit == postorder || visit == leaf) {
50 struct candidate *candidate;
51 candidate = candidates + (candidate_count++);
52 candidate->key = *candidate_key;
53 candidate->seat = 0;
54 }
55 }
57 static struct candidate *candidate_by_key(char *candidate_key) {
58 struct candidate *candidate;
59 struct candidate compare;
60 compare.key = candidate_key;
61 candidate = bsearch(&compare, candidates, candidate_count, sizeof(struct candidate), (void *)compare_candidate);
62 if (!candidate) {
63 fprintf(stderr, "Candidate not found (should not happen).\n");
64 abort();
65 }
66 return candidate;
67 }
69 struct ballot_section {
70 int count;
71 struct candidate **candidates;
72 };
74 struct ballot {
75 int weight;
76 struct ballot_section sections[4];
77 };
79 static struct candidate *loser(int round_number, struct ballot *ballots, int ballot_count) {
80 int i, j, k;
81 int remaining;
82 for (i=0; i<candidate_count; i++) {
83 candidates[i].score = 0.0;
84 }
85 remaining = candidate_count - round_number;
86 while (1) {
87 double scale;
88 if (remaining <= 1) break;
89 for (i=0; i<candidate_count; i++) {
90 candidates[i].score_per_step = 0.0;
91 candidates[i].reaches_score = 0;
92 }
93 for (i=0; i<ballot_count; i++) {
94 for (j=0; j<4; j++) {
95 int matches = 0;
96 for (k=0; k<ballots[i].sections[j].count; k++) {
97 struct candidate *candidate;
98 candidate = ballots[i].sections[j].candidates[k];
99 if (candidate->score < 1.0 && !candidate->seat) matches++;
100 }
101 if (matches) {
102 double score_inc;
103 score_inc = 1.0 / (double)matches;
104 for (k=0; k<ballots[i].sections[j].count; k++) {
105 struct candidate *candidate;
106 candidate = ballots[i].sections[j].candidates[k];
107 if (candidate->score < 1.0 && !candidate->seat) {
108 candidate->score_per_step += score_inc;
109 }
110 }
111 break;
112 }
113 }
114 }
115 scale = (double)candidate_count;
116 for (i=0; i<candidate_count; i++) {
117 double max_scale;
118 if (candidates[i].score_per_step > 0.0) {
119 max_scale = (1.0-candidates[i].score) / candidates[i].score_per_step;
120 if (max_scale <= scale) {
121 scale = max_scale;
122 candidates[i].reaches_score = 1;
123 }
124 }
125 }
126 for (i=0; i<candidate_count; i++) {
127 if (candidates[i].score_per_step > 0.0) {
128 if (candidates[i].reaches_score) {
129 candidates[i].score = 1.0;
130 remaining--;
131 } else {
132 candidates[i].score += scale * candidates[i].score_per_step;
133 if (candidates[i].score >= 1.0) remaining--;
134 }
135 if (remaining <= 1) break;
136 }
137 }
138 }
139 for (i=candidate_count-1; i>=0; i--) {
140 if (candidates[i].score < 1.0 && !candidates[i].seat) return candidates+i;
141 }
142 fprintf(stderr, "No remaining candidate (should not happen).");
143 abort();
144 }
146 static int write_ranks(PGconn *db, char *escaped_initiative_id, int final) {
147 PGresult *res;
148 char *cmd;
149 int i;
150 if (final) {
151 if (asprintf(&cmd, "BEGIN; UPDATE \"initiative\" SET \"final_suggestion_order_calculated\" = TRUE WHERE \"id\" = %s; UPDATE \"suggestion\" SET \"proportional_order\" = NULL WHERE \"initiative_id\" = %s", escaped_initiative_id, escaped_initiative_id) < 0) {
152 fprintf(stderr, "Could not prepare query string in memory.\n");
153 abort();
154 }
155 } else {
156 if (asprintf(&cmd, "BEGIN; UPDATE \"suggestion\" SET \"proportional_order\" = NULL WHERE \"initiative_id\" = %s", escaped_initiative_id) < 0) {
157 fprintf(stderr, "Could not prepare query string in memory.\n");
158 abort();
159 }
160 }
161 res = PQexec(db, cmd);
162 free(cmd);
163 if (!res) {
164 fprintf(stderr, "Error in pqlib while sending SQL command to initiate suggestion update.\n");
165 return 1;
166 } else if (
167 PQresultStatus(res) != PGRES_COMMAND_OK &&
168 PQresultStatus(res) != PGRES_TUPLES_OK
169 ) {
170 fprintf(stderr, "Error while executing SQL command to initiate suggestion update:\n%s", PQresultErrorMessage(res));
171 PQclear(res);
172 return 1;
173 } else {
174 PQclear(res);
175 }
176 for (i=0; i<candidate_count; i++) {
177 char *escaped_suggestion_id;
178 escaped_suggestion_id = escapeLiteral(db, candidates[i].key, strlen(candidates[i].key));
179 if (!escaped_suggestion_id) {
180 fprintf(stderr, "Could not escape literal in memory.\n");
181 abort();
182 }
183 if (asprintf(&cmd, "UPDATE \"suggestion\" SET \"proportional_order\" = %i WHERE \"id\" = %s", candidates[i].seat, escaped_suggestion_id) < 0) {
184 fprintf(stderr, "Could not prepare query string in memory.\n");
185 abort();
186 }
187 freemem(escaped_suggestion_id);
188 res = PQexec(db, cmd);
189 free(cmd);
190 if (!res) {
191 fprintf(stderr, "Error in pqlib while sending SQL command to update suggestion order.\n");
192 } else if (
193 PQresultStatus(res) != PGRES_COMMAND_OK &&
194 PQresultStatus(res) != PGRES_TUPLES_OK
195 ) {
196 fprintf(stderr, "Error while executing SQL command to update suggestion order:\n%s", PQresultErrorMessage(res));
197 PQclear(res);
198 } else {
199 PQclear(res);
200 continue;
201 }
202 res = PQexec(db, "ROLLBACK");
203 if (res) PQclear(res);
204 return 1;
205 }
206 res = PQexec(db, "COMMIT");
207 if (!res) {
208 fprintf(stderr, "Error in pqlib while sending SQL command to commit transaction.\n");
209 return 1;
210 } else if (
211 PQresultStatus(res) != PGRES_COMMAND_OK &&
212 PQresultStatus(res) != PGRES_TUPLES_OK
213 ) {
214 fprintf(stderr, "Error while executing SQL command to commit transaction:\n%s", PQresultErrorMessage(res));
215 PQclear(res);
216 return 1;
217 } else {
218 PQclear(res);
219 return 0;
220 }
221 }
223 static int process_initiative(PGconn *db, PGresult *res, char *escaped_initiative_id, int final) {
224 int err;
225 int ballot_count = 0;
226 struct ballot *ballots;
227 int i;
228 {
229 void *candidate_tree = NULL;
230 int tuple_count;
231 char *old_member_id = NULL;
232 struct ballot *ballot;
233 int candidates_in_sections[4] = {0, };
234 tuple_count = PQntuples(res);
235 if (!tuple_count) {
236 if (final) {
237 printf("No suggestions found, but marking initiative as finally calculated.\n");
238 err = write_ranks(db, escaped_initiative_id, final);
239 printf("Done.\n");
240 return err;
241 } else {
242 printf("Nothing to do.\n");
243 return 0;
244 }
245 }
246 candidate_count = 0;
247 for (i=0; i<=tuple_count; i++) {
248 char *member_id, *suggestion_id;
249 if (i<tuple_count) {
250 member_id = PQgetvalue(res, i, COL_MEMBER_ID);
251 suggestion_id = PQgetvalue(res, i, COL_SUGGESTION_ID);
252 if (!candidate_tree || !tfind(suggestion_id, &candidate_tree, (void *)strcmp)) {
253 candidate_count++;
254 if (!tsearch(suggestion_id, &candidate_tree, (void *)strcmp)) {
255 fprintf(stderr, "Insufficient memory while inserting into candidate tree.\n");
256 abort();
257 }
258 }
259 }
260 if (i==tuple_count || (old_member_id && strcmp(old_member_id, member_id))) {
261 ballot_count++;
262 }
263 old_member_id = member_id;
264 }
265 printf("Candidate count: %i\n", candidate_count);
266 candidates = malloc(candidate_count * sizeof(struct candidate));
267 if (!candidates) {
268 fprintf(stderr, "Insufficient memory while creating candidate list.\n");
269 abort();
270 }
271 candidate_count = 0;
272 twalk(candidate_tree, (void *)register_candidate);
273 while (candidate_tree) tdelete(*(void **)candidate_tree, &candidate_tree, (void *)strcmp);
274 printf("Ballot count: %i\n", ballot_count);
275 ballots = calloc(ballot_count, sizeof(struct ballot));
276 if (!ballots) {
277 fprintf(stderr, "Insufficient memory while creating ballot list.\n");
278 abort();
279 }
280 ballot = ballots;
281 for (i=0; i<tuple_count; i++) {
282 char *member_id, *suggestion_id;
283 int weight, preference;
284 member_id = PQgetvalue(res, i, COL_MEMBER_ID);
285 suggestion_id = PQgetvalue(res, i, COL_SUGGESTION_ID);
286 weight = (int)strtol(PQgetvalue(res, i, COL_WEIGHT), (char **)NULL, 10);
287 if (weight <= 0) {
288 fprintf(stderr, "Unexpected weight value.\n");
289 free(ballots);
290 free(candidates);
291 return 1;
292 }
293 preference = (int)strtol(PQgetvalue(res, i, COL_PREFERENCE), (char **)NULL, 10);
294 if (preference < 1 || preference > 4) {
295 fprintf(stderr, "Unexpected preference value.\n");
296 free(ballots);
297 free(candidates);
298 return 1;
299 }
300 preference--;
301 ballot->weight = weight;
302 ballot->sections[preference].count++;
303 if (old_member_id && strcmp(old_member_id, member_id)) ballot++;
304 old_member_id = member_id;
305 }
306 for (i=0; i<ballot_count; i++) {
307 int j;
308 for (j=0; j<4; j++) {
309 if (ballots[i].sections[j].count) {
310 ballots[i].sections[j].candidates = malloc(ballots[i].sections[j].count * sizeof(struct candidate *));
311 if (!ballots[i].sections[j].candidates) {
312 fprintf(stderr, "Insufficient memory while creating ballot section.\n");
313 abort();
314 }
315 }
316 }
317 }
318 ballot = ballots;
319 for (i=0; i<=tuple_count; i++) {
320 char *member_id, *suggestion_id;
321 int preference;
322 if (i<tuple_count) {
323 member_id = PQgetvalue(res, i, COL_MEMBER_ID);
324 suggestion_id = PQgetvalue(res, i, COL_SUGGESTION_ID);
325 preference = (int)strtol(PQgetvalue(res, i, COL_PREFERENCE), (char **)NULL, 10);
326 preference--;
327 ballot->sections[preference].candidates[candidates_in_sections[preference]++] = candidate_by_key(suggestion_id);
328 }
329 if (i==tuple_count || (old_member_id && strcmp(old_member_id, member_id))) {
330 ballot++;
331 candidates_in_sections[0] = 0;
332 candidates_in_sections[1] = 0;
333 candidates_in_sections[2] = 0;
334 candidates_in_sections[3] = 0;
335 }
336 old_member_id = member_id;
337 }
338 }
340 for (i=0; i<candidate_count; i++) {
341 struct candidate *candidate = loser(i, ballots, ballot_count);
342 candidate->seat = candidate_count - i;
343 printf("Assigning rank #%i to suggestion #%s.\n", candidate_count - i, candidate->key);
344 }
346 for (i=0; i<ballot_count; i++) {
347 int j;
348 for (j=0; j<4; j++) {
349 if (ballots[i].sections[j].count) {
350 free(ballots[i].sections[j].candidates);
351 }
352 }
353 }
354 free(ballots);
356 if (final) {
357 printf("Writing final ranks to database.\n");
358 } else {
359 printf("Writing ranks to database.\n");
360 }
361 err = write_ranks(db, escaped_initiative_id, final);
362 printf("Done.\n");
364 free(candidates);
366 return err;
367 }
369 int main(int argc, char **argv) {
371 // variable declarations:
372 int err = 0;
373 int i, count;
374 char *conninfo;
375 PGconn *db;
376 PGresult *res;
378 // parse command line:
379 if (argc == 0) return 1;
380 if (argc == 1 || !strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
381 FILE *out;
382 out = argc == 1 ? stderr : stdout;
383 fprintf(out, "\n");
384 fprintf(out, "Usage: %s <conninfo>\n", argv[0]);
385 fprintf(out, "\n");
386 fprintf(out, "<conninfo> is specified by PostgreSQL's libpq,\n");
387 fprintf(out, "see http://www.postgresql.org/docs/9.1/static/libpq-connect.html\n");
388 fprintf(out, "\n");
389 fprintf(out, "Example: %s dbname=liquid_feedback\n", argv[0]);
390 fprintf(out, "\n");
391 return argc == 1 ? 1 : 0;
392 }
393 {
394 size_t len = 0;
395 for (i=1; i<argc; i++) len += strlen(argv[i]) + 1;
396 conninfo = malloc(len * sizeof(char));
397 if (!conninfo) {
398 fprintf(stderr, "Error: Could not allocate memory for conninfo string.\n");
399 abort();
400 }
401 conninfo[0] = 0;
402 for (i=1; i<argc; i++) {
403 if (i>1) strcat(conninfo, " ");
404 strcat(conninfo, argv[i]);
405 }
406 }
408 // connect to database:
409 db = PQconnectdb(conninfo);
410 if (!db) {
411 fprintf(stderr, "Error: Could not create database handle.\n");
412 return 1;
413 }
414 if (PQstatus(db) != CONNECTION_OK) {
415 fprintf(stderr, "Could not open connection:\n%s", PQerrorMessage(db));
416 return 1;
417 }
419 // check initiatives:
420 res = PQexec(db, "SELECT \"initiative_id\", \"final\" FROM \"initiative_suggestion_order_calculation\"");
421 if (!res) {
422 fprintf(stderr, "Error in pqlib while sending SQL command selecting initiatives to process.\n");
423 err = 1;
424 } else if (PQresultStatus(res) != PGRES_TUPLES_OK) {
425 fprintf(stderr, "Error while executing SQL command selecting initiatives to process:\n%s", PQresultErrorMessage(res));
426 err = 1;
427 PQclear(res);
428 } else if (PQnfields(res) < 2) {
429 fprintf(stderr, "Too few columns returned by SQL command selecting initiatives to process.\n");
430 err = 1;
431 PQclear(res);
432 } else {
433 count = PQntuples(res);
434 printf("Number of initiatives to process: %i\n", count);
435 for (i=0; i<count; i++) {
436 char *initiative_id, *escaped_initiative_id;
437 int final;
438 char *cmd;
439 PGresult *res2;
440 initiative_id = PQgetvalue(res, i, 0);
441 final = (PQgetvalue(res, i, 1)[0] == 't') ? 1 : 0;
442 printf("Processing initiative_id: %s\n", initiative_id);
443 escaped_initiative_id = escapeLiteral(db, initiative_id, strlen(initiative_id));
444 if (!escaped_initiative_id) {
445 fprintf(stderr, "Could not escape literal in memory.\n");
446 abort();
447 }
448 if (asprintf(&cmd, "SELECT \"member_id\", \"weight\", \"preference\", \"suggestion_id\" FROM \"individual_suggestion_ranking\" WHERE \"initiative_id\" = %s ORDER BY \"member_id\", \"preference\"", escaped_initiative_id) < 0) {
449 fprintf(stderr, "Could not prepare query string in memory.\n");
450 abort();
451 }
452 res2 = PQexec(db, cmd);
453 free(cmd);
454 if (!res2) {
455 fprintf(stderr, "Error in pqlib while sending SQL command selecting individual suggestion rankings.\n");
456 err = 1;
457 } else if (PQresultStatus(res2) != PGRES_TUPLES_OK) {
458 fprintf(stderr, "Error while executing SQL command selecting individual suggestion rankings:\n%s", PQresultErrorMessage(res));
459 err = 1;
460 PQclear(res2);
461 } else if (PQnfields(res2) < 4) {
462 fprintf(stderr, "Too few columns returned by SQL command selecting individual suggestion rankings.\n");
463 err = 1;
464 PQclear(res2);
465 } else {
466 if (process_initiative(db, res2, escaped_initiative_id, final)) err = 1;
467 PQclear(res2);
468 }
469 freemem(escaped_initiative_id);
470 }
471 PQclear(res);
472 }
474 // cleanup and exit
475 PQfinish(db);
476 if (!err) printf("Successfully terminated.\n");
477 else fprintf(stderr, "Exiting with error code #%i.\n", err);
478 return err;
480 }

Impressum / About Us