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