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