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