7 DEBUG_DEFINE_DEBUGF(value);
9 typedef struct { int mass, volu; } CommodInfo;
10 static int commodstabsz;
11 static CommodInfo *commodstab;
13 static sqlite3_stmt *ss_ipair_dist;
14 static sqlite3_stmt *ss_ite_buy, *ss_ite_sell;
17 #define MAX_LEGS (MAX_ROUTELEN-1)
20 int commodid, src_price, dst_price;
23 #define TRADES_PER_BLOCK 10
25 typedef struct TradesBlock {
26 struct TradesBlock *next;
28 Trade t[TRADES_PER_BLOCK];
31 static IslandPair ***ipairs; /* ipairs[sislandid][dislandid] */
33 typedef struct IslandTradeEnd {
34 struct IslandTradeEnd *next;
39 unsigned long generation;
44 IslandTradeEnd *src, *dst;
45 } IslandTradeEndHeads;
47 IslandTradeEndHeads *itradeends;
48 /* itradeends[islandid].{src,dst}->commodid etc. */
51 static unsigned long generation;
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] ) */
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;
64 static void avail_c(const Trade *t, IslandTradeEnd **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;
70 for (search= *trades; search; search=search->next)
71 if (search->commodid==t->commodid && search->price==price)
76 if (search->generation != generation) {
77 search->rownum= lpx_add_rows(lp, 1);
78 lpx_set_row_bnds(lp, search->rownum, LPX_UP, 0, search->qty);
80 if (DEBUGP(value) || DEBUGP(check)) {
81 char *name= masprintf("%s_i%d_c%d_%d_all",
82 srcdst, islandid, t->commodid, price);
83 lpx_set_row_name(lp,search->rownum,name);
86 int nrows= lpx_get_num_rows(lp);
87 assert(search->rownum == nrows);
89 for (i=1; i<nrows; i++)
90 assert(strcmp(name, lpx_get_row_name(lp,i)));
94 search->generation= generation;
97 add_constraint(search->rownum, 1.0);
100 static int setup_leg_constraints(double max_thing, int legs, const char *wh) {
102 if (max_thing < 0 || !legs) return -1;
103 startrow= lpx_add_rows(lp, legs);
104 for (leg=0; leg<legs; leg++) {
105 int row= leg+startrow;
106 lpx_set_row_bnds(lp, row, LPX_UP, 0, max_thing);
108 char *name= masprintf("%s_%d",wh,leg);
109 lpx_set_row_name(lp,row,name);
116 static void add_leg_c(int startrow, int leg, double value) {
117 if (startrow<=0) return;
119 add_constraint(startrow+leg, value);
122 IslandPair *ipair_get_maybe(int si, int di) {
125 assert(si < islandtablesz);
126 assert(di < islandtablesz);
128 if (!(ipa= ipairs[si])) return 0;
132 static IslandPair *ipair_get_create(int si, int di) {
133 IslandPair *ip, **ipa;
135 assert(si < islandtablesz);
136 assert(di < islandtablesz);
138 if (!(ipa= ipairs[si])) {
139 ipairs[si]= MCALLOC(ipa, islandtablesz);
146 ip->route_tail_value= -1;
148 if (si==di) ctr_islands_arbitrage++;
149 else ctr_ipairs_relevant++;
151 debugf("VALUE ipair_get(i%d,i%d) running...\n", si,di);
152 SQL_MUST( sqlite3_bind_int(ss_ipair_dist, 1, si) );
153 SQL_MUST( sqlite3_bind_int(ss_ipair_dist, 2, di) );
154 assert(SQL_STEP(ss_ipair_dist));
155 int dist= sqlite3_column_int(ss_ipair_dist, 0);
156 ip->distance_loss_factor= pow(distance_loss_factor_per_league, dist);
157 sqlite3_reset(ss_ipair_dist);
162 double value_route(int nislands, const int *islands, int exclude_arbitrage) {
165 ctr_subroutes_valued++;
167 /* We need to construct the LP problem. GLPK talks
168 * about rows and columns, which are numbered from 1.
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.
179 * We iterate over the possible Flows adding them as columns as we
180 * go, and also adding their entries to the various constraints.
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.
193 * The latter are added as needed and the row numbers are stored in
194 * a data structure for later reuse.
197 assert(nislands >= 1);
198 assert(++generation);
201 lp= lpx_create_prob();
202 lpx_set_obj_dir(lp, LPX_MAX);
203 lpx_set_int_parm(lp, LPX_K_MSGLEV, DEBUGP(lp) ? 3 : 1);
204 lpx_set_int_parm(lp, LPX_K_PRESOL, 1);
207 lpx_set_prob_name(lp,(char*)"value_route");
208 lpx_set_obj_name(lp,(char*)"profit");
211 int legs= nislands-1;
212 int mass_constraints= setup_leg_constraints(max_mass, legs, "mass");
213 int volu_constraints= setup_leg_constraints(max_volu, legs, "volu");
214 int capi_constraints= setup_leg_constraints(max_capi, legs, "capi");
216 double delay_slot_loss_factor= 1.0;
219 s++, delay_slot_loss_factor *= LOSS_FACTOR_PER_DELAY_SLOT) {
222 for (d= s + exclude_arbitrage;
227 for (already_d=s+1; already_d<d; already_d++)
228 if (islands[already_d] == di)
229 /* visited this island already since we left s, uninteresting */
233 /* route has returned to si, no need to think more about s */
236 /*----- actually add these trades to the LP problem -----*/
238 IslandPair *ip= ipair_get_maybe(islands[s], islands[d]);
240 if (!ip || !ip->trades)
243 double loss_factor= delay_slot_loss_factor * ip->distance_loss_factor;
244 debugf(" SOME i%d#%d..i%d#%d dslf=%g dlf=%g lf=%g\n",
246 delay_slot_loss_factor, ip->distance_loss_factor, loss_factor);
249 for (block=ip->trades; block; block=block->next) {
251 for (inblock=0; inblock<block->ntrades; inblock++) {
252 Trade *t= &block->t[inblock];
254 debugf(" TRADE i%d#%d..i%d#%d c%d %d-%d ",
255 si,s, di,d, t->commodid, t->src_price, t->dst_price);
259 avail_c(t, &itradeends[si].src, t->src_price, "src", si,ss_ite_sell);
260 avail_c(t, &itradeends[di].dst, t->dst_price, "dst", di,ss_ite_buy);
263 for (leg=s; leg<d; leg++) {
264 add_leg_c(mass_constraints,leg, commodstab[t->commodid].mass*1e-3);
265 add_leg_c(volu_constraints,leg, commodstab[t->commodid].volu*1e-3);
266 add_leg_c(capi_constraints,leg, t->src_price);
269 double unit_profit= t->dst_price * loss_factor - t->src_price;
270 debugf(" unit profit %f\n", unit_profit);
271 if (unit_profit <= 0) continue;
273 int col= lpx_add_cols(lp,1);
274 lpx_set_col_bnds(lp, col, LPX_LO, 0, 0);
275 lpx_set_obj_coef(lp, col, unit_profit);
276 lpx_set_mat_col(lp, col, nconstraint_rows,
277 constraint_rows, constraint_coeffs);
280 char *name= masprintf("c%d_p%d_%d_p%d_%d", t->commodid,
281 s, t->src_price, d, t->dst_price);
282 lpx_set_col_name(lp, col, name);
288 /*----- that's done adding these trades to the LP problem -----*/
297 if (lpx_get_num_cols(lp)) {
298 ctr_subroutes_nonempty++;
301 lpx_write_cpxlp(lp, (char*)DEBUG_DEV);
303 int ipr= lpx_simplex(lp);
304 assert(ipr==LPX_E_OK);
307 lpx_print_sol(lp, (char*)DEBUG_DEV);
309 int lpst= lpx_get_status(lp);
310 assert(lpst == LPX_OPT);
311 profit= lpx_get_obj_val(lp);
321 " FROM sell, buy\n" \
322 " WHERE sell.commodid=buy.commodid AND sell.price < buy.price\n"
324 static void read_trades(void) {
325 /* We would like to use DISTINCT but sqlite3 is too stupid
326 * to notice that it could use the index to do the DISTINCT
327 * which makes it rather slow. */
328 sqlite3_stmt *ss_trades;
331 "sell.commodid, sell.islandid, sell.price, buy.islandid, buy.price"
332 SQL_PREPARE(ss_trades,
333 " SELECT " TRADE_COLS "\n"
335 " ORDER BY " TRADE_COLS);
337 SQL_DISTINCT_DECL(cols,5);
338 while (SQL_DISTINCT_STEP(ss_trades,cols,5)) {
340 IslandPair *ip= ipair_get_create(cols[1], cols[3]);
341 TradesBlock *block= ip->trades;
342 if (!block || ip->trades->ntrades >= TRADES_PER_BLOCK) {
344 block->next= ip->trades;
348 Trade *trade= &block->t[block->ntrades];
349 trade->commodid= cols[0];
350 trade->src_price= cols[2];
351 trade->dst_price= cols[4];
354 sqlite3_finalize(ss_trades);
357 static void read_islandtradeends(const char *bs, int srcdstoff) {
359 #define TRADEEND_KEYCOLS "%s.commodid, %s.islandid, %s.stallid"
360 char *stmt= masprintf(" SELECT " TRADEEND_KEYCOLS ", %s.price, %s.qty\n"
362 " ORDER BY " TRADEEND_KEYCOLS,
363 bs,bs,bs,bs,bs, bs,bs,bs);
364 char *stmt_id= masprintf("qtys (%s)",bs);
365 sqlite3_stmt *ss= sql_prepare(stmt, stmt_id);
366 free(stmt); free(stmt_id);
368 SQL_DISTINCT_DECL(cols,5);
369 while (SQL_DISTINCT_STEP(ss,cols,3)) {
370 ctr_quantities_loaded++;
371 IslandTradeEnd *search;
373 int commodid= cols[0];
374 int islandid= cols[1];
378 IslandTradeEnd **trades= (void*)((char*)&itradeends[islandid] + srcdstoff);
380 for (search= *trades; search; search=search->next)
381 if (search->commodid==commodid && search->price==price)
383 /* not found, add new end */
386 search->commodid= commodid;
387 search->price= price;
388 search->next= *trades;
389 search->generation= 0;
396 sqlite3_finalize(ss);
399 void setup_value(void) {
402 commodstabsz= sql_single_int("SELECT max(commodid) FROM commods") + 1;
403 MCALLOC_INITEACH(commodstab, commodstabsz,
404 this->mass= this->volu= -1
408 "SELECT commodid,unitmass,unitvolume FROM commods");
409 while (SQL_STEP(sst)) {
410 ctr_commodities_loaded++;
411 int id= sqlite3_column_int(sst,0);
412 assert(id>=0 && id<commodstabsz);
413 commodstab[id].mass= sqlite3_column_int(sst,1);
414 commodstab[id].volu= sqlite3_column_int(sst,2);
416 sqlite3_finalize(sst);
418 MCALLOC(ipairs, islandtablesz);
419 MCALLOC(itradeends, islandtablesz);
421 SQL_PREPARE(ss_ipair_dist,
422 " SELECT dist FROM dists\n"
423 " WHERE aiid=? and biid=?");
426 read_islandtradeends("sell", offsetof(IslandTradeEndHeads, src));
427 read_islandtradeends("buy", offsetof(IslandTradeEndHeads, dst));