liquid_feedback_core

view lf_update_suggestion_order.c @ 363:d11a5c013df9

Removed unused variable in "lf_update_suggestion_order"
author jbe
date Sun Mar 17 12:19:36 2013 +0100 (2013-03-17)
parents 6b59cf46f772
children 90ac85d184f8
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;
283 int weight, preference;
284 member_id = PQgetvalue(res, i, COL_MEMBER_ID);
285 weight = (int)strtol(PQgetvalue(res, i, COL_WEIGHT), (char **)NULL, 10);
286 if (weight <= 0) {
287 fprintf(stderr, "Unexpected weight value.\n");
288 free(ballots);
289 free(candidates);
290 return 1;
291 }
292 preference = (int)strtol(PQgetvalue(res, i, COL_PREFERENCE), (char **)NULL, 10);
293 if (preference < 1 || preference > 4) {
294 fprintf(stderr, "Unexpected preference value.\n");
295 free(ballots);
296 free(candidates);
297 return 1;
298 }
299 preference--;
300 ballot->weight = weight;
301 ballot->sections[preference].count++;
302 if (old_member_id && strcmp(old_member_id, member_id)) ballot++;
303 old_member_id = member_id;
304 }
305 for (i=0; i<ballot_count; i++) {
306 int j;
307 for (j=0; j<4; j++) {
308 if (ballots[i].sections[j].count) {
309 ballots[i].sections[j].candidates = malloc(ballots[i].sections[j].count * sizeof(struct candidate *));
310 if (!ballots[i].sections[j].candidates) {
311 fprintf(stderr, "Insufficient memory while creating ballot section.\n");
312 abort();
313 }
314 }
315 }
316 }
317 ballot = ballots;
318 for (i=0; i<=tuple_count; i++) {
319 char *member_id, *suggestion_id;
320 int preference;
321 if (i<tuple_count) {
322 member_id = PQgetvalue(res, i, COL_MEMBER_ID);
323 suggestion_id = PQgetvalue(res, i, COL_SUGGESTION_ID);
324 preference = (int)strtol(PQgetvalue(res, i, COL_PREFERENCE), (char **)NULL, 10);
325 preference--;
326 ballot->sections[preference].candidates[candidates_in_sections[preference]++] = candidate_by_key(suggestion_id);
327 }
328 if (i==tuple_count || (old_member_id && strcmp(old_member_id, member_id))) {
329 ballot++;
330 candidates_in_sections[0] = 0;
331 candidates_in_sections[1] = 0;
332 candidates_in_sections[2] = 0;
333 candidates_in_sections[3] = 0;
334 }
335 old_member_id = member_id;
336 }
337 }
339 for (i=0; i<candidate_count; i++) {
340 struct candidate *candidate = loser(i, ballots, ballot_count);
341 candidate->seat = candidate_count - i;
342 printf("Assigning rank #%i to suggestion #%s.\n", candidate_count - i, candidate->key);
343 }
345 for (i=0; i<ballot_count; i++) {
346 int j;
347 for (j=0; j<4; j++) {
348 if (ballots[i].sections[j].count) {
349 free(ballots[i].sections[j].candidates);
350 }
351 }
352 }
353 free(ballots);
355 if (final) {
356 printf("Writing final ranks to database.\n");
357 } else {
358 printf("Writing ranks to database.\n");
359 }
360 err = write_ranks(db, escaped_initiative_id, final);
361 printf("Done.\n");
363 free(candidates);
365 return err;
366 }
368 int main(int argc, char **argv) {
370 // variable declarations:
371 int err = 0;
372 int i, count;
373 char *conninfo;
374 PGconn *db;
375 PGresult *res;
377 // parse command line:
378 if (argc == 0) return 1;
379 if (argc == 1 || !strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
380 FILE *out;
381 out = argc == 1 ? stderr : stdout;
382 fprintf(out, "\n");
383 fprintf(out, "Usage: %s <conninfo>\n", argv[0]);
384 fprintf(out, "\n");
385 fprintf(out, "<conninfo> is specified by PostgreSQL's libpq,\n");
386 fprintf(out, "see http://www.postgresql.org/docs/9.1/static/libpq-connect.html\n");
387 fprintf(out, "\n");
388 fprintf(out, "Example: %s dbname=liquid_feedback\n", argv[0]);
389 fprintf(out, "\n");
390 return argc == 1 ? 1 : 0;
391 }
392 {
393 size_t len = 0;
394 for (i=1; i<argc; i++) len += strlen(argv[i]) + 1;
395 conninfo = malloc(len * sizeof(char));
396 if (!conninfo) {
397 fprintf(stderr, "Error: Could not allocate memory for conninfo string.\n");
398 abort();
399 }
400 conninfo[0] = 0;
401 for (i=1; i<argc; i++) {
402 if (i>1) strcat(conninfo, " ");
403 strcat(conninfo, argv[i]);
404 }
405 }
407 // connect to database:
408 db = PQconnectdb(conninfo);
409 if (!db) {
410 fprintf(stderr, "Error: Could not create database handle.\n");
411 return 1;
412 }
413 if (PQstatus(db) != CONNECTION_OK) {
414 fprintf(stderr, "Could not open connection:\n%s", PQerrorMessage(db));
415 return 1;
416 }
418 // check initiatives:
419 res = PQexec(db, "SELECT \"initiative_id\", \"final\" FROM \"initiative_suggestion_order_calculation\"");
420 if (!res) {
421 fprintf(stderr, "Error in pqlib while sending SQL command selecting initiatives to process.\n");
422 err = 1;
423 } else if (PQresultStatus(res) != PGRES_TUPLES_OK) {
424 fprintf(stderr, "Error while executing SQL command selecting initiatives to process:\n%s", PQresultErrorMessage(res));
425 err = 1;
426 PQclear(res);
427 } else if (PQnfields(res) < 2) {
428 fprintf(stderr, "Too few columns returned by SQL command selecting initiatives to process.\n");
429 err = 1;
430 PQclear(res);
431 } else {
432 count = PQntuples(res);
433 printf("Number of initiatives to process: %i\n", count);
434 for (i=0; i<count; i++) {
435 char *initiative_id, *escaped_initiative_id;
436 int final;
437 char *cmd;
438 PGresult *res2;
439 initiative_id = PQgetvalue(res, i, 0);
440 final = (PQgetvalue(res, i, 1)[0] == 't') ? 1 : 0;
441 printf("Processing initiative_id: %s\n", initiative_id);
442 escaped_initiative_id = escapeLiteral(db, initiative_id, strlen(initiative_id));
443 if (!escaped_initiative_id) {
444 fprintf(stderr, "Could not escape literal in memory.\n");
445 abort();
446 }
447 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) {
448 fprintf(stderr, "Could not prepare query string in memory.\n");
449 abort();
450 }
451 res2 = PQexec(db, cmd);
452 free(cmd);
453 if (!res2) {
454 fprintf(stderr, "Error in pqlib while sending SQL command selecting individual suggestion rankings.\n");
455 err = 1;
456 } else if (PQresultStatus(res2) != PGRES_TUPLES_OK) {
457 fprintf(stderr, "Error while executing SQL command selecting individual suggestion rankings:\n%s", PQresultErrorMessage(res));
458 err = 1;
459 PQclear(res2);
460 } else if (PQnfields(res2) < 4) {
461 fprintf(stderr, "Too few columns returned by SQL command selecting individual suggestion rankings.\n");
462 err = 1;
463 PQclear(res2);
464 } else {
465 if (process_initiative(db, res2, escaped_initiative_id, final)) err = 1;
466 PQclear(res2);
467 }
468 freemem(escaped_initiative_id);
469 }
470 PQclear(res);
471 }
473 // cleanup and exit
474 PQfinish(db);
475 if (!err) printf("Successfully terminated.\n");
476 else fprintf(stderr, "Exiting with error code #%i.\n", err);
477 return err;
479 }

Impressum / About Us