chiark / gitweb /
WIP routesearch; before better SQL stmts
[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, src_qty, dst_price, dst_qty;
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_MUST( sqlite3_bind_int(ss_ite, 1, islandid) );
83   SQL_MUST( sqlite3_bind_int(ss_ite, 2, t->commodid) );
84   SQL_MUST( sqlite3_bind_int(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_commod%d_price%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<5; 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 void 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   if (DEBUGP(value)) {
238     lpx_set_prob_name(lp,(char*)"value_route");
239     lpx_set_obj_name(lp,(char*)"profit");
240   }
241
242   int legs= nislands-1;
243   int mass_constraints= setup_leg_constraints(max_mass, legs, "mass");
244   int volu_constraints= setup_leg_constraints(max_volu, legs, "volu");
245   int capi_constraints= setup_leg_constraints(max_capi, legs, "capi");
246
247   double delay_slot_loss_factor= 1.0;
248   for (s=0;
249        s<nislands;
250        s++, delay_slot_loss_factor *= LOSS_FACTOR_PER_DELAY_SLOT) {
251     int si= islands[s];
252     
253     for (d=s; d<nislands; d++) {
254       int di= islands[d];
255       int already_d;
256       for (already_d=s+1; already_d<d; already_d++)
257         if (islands[already_d] == di)
258           /* visited this island already since we left s, uninteresting */
259           goto next_d;
260
261       if (d>s && di==si)
262         /* route has returned to si, no need to think more about s */
263         goto next_s;
264
265       /*----- actually add these trades to the LP problem -----*/
266       
267       IslandPair *ip= ipair_get(islands[s], islands[d]);
268       TradesBlock *block= ip->trades;
269       int tradestodo= ip->ntrades;
270       if (!tradestodo)
271         goto next_d;
272
273       int inblock= 0;
274       int col= lpx_add_cols(lp,ip->ntrades);
275
276       double loss_factor= delay_slot_loss_factor * ip->distance_loss_factor;
277
278       while (tradestodo-- >0) {
279         if (inblock >= TRADES_PER_BLOCK) {
280           block= block->next;
281           inblock= 0;
282         }
283         Trade *t= &block->t[inblock++];
284
285         debugf("  TRADE %d#%d..%d#%d %d %d-%d\n",
286                si,s, di,d, t->commodid, t->src_price, t->dst_price);
287
288         nconstraint_rows=0;
289
290         avail_c(t, &iteps[s]->collect, t->src_price,"src", si, ss_ite_sell);
291         avail_c(t, &iteps[d]->deliver, t->dst_price,"dst", di, ss_ite_buy);
292
293         int leg;
294         for (leg=s; leg<d; leg++) {
295           add_leg_c(mass_constraints, leg, commodstable[t->commodid].mass);
296           add_leg_c(volu_constraints, leg, commodstable[t->commodid].volu);
297           add_leg_c(capi_constraints, leg, t->src_price);
298         }
299
300         lpx_set_col_bnds(lp, col, LPX_LO, 0, 0);
301         lpx_set_obj_coef(lp, col,
302                          (t->dst_price - t->src_price) * loss_factor);
303         lpx_set_mat_col(lp, col, nconstraint_rows,
304                         constraint_rows, constraint_coeffs);
305         if (DEBUGP(value)) {
306           char *name= masprintf("trade_commod%d_port%d_at%d_port%d_at%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       } /* while (tradestodo-- >0) */
312       
313       /*----- that's done adding these trades to the LP problem -----*/
314       
315     next_d:;
316     } /* for (d) */
317   next_s:;
318   } /* for (s) */
319
320   lpx_delete_prob(lp);
321   lp= 0;
322 }
323
324 void setup_value(void) {
325   sqlite3_stmt *sst;
326   int i;
327
328   nislands= sql_single_int("SELECT max(islandid) FROM islands") + 1;
329   debugf("VALUE nislands=%d\n",nislands);
330
331   commodstablesz= sql_single_int("SELECT max(commodid) FROM commods") + 1;
332   commodstable= mmalloc(sizeof(*commodstable)*commodstablesz);
333   for (i=0; i<commodstablesz; i++)
334     commodstable[i].mass= commodstable[i].volu= -1;
335
336   SQL_MUST( sqlite3_prepare(db,
337      "SELECT commodid,unitmass,unitvolume FROM commods", -1,&sst,0) );
338   while (SQL_STEP(sst)) {
339     int id= sqlite3_column_int(sst,0);
340     assert(id>=0 && id<commodstablesz);
341     commodstable[id].mass= sqlite3_column_int(sst,1);
342     commodstable[id].volu= sqlite3_column_int(sst,2);
343   }
344   sqlite3_finalize(sst);
345
346   SQL_MUST( sqlite3_prepare(db,
347      " SELECT dist from dists where aiid=? and biid=?",
348                             -1, &ss_ipair_dist, 0) );
349
350   SQL_MUST( sqlite3_prepare(db,
351      "SELECT DISTINCT\n"
352      " sell.commodid            commodid,\n"
353      " sell.price               src_price,\n"
354      " buy.price                dst_price\n"
355      " FROM sell JOIN buy\n"
356      "   ON sell.commodid = buy.commodid\n"
357      "  AND buy.price > sell.price\n"
358      " WHERE sell.islandid=?\n"
359      "   AND buy.islandid=?",
360                             -1, &ss_ipair_trades, 0) );
361
362 #define BS(bs)                                          \
363   SQL_MUST( sqlite3_prepare(db,                         \
364      "SELECT\n"                                         \
365      " sum(qty)\n"                                      \
366      " FROM " #bs "\n"                                  \
367      " WHERE islandid=?\n"                              \
368      "   AND commodid=?\n"                              \
369      "   AND price=?",                                  \
370                             -1, &ss_ite_##bs, 0) );
371   BS(buy)
372   BS(sell)
373 #undef BS
374
375   ipairs= mcalloc(sizeof(*ipairs) * nislands);
376 }