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