chiark / gitweb /
routesearch: use quick elim criterion separately per ap in bucketelim
[ypp-sc-tools.main.git] / yarrg / rsvalue.c
1 /**/
2
3 #include <glpk.h>
4
5 #include "rscommon.h"
6
7 DEBUG_DEFINE_DEBUGF(value);
8 DEBUG_DEFINE_SOME_DEBUGF(value2,debug2f);
9
10 typedef struct { int mass, volu; } CommodInfo;
11 static int commodstabsz;
12 static CommodInfo *commodstab;
13
14 static sqlite3_stmt *ss_ipair_dist;
15 static sqlite3_stmt *ss_ite_buy, *ss_ite_sell;
16
17
18 #define MAX_LEGS (MAX_ROUTELEN-1)
19
20 typedef struct {
21   int commodid, src_price, dst_price;
22 } Trade;
23
24 #define TRADES_PER_BLOCK 10
25
26 typedef struct TradesBlock {
27   struct TradesBlock *next;
28   int ntrades;
29   Trade t[TRADES_PER_BLOCK];
30 } TradesBlock;
31
32 static IslandPair ***ipairs; /* ipairs[sislandid][dislandid] */
33
34 typedef struct IslandTradeEnd {
35   struct IslandTradeEnd *next;
36   /* key: */
37   int commodid, price;
38   /* values: */
39   int qty;
40   unsigned long generation;
41   int rownum;
42 } IslandTradeEnd;
43
44 typedef struct {
45   IslandTradeEnd *src, *dst;
46 } IslandTradeEndHeads;
47
48 IslandTradeEndHeads *itradeends;
49   /* itradeends[islandid].{src,dst}->commodid etc. */
50
51 static LPX *lp;
52 static unsigned long generation;
53
54 static int nconstraint_rows;
55 static int constraint_rows[1+2+3*MAX_LEGS];
56 static double constraint_coeffs[1+2+3*MAX_LEGS];
57       /* dummy0, src, dst, for_each_leg( [mass], [volume], [capital] ) */
58
59 static void add_constraint(int row, double coefficient) {
60   nconstraint_rows++; /* glpk indices start from 1 !!! */
61   constraint_rows  [nconstraint_rows]= row;
62   constraint_coeffs[nconstraint_rows]= coefficient;
63 }
64
65 static void avail_c(const Trade *t, IslandTradeEnd **trades,
66                     int price, const char *srcdst,
67                     int islandid, sqlite3_stmt *ss_ite) {
68   /* find row number of trade availability constraint */
69   IslandTradeEnd *search;
70
71   for (search= *trades; search; search=search->next)
72     if (search->commodid==t->commodid && search->price==price)
73       goto found;
74   abort();
75   
76  found:;
77   if (search->generation != generation) {
78     search->rownum= lpx_add_rows(lp, 1);
79     lpx_set_row_bnds(lp, search->rownum, LPX_UP, 0, search->qty);
80
81     if (DEBUGP(value) || DEBUGP(check)) {
82       char *name= masprintf("%s_i%d_c%d_%d_all",
83                             srcdst, islandid, t->commodid, price);
84       lpx_set_row_name(lp,search->rownum,name);
85
86       if (DEBUGP(check)) {
87         int nrows= lpx_get_num_rows(lp);
88         assert(search->rownum == nrows);
89         int i;
90         for (i=1; i<nrows; i++)
91           assert(strcmp(name, lpx_get_row_name(lp,i)));
92       }
93       free(name);
94     }
95     search->generation= generation;
96   }
97
98   add_constraint(search->rownum, 1.0);
99 }
100
101 static int setup_leg_constraints(double max_thing, int legs, const char *wh) {
102   int leg, startrow;
103   if (max_thing < 0 || !legs) return -1;
104   startrow= lpx_add_rows(lp, legs);
105   for (leg=0; leg<legs; leg++) {
106     int row= leg+startrow;
107     lpx_set_row_bnds(lp, row, LPX_UP, 0, max_thing);
108     if (DEBUGP(value)) {
109       char *name= masprintf("%s_%d",wh,leg);
110       lpx_set_row_name(lp,row,name);
111       free(name);
112     }
113   }
114   return startrow;
115 }
116
117 static void add_leg_c(int startrow, int leg, double value) {
118   if (startrow<=0) return;
119   assert(value > 0);
120   add_constraint(startrow+leg, value);
121 }
122
123 IslandPair *ipair_get_maybe(int si, int di) {
124   IslandPair **ipa;
125
126   assert(si < islandtablesz);
127   assert(di < islandtablesz);
128
129   if (!(ipa= ipairs[si])) return 0;
130   return ipa[di];
131 }
132
133 static IslandPair *ipair_get_create(int si, int di) {
134   IslandPair *ip, **ipa;
135
136   assert(si < islandtablesz);
137   assert(di < islandtablesz);
138
139   if (!(ipa= ipairs[si])) {
140     ipairs[si]= MCALLOC(ipa, islandtablesz);
141   }
142   if ((ip= ipa[di]))
143     return ip;
144
145   ipa[di]= NEW(ip);
146   ip->trades= 0;
147   ip->route_tail_value= -1;
148
149   if (si==di) ctr_islands_arbitrage++;
150   else ctr_ipairs_relevant++;
151
152   debug2f("VALUE ipair_get(i%d,i%d) running...\n", si,di);
153   SQL_MUST( sqlite3_bind_int(ss_ipair_dist, 1, si) );
154   SQL_MUST( sqlite3_bind_int(ss_ipair_dist, 2, di) );
155   assert(SQL_STEP(ss_ipair_dist));
156   int dist= sqlite3_column_int(ss_ipair_dist, 0);
157   ip->distance_loss_factor= pow(distance_loss_factor_per_league, dist);
158   sqlite3_reset(ss_ipair_dist);
159   
160   return ip;
161 }
162
163 double value_route(int nislands, const int *islands, int exclude_arbitrage) {
164   int s,d;
165
166   ctr_subroutes_valued++;
167
168   /* We need to construct the LP problem.  GLPK talks
169    * about rows and columns, which are numbered from 1.
170    *
171    * Each column is a `structural variable' ie one of the entries in
172    * the objective function.  In our case the set of structural
173    * variable is, for each port, the set of Trades which collect at
174    * that island.  (We use `port' to mean `specific visit to an
175    * island' so if an island appears more than once so do its trades.)
176    * We don't need to worry about crossing with all the possible
177    * delivery locations as we always deliver on the first port.
178    * We will call such a structural variable a Flow, for brevity.
179    *
180    * We iterate over the possible Flows adding them as columns as we
181    * go, and also adding their entries to the various constraints.
182    *
183    * Each row is an `auxiliary variable' ie one of the constraints.
184    * We have two kinds of constraint:
185    *   - mass/volume/capital: one constraint for each sailed leg
186    *       (unless relevant constraint is not satisfied)
187    *   - quantity of commodity available for collection
188    *       or delivery at particular price and island
189    * The former are numbered predictably: we have first all the mass
190    * limits, then all the volume limits, then all the capital limits
191    * (as applicable) - one for each leg, ie one for each entry
192    * in islands except the first.
193    *
194    * The latter are added as needed and the row numbers are stored in
195    * a data structure for later reuse.
196    */
197
198   assert(nislands >= 1);
199   assert(++generation);
200
201   assert(!lp);
202   lp= lpx_create_prob();
203   lpx_set_obj_dir(lp, LPX_MAX);
204   lpx_set_int_parm(lp, LPX_K_MSGLEV, DEBUGP(lp) ? 3 : 1);
205   lpx_set_int_parm(lp, LPX_K_PRESOL, 1);
206
207   if (DEBUGP(value)) {
208     lpx_set_prob_name(lp,(char*)"value_route");
209     lpx_set_obj_name(lp,(char*)"profit");
210   }
211
212   int legs= nislands-1;
213   int mass_constraints= setup_leg_constraints(max_mass, legs, "mass");
214   int volu_constraints= setup_leg_constraints(max_volu, legs, "volu");
215   int capi_constraints= setup_leg_constraints(max_capi, legs, "capi");
216
217   double delay_slot_loss_factor= 1.0;
218   for (s=0;
219        s<nislands;
220        s++, delay_slot_loss_factor *= LOSS_FACTOR_PER_DELAY_SLOT) {
221     int si= islands[s];
222     
223     for (d= s + exclude_arbitrage;
224          d < nislands;
225          d++) {
226       int di= islands[d];
227       int already_d;
228       for (already_d=s+1; already_d<d; already_d++)
229         if (islands[already_d] == di)
230           /* visited this island already since we left s, uninteresting */
231           goto next_d;
232
233       if (d>s && di==si)
234         /* route has returned to si, no need to think more about s */
235         goto next_s;
236
237       /*----- actually add these trades to the LP problem -----*/
238       
239       IslandPair *ip= ipair_get_maybe(islands[s], islands[d]);
240
241       if (!ip || !ip->trades)
242         goto next_d;
243
244       double loss_factor= delay_slot_loss_factor * ip->distance_loss_factor;
245       debugf(" SOME   i%d#%d..i%d#%d  dslf=%g dlf=%g  lf=%g\n",
246              si,s, di,d,
247              delay_slot_loss_factor, ip->distance_loss_factor, loss_factor);
248
249       TradesBlock *block;
250       for (block=ip->trades; block; block=block->next) {
251         int inblock;
252         for (inblock=0; inblock<block->ntrades; inblock++) {
253           Trade *t= &block->t[inblock];
254
255           debugf("  TRADE i%d#%d..i%d#%d c%d %d-%d  ",
256                  si,s, di,d, t->commodid, t->src_price, t->dst_price);
257
258           nconstraint_rows=0;
259
260           avail_c(t, &itradeends[si].src, t->src_price, "src", si,ss_ite_sell);
261           avail_c(t, &itradeends[di].dst, t->dst_price, "dst", di,ss_ite_buy);
262
263           int leg;
264           for (leg=s; leg<d; leg++) {
265             add_leg_c(mass_constraints,leg, commodstab[t->commodid].mass*1e-3);
266             add_leg_c(volu_constraints,leg, commodstab[t->commodid].volu*1e-3);
267             add_leg_c(capi_constraints,leg, t->src_price);
268           }
269
270           double unit_profit= t->dst_price * loss_factor - t->src_price;
271           debugf("    unit profit %f\n", unit_profit);
272           if (unit_profit <= 0) continue;
273
274           int col= lpx_add_cols(lp,1);
275           lpx_set_col_bnds(lp, col, LPX_LO, 0, 0);
276           lpx_set_obj_coef(lp, col, unit_profit);
277           lpx_set_mat_col(lp, col, nconstraint_rows,
278                           constraint_rows, constraint_coeffs);
279
280           if (DEBUGP(value)) {
281             char *name= masprintf("c%d_p%d_%d_p%d_%d", t->commodid,
282                                   s, t->src_price, d, t->dst_price);
283             lpx_set_col_name(lp, col, name);
284             free(name);
285           }
286         } /* inblock */
287       } /* block */
288       
289       /*----- that's done adding these trades to the LP problem -----*/
290       
291     next_d:;
292     } /* for (d) */
293   next_s:;
294   } /* for (s) */
295
296   double profit= 0;
297
298   if (lpx_get_num_cols(lp)) {
299     ctr_subroutes_nonempty++;
300     
301     if (DEBUGP(lp))
302       lpx_write_cpxlp(lp, (char*)DEBUG_DEV);
303
304     int ipr= lpx_simplex(lp);
305     assert(ipr==LPX_E_OK);
306
307     if (DEBUGP(lp))
308       lpx_print_sol(lp, (char*)DEBUG_DEV);
309
310     int lpst= lpx_get_status(lp);
311     assert(lpst == LPX_OPT);
312     profit= lpx_get_obj_val(lp);
313   }
314
315   lpx_delete_prob(lp);
316   lp= 0;
317
318   debugf("    %s %f\n",
319          exclude_arbitrage ? "base value" : "route value",
320          profit);
321   return profit;
322 }
323
324 #define TRADE_FROM                                                      \
325     "  FROM sell, buy\n"                                                \
326     "  WHERE sell.commodid=buy.commodid AND sell.price < buy.price\n"
327               
328 static void read_trades(void) {
329   /* We would like to use DISTINCT but sqlite3 is too stupid
330    * to notice that it could use the index to do the DISTINCT
331    * which makes it rather slow. */
332   sqlite3_stmt *ss_trades;
333
334 #define TRADE_COLS \
335     "sell.commodid, sell.islandid, sell.price, buy.islandid, buy.price"
336   SQL_PREPARE(ss_trades,
337               " SELECT " TRADE_COLS "\n"
338               TRADE_FROM
339               "  ORDER BY " TRADE_COLS);
340
341   SQL_DISTINCT_DECL(cols,5);
342   while (SQL_DISTINCT_STEP(ss_trades,cols,5)) {    
343     ctr_trades_loaded++;
344     IslandPair *ip= ipair_get_create(cols[1], cols[3]);
345     TradesBlock *block= ip->trades;
346     if (!block || ip->trades->ntrades >= TRADES_PER_BLOCK) {
347       NEW(block);
348       block->next= ip->trades;
349       ip->trades= block;
350       block->ntrades= 0;
351     }
352     Trade *trade= &block->t[block->ntrades];
353     trade->commodid=  cols[0];
354     trade->src_price= cols[2];
355     trade->dst_price= cols[4];
356     block->ntrades++;
357   }
358   sqlite3_finalize(ss_trades);
359 }
360
361 static void read_islandtradeends(const char *bs, int srcdstoff) {
362
363 #define TRADEEND_KEYCOLS "%s.commodid, %s.islandid, %s.stallid"
364   char *stmt= masprintf(" SELECT " TRADEEND_KEYCOLS ", %s.price, %s.qty\n"
365                         TRADE_FROM
366                         "  ORDER BY "  TRADEEND_KEYCOLS,
367                         bs,bs,bs,bs,bs, bs,bs,bs);
368   char *stmt_id= masprintf("qtys (%s)",bs);
369   sqlite3_stmt *ss= sql_prepare(stmt, stmt_id);
370   free(stmt); free(stmt_id);
371
372   SQL_DISTINCT_DECL(cols,5);
373   while (SQL_DISTINCT_STEP(ss,cols,3)) {
374     ctr_quantities_loaded++;
375     IslandTradeEnd *search;
376
377     int commodid= cols[0];
378     int islandid= cols[1];
379     int price= cols[3];
380     int qty= cols[4];
381
382     IslandTradeEnd **trades= (void*)((char*)&itradeends[islandid] + srcdstoff);
383
384     for (search= *trades; search; search=search->next)
385       if (search->commodid==commodid && search->price==price)
386         goto found;
387     /* not found, add new end */
388
389     NEW(search);
390     search->commodid= commodid;
391     search->price= price;
392     search->next= *trades;
393     search->generation= 0;
394     search->qty= 0;
395     *trades= search;
396
397   found:
398     search->qty += qty;
399   }
400   sqlite3_finalize(ss);
401 }
402
403 void setup_value(void) {
404   sqlite3_stmt *sst;
405
406   commodstabsz= sql_single_int("SELECT max(commodid) FROM commods") + 1;
407   MCALLOC_INITEACH(commodstab, commodstabsz,
408                    this->mass= this->volu= -1
409                    );
410
411   SQL_PREPARE(sst,
412               "SELECT commodid,unitmass,unitvolume FROM commods");
413   while (SQL_STEP(sst)) {
414     ctr_commodities_loaded++;
415     int id= sqlite3_column_int(sst,0);
416     assert(id>=0 && id<commodstabsz);
417     commodstab[id].mass= sqlite3_column_int(sst,1);
418     commodstab[id].volu= sqlite3_column_int(sst,2);
419   }
420   sqlite3_finalize(sst);
421
422   MCALLOC(ipairs, islandtablesz);
423   MCALLOC(itradeends, islandtablesz);
424
425   SQL_PREPARE(ss_ipair_dist,
426               " SELECT dist FROM dists\n"
427               "  WHERE aiid=? and biid=?");
428
429   read_trades();
430   read_islandtradeends("sell", offsetof(IslandTradeEndHeads, src));
431   read_islandtradeends("buy",  offsetof(IslandTradeEndHeads, dst));
432 }