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