chiark / gitweb /
WIP route value calculation - compiles, although doesn't run the LP
[ypp-sc-tools.db-test.git] / yarrg / rsvalue.c
1 /**/
2
3 #include <obstack.h>
4 #include <glpk.h>
5
6 #include "rscommon.h"
7
8 DEBUG_DEFINE_DEBUGF(value);
9
10 typedef struct { int mass, volu; } CommodInfo;
11 static int commodstablesz;
12 static CommodInfo *commodstable;
13
14 static sqlite3_stmt *ss_ipair_dist, *ss_ipair_trades;
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, rownum;
42 } IslandTradeEnd, *IslandDirnTradeEnds;
43
44 typedef struct {
45   int islandid;
46   IslandDirnTradeEnds collect, deliver;
47 } IslandTradeEnds;
48
49 static struct obstack ites_obstack;
50 static LPX *lp;
51
52 static int nconstraint_rows;
53 static int constraint_rows[1+2+3*MAX_LEGS];
54 static double constraint_coeffs[1+2+3*MAX_LEGS];
55       /* dummy0, src, dst, for_each_leg( [mass], [volume], [capital] ) */
56
57 static void add_constraint(int row, double coefficient) {
58   nconstraint_rows++; /* glpk indices start from 1 !!! */
59   constraint_rows  [nconstraint_rows]= row;
60   constraint_coeffs[nconstraint_rows]= coefficient;
61 }
62
63 static void avail_constraint(const Trade *t, IslandDirnTradeEnds *trades,
64                              int price, int qty, const char *srcdst) {
65   /* find row number of trade availability constraint */
66   IslandTradeEnd *search;
67
68   for (search= *trades; search; search=search->next)
69     if (search->commodid==t->commodid && search->price==price) {
70       assert(search->qty == qty);
71       goto found;
72     }
73   /* not found, add new row */
74   search= obstack_alloc(&ites_obstack, sizeof(*search));
75   search->commodid= t->commodid;
76   search->price= price;
77   search->qty= qty;
78   search->rownum= lpx_add_rows(lp, 1);
79   search->next= *trades;
80   if (DEBUGP(value)) {
81     char *name= masprintf("%s_commod%d_price%d",srcdst,t->commodid,price);
82     lpx_set_row_name(lp,search->rownum,name);
83     free(name);
84   }
85   *trades= search;
86  found:;
87   int rownum= search->rownum;
88
89   lpx_set_row_bnds(lp, rownum, LPX_UP, 0, qty);
90   add_constraint(rownum, 1.0);
91 }
92
93 static int setup_leg_constraints(double max_thing, int legs, const char *wh) {
94   int leg, startrow;
95   if (max_thing < 0 || !legs) return -1;
96   startrow= lpx_add_rows(lp, legs);
97   for (leg=0; leg<nislands-1; leg++) {
98     int row= leg+startrow;
99     lpx_set_row_bnds(lp, row, LPX_UP, 0, max_thing);
100     if (DEBUGP(value)) {
101       char *name= masprintf("max_leg%d_%s",leg,wh);
102       lpx_set_row_name(lp,row,name);
103       free(name);
104     }
105   }
106   return startrow;
107 }
108
109 static void add_leg_c(int startrow, int leg, double value) {
110   if (startrow<=0) return;
111   add_constraint(startrow+leg, value);
112 }
113
114 static IslandPair *ipair_get(int si, int di) {
115   IslandPair *ip, **ipa;
116
117   assert(si < nislands);
118   assert(di < nislands);
119
120   if (!(ipa= ipairs[si])) {
121     ipa= ipairs[si]= mcalloc(sizeof(*ipa) * nislands);
122   }
123   if ((ip= ipa[di]))
124     return ip;
125
126   ipa[di]= ip= mmalloc(sizeof(*ip));
127   ip->ntrades= 0;
128   ip->trades= 0;
129   int inblock= TRADES_PER_BLOCK;
130   TradesBlock *block= 0;
131
132   debugf("VALUE ipair_get(%d,%d) running...\n", si,di);
133   SQL_MUST( sqlite3_bind_int(ss_ipair_dist, 1, si) );
134   SQL_MUST( sqlite3_bind_int(ss_ipair_dist, 2, di) );
135   assert(SQL_STEP(ss_ipair_dist));
136   int dist= sqlite3_column_int(ss_ipair_dist, 0);
137   ip->distance_loss_factor= pow(distance_loss_factor_per_league, dist);
138   sqlite3_reset(ss_ipair_dist);
139
140   SQL_MUST( sqlite3_bind_int(ss_ipair_trades, 1, si) );
141   SQL_MUST( sqlite3_bind_int(ss_ipair_trades, 2, di) );
142
143   while (SQL_STEP(ss_ipair_trades)) {
144     if (inblock == TRADES_PER_BLOCK) {
145       block= mmalloc(sizeof(*block));
146       block->next= ip->trades;
147       ip->trades= block;
148       inblock= 0;
149     }
150     int *irp, i;
151     for (i=0, irp=&block->t[inblock].commodid; i<5; i++, irp++)
152       *irp= sqlite3_column_int(ss_ipair_trades, i);
153     ip->ntrades++;
154     inblock++;
155   }
156   if (inblock < TRADES_PER_BLOCK)
157     block->t[inblock].commodid= -1;
158
159   sqlite3_reset(ss_ipair_trades);
160   
161   return ip;
162 }
163
164 void value_route(int nislands, const int *islands) {
165   int s,d;
166
167   /* We need to construct the LP problem.  GLPK talks
168    * about rows and columns, which are numbered from 1.
169    *
170    * Each column is a `structural variable' ie one of the entries in
171    * the objective function.  In our case the set of structural
172    * variable is, for each port, the set of Trades which collect at
173    * that island.  (We use `port' to mean `specific visit to an
174    * island' so if an island appears more than once so do its trades.)
175    * We don't need to worry about crossing with all the possible
176    * delivery locations as we always deliver on the first port.
177    * We will call such a structural variable a Flow, for brevity.
178    *
179    * We iterate over the possible Flows adding them as columns as we
180    * go, and also adding their entries to the various constraints.
181    *
182    * Each row is an `auxiliary variable' ie one of the constraints.
183    * We have two kinds of constraint:
184    *   - mass/volume/capital: one constraint for each sailed leg
185    *       (unless relevant constraint is not satisfied)
186    *   - quantity of commodity available for collection
187    *       or delivery at particular price and island
188    * The former are numbered predictably: we have first all the mass
189    * limits, then all the volume limits, then all the capital limits
190    * (as applicable) - one for each leg, ie one for each entry
191    * in islands except the first.
192    *
193    * The latter are added as needed and the row numbers are stored in
194    * a data structure for later reuse.
195    */
196
197   assert(nislands >= 1);
198
199   char *free_to_reset_obstack= obstack_alloc(&ites_obstack, 1);
200
201   int nites=0;
202   IslandTradeEnds ites[nislands], *iteps[nislands];
203
204   for (s=0; s<nislands; s++) {
205     IslandTradeEnds *ite;
206     int si= islands[s];
207     int i;
208     for (i=0, ite=ites; i<nites; i++, ite++)
209       if (ite->islandid==si)
210         goto found;
211     /* not found, add new */
212     assert(ite == &ites[nites]);
213     ite->islandid= si;
214     ite->collect= ite->deliver= 0;
215     nites++;
216   found:
217     iteps[s]= ite;
218   }
219
220   assert(!lp);
221   lp= lpx_create_prob();
222   lpx_set_obj_dir(lp, LPX_MAX);
223   if (DEBUGP(value)) {
224     lpx_set_prob_name(lp,(char*)"value_route");
225     lpx_set_obj_name(lp,(char*)"profit");
226   }
227
228   int legs= nislands-1;
229   int mass_constraints= setup_leg_constraints(max_mass, legs, "mass");
230   int volu_constraints= setup_leg_constraints(max_volu, legs, "volu");
231   int capi_constraints= setup_leg_constraints(max_capi, legs, "capi");
232
233   double delay_slot_loss_factor= 1.0;
234   for (s=0;
235        s<nislands;
236        s++, delay_slot_loss_factor *= LOSS_FACTOR_PER_DELAY_SLOT) {
237     int si= islands[s];
238     
239     for (d=s; d<nislands; d++) {
240       int di= islands[d];
241       int already_d;
242       for (already_d=s+1; already_d<d; already_d++)
243         if (islands[already_d] == di)
244           /* visited this island already since we left s, uninteresting */
245           goto next_d;
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       int inblock= 0;
256       int col= lpx_add_cols(lp,ip->ntrades);
257
258       double loss_factor= delay_slot_loss_factor * ip->distance_loss_factor;
259
260       while (tradestodo-- >0) {
261         if (inblock >= TRADES_PER_BLOCK) {
262           block= block->next;
263           inblock= 0;
264         }
265         Trade *t= &block->t[inblock++];
266
267         debugf("  TRADE %d#%d..%d#%d %d %d-%d\n",
268                si,s, di,d, t->commodid, t->src_price, t->dst_price);
269
270         nconstraint_rows=0;
271
272         avail_constraint(t, &iteps[s]->collect, t->src_price,t->src_qty,"src");
273         avail_constraint(t, &iteps[d]->deliver, t->dst_price,t->dst_qty,"dst");
274
275         int leg;
276         for (leg=s; leg<d; leg++) {
277           add_leg_c(mass_constraints, leg, commodstable[t->commodid].mass);
278           add_leg_c(volu_constraints, leg, commodstable[t->commodid].volu);
279           add_leg_c(capi_constraints, leg, t->src_price);
280         }
281
282         lpx_set_col_bnds(lp, col, LPX_LO, 0, 0);
283         lpx_set_obj_coef(lp, col,
284                          (t->dst_price - t->src_price) * loss_factor);
285         lpx_set_mat_col(lp, col, nconstraint_rows,
286                         constraint_rows, constraint_coeffs);
287         if (DEBUGP(value)) {
288           char *name= masprintf("trade_commod%d_port%d_at%d_port%d_at%d",
289                                 t->commodid, s, t->src_price, d, t->dst_price);
290           lpx_set_col_name(lp, col, name);
291           free(name);
292         }
293       } /* while (tradestodo-- >0) */
294       
295       /*----- that's done adding these trades to the LP problem -----*/
296       
297     next_d:;
298     } /* for (d) */
299   next_s:;
300   } /* for (s) */
301
302   lpx_delete_prob(lp);
303   lp= 0;
304
305   obstack_free(&ites_obstack, free_to_reset_obstack);
306 }
307
308 void setup_value(void) {
309   sqlite3_stmt *sst;
310   int i;
311
312 #define obstack_chunk_alloc mmalloc
313 #define obstack_chunk_free free
314   obstack_init(&ites_obstack);
315
316   nislands= sql_single_int("SELECT max(islandid) FROM islands") + 1;
317   debugf("VALUE nislands=%d\n",nislands);
318
319   commodstablesz= sql_single_int("SELECT max(commodid) FROM commods") + 1;
320   commodstable= mmalloc(sizeof(*commodstable)*commodstablesz);
321   for (i=0; i<commodstablesz; i++)
322     commodstable[i].mass= commodstable[i].volu= -1;
323
324   SQL_MUST( sqlite3_prepare(db,
325      "SELECT commodid,unitmass,unitvolume FROM commods", -1,&sst,0) );
326   while (SQL_STEP(sst)) {
327     int id= sqlite3_column_int(sst,0);
328     assert(id>=0 && id<commodstablesz);
329     commodstable[id].mass= sqlite3_column_int(sst,1);
330     commodstable[id].volu= sqlite3_column_int(sst,2);
331   }
332   sqlite3_finalize(sst);
333
334   SQL_MUST( sqlite3_prepare(db,
335      "SELECT\n"
336      " sell.commodid            commodid,\n"
337      " sell.price               src_price,\n"
338      " sum(sell.qty)            src_qty,\n"
339      " buy.price                dst_price,\n"
340      " sum(buy.qty)             dst_qty\n"
341      " FROM sell JOIN buy\n"
342      "   ON sell.commodid = buy.commodid\n"
343      "  AND buy.price > sell.price\n"
344      " WHERE sell.islandid=?\n"
345      "   AND buy.islandid=?\n"
346      " GROUP BY sell.commodid, sell.price, buy.price",
347                             -1, &ss_ipair_trades, 0) );
348
349   SQL_MUST( sqlite3_prepare(db,
350      " SELECT dist from dists where aiid=? and biid=?",
351                             -1, &ss_ipair_dist, 0) );
352
353   ipairs= mcalloc(sizeof(*ipairs) * nislands);
354 }