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