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