7 DEBUG_DEFINE_DEBUGF(value);
9 typedef struct { int mass, volu; } CommodInfo;
10 static int commodstablesz;
11 static CommodInfo *commodstable;
13 static sqlite3_stmt *ss_ipair_dist, *ss_ipair_trades;
14 static sqlite3_stmt *ss_ite_buy, *ss_ite_sell;
16 #define MAX_LEGS (MAX_ROUTELEN-1)
19 int commodid, src_price, dst_price;
22 #define TRADES_PER_BLOCK 10
24 typedef struct TradesBlock {
25 struct TradesBlock *next;
26 Trade t[TRADES_PER_BLOCK];
29 static IslandPair ***ipairs; /* ipairs[sislandid][dislandid] */
31 typedef struct IslandTradeEnd {
32 struct IslandTradeEnd *next;
35 unsigned long generation;
40 IslandTradeEnd *src, *dst;
41 } IslandTradeEndHeads;
43 IslandTradeEndHeads *itradeends;
44 /* itradeends[islandid].{src,dst}->commodid etc. */
47 static unsigned long generation;
49 static int nconstraint_rows;
50 static int constraint_rows[1+2+3*MAX_LEGS];
51 static double constraint_coeffs[1+2+3*MAX_LEGS];
52 /* dummy0, src, dst, for_each_leg( [mass], [volume], [capital] ) */
54 static void add_constraint(int row, double coefficient) {
55 nconstraint_rows++; /* glpk indices start from 1 !!! */
56 constraint_rows [nconstraint_rows]= row;
57 constraint_coeffs[nconstraint_rows]= coefficient;
60 static void avail_c(const Trade *t, IslandTradeEnd **trades,
61 int price, const char *srcdst,
62 int islandid, sqlite3_stmt *ss_ite) {
63 /* find row number of trade availability constraint */
64 IslandTradeEnd *search;
66 for (search= *trades; search; search=search->next)
67 if (search->commodid==t->commodid && search->price==price)
69 /* not found, add new row */
71 search= mmalloc(sizeof(*search));
72 search->commodid= t->commodid;
74 search->next= *trades;
75 search->generation= 0;
77 SQL_BIND(ss_ite, 1, islandid);
78 SQL_BIND(ss_ite, 2, t->commodid);
79 SQL_BIND(ss_ite, 3, price);
80 assert(SQL_STEP(ss_ite));
81 search->qty= sqlite3_column_int(ss_ite, 0);
82 SQL_MUST( sqlite3_reset(ss_ite) );
87 if (search->generation != generation) {
88 search->rownum= lpx_add_rows(lp, 1);
89 lpx_set_row_bnds(lp, search->rownum, LPX_UP, 0, search->qty);
91 if (DEBUGP(value) || DEBUGP(check)) {
92 char *name= masprintf("%s_i%d_c%d_%d_all",
93 srcdst, islandid, t->commodid, price);
94 lpx_set_row_name(lp,search->rownum,name);
97 int nrows= lpx_get_num_rows(lp);
98 assert(search->rownum == nrows);
100 for (i=1; i<nrows; i++)
101 assert(strcmp(name, lpx_get_row_name(lp,i)));
105 search->generation= generation;
108 add_constraint(search->rownum, 1.0);
111 static int setup_leg_constraints(double max_thing, int legs, const char *wh) {
113 if (max_thing < 0 || !legs) return -1;
114 startrow= lpx_add_rows(lp, legs);
115 for (leg=0; leg<legs; leg++) {
116 int row= leg+startrow;
117 lpx_set_row_bnds(lp, row, LPX_UP, 0, max_thing);
119 char *name= masprintf("%s_%d",wh,leg);
120 lpx_set_row_name(lp,row,name);
127 static void add_leg_c(int startrow, int leg, double value) {
128 if (startrow<=0) return;
130 add_constraint(startrow+leg, value);
133 IslandPair *ipair_get(int si, int di) {
134 IslandPair *ip, **ipa;
136 assert(si < islandtablesz);
137 assert(di < islandtablesz);
139 if (!(ipa= ipairs[si])) {
140 ipa= ipairs[si]= mcalloc(sizeof(*ipa) * islandtablesz);
145 ipa[di]= ip= mmalloc(sizeof(*ip));
148 ip->route_tail_value= -1;
149 int inblock= TRADES_PER_BLOCK;
150 TradesBlock *block=0, **tail=&ip->trades;
152 debugf("VALUE ipair_get(%d,%d) running...\n", si,di);
153 SQL_MUST( sqlite3_bind_int(ss_ipair_dist, 1, si) );
154 SQL_MUST( sqlite3_bind_int(ss_ipair_dist, 2, di) );
155 assert(SQL_STEP(ss_ipair_dist));
156 int dist= sqlite3_column_int(ss_ipair_dist, 0);
157 ip->distance_loss_factor= pow(distance_loss_factor_per_league, dist);
158 sqlite3_reset(ss_ipair_dist);
160 SQL_MUST( sqlite3_bind_int(ss_ipair_trades, 1, si) );
161 SQL_MUST( sqlite3_bind_int(ss_ipair_trades, 2, di) );
163 while (SQL_STEP(ss_ipair_trades)) {
164 if (inblock == TRADES_PER_BLOCK) {
165 block= mmalloc(sizeof(*block));
172 for (i=0, irp=&block->t[inblock].commodid; i<3; i++, irp++)
173 *irp= sqlite3_column_int(ss_ipair_trades, i);
177 if (inblock < TRADES_PER_BLOCK)
178 block->t[inblock].commodid= -1;
180 sqlite3_reset(ss_ipair_trades);
185 double value_route(int nislands, const int *islands, int exclude_arbitrage) {
188 /* We need to construct the LP problem. GLPK talks
189 * about rows and columns, which are numbered from 1.
191 * Each column is a `structural variable' ie one of the entries in
192 * the objective function. In our case the set of structural
193 * variable is, for each port, the set of Trades which collect at
194 * that island. (We use `port' to mean `specific visit to an
195 * island' so if an island appears more than once so do its trades.)
196 * We don't need to worry about crossing with all the possible
197 * delivery locations as we always deliver on the first port.
198 * We will call such a structural variable a Flow, for brevity.
200 * We iterate over the possible Flows adding them as columns as we
201 * go, and also adding their entries to the various constraints.
203 * Each row is an `auxiliary variable' ie one of the constraints.
204 * We have two kinds of constraint:
205 * - mass/volume/capital: one constraint for each sailed leg
206 * (unless relevant constraint is not satisfied)
207 * - quantity of commodity available for collection
208 * or delivery at particular price and island
209 * The former are numbered predictably: we have first all the mass
210 * limits, then all the volume limits, then all the capital limits
211 * (as applicable) - one for each leg, ie one for each entry
212 * in islands except the first.
214 * The latter are added as needed and the row numbers are stored in
215 * a data structure for later reuse.
218 assert(nislands >= 1);
219 assert(++generation);
222 lp= lpx_create_prob();
223 lpx_set_obj_dir(lp, LPX_MAX);
224 lpx_set_int_parm(lp, LPX_K_MSGLEV, DEBUGP(lp) ? 3 : 1);
227 lpx_set_prob_name(lp,(char*)"value_route");
228 lpx_set_obj_name(lp,(char*)"profit");
231 int legs= nislands-1;
232 int mass_constraints= setup_leg_constraints(max_mass, legs, "mass");
233 int volu_constraints= setup_leg_constraints(max_volu, legs, "volu");
234 int capi_constraints= setup_leg_constraints(max_capi, legs, "capi");
236 double delay_slot_loss_factor= 1.0;
239 s++, delay_slot_loss_factor *= LOSS_FACTOR_PER_DELAY_SLOT) {
242 for (d= s + exclude_arbitrage;
247 for (already_d=s+1; already_d<d; already_d++)
248 if (islands[already_d] == di)
249 /* visited this island already since we left s, uninteresting */
253 /* route has returned to si, no need to think more about s */
256 /*----- actually add these trades to the LP problem -----*/
258 IslandPair *ip= ipair_get(islands[s], islands[d]);
259 TradesBlock *block= ip->trades;
260 int tradestodo= ip->ntrades;
265 int col= lpx_add_cols(lp,ip->ntrades);
267 double loss_factor= delay_slot_loss_factor * ip->distance_loss_factor;
268 debugf(" SOME i%d#%d..i%d#%d dslf=%g dlf=%g lf=%g\n",
270 delay_slot_loss_factor, ip->distance_loss_factor, loss_factor);
272 while (tradestodo-- >0) {
273 if (inblock >= TRADES_PER_BLOCK) {
277 Trade *t= &block->t[inblock++];
279 debugf(" TRADE i%d#%d..i%d#%d c%d %d-%d ",
280 si,s, di,d, t->commodid, t->src_price, t->dst_price);
284 avail_c(t, &itradeends[si].src, t->src_price, "src", si, ss_ite_sell);
285 avail_c(t, &itradeends[di].dst, t->dst_price, "dst", di, ss_ite_buy);
288 for (leg=s; leg<d; leg++) {
289 add_leg_c(mass_constraints,leg, commodstable[t->commodid].mass*1e-3);
290 add_leg_c(volu_constraints,leg, commodstable[t->commodid].volu*1e-3);
291 add_leg_c(capi_constraints,leg, t->src_price);
294 double unit_profit= t->dst_price * loss_factor - t->src_price;
295 debugf(" unit profit %f\n", unit_profit);
297 lpx_set_col_bnds(lp, col, LPX_LO, 0, 0);
298 lpx_set_obj_coef(lp, col, unit_profit);
299 lpx_set_mat_col(lp, col, nconstraint_rows,
300 constraint_rows, constraint_coeffs);
303 char *name= masprintf("c%d_p%d_%d_p%d_%d",
304 t->commodid, s, t->src_price, d, t->dst_price);
305 lpx_set_col_name(lp, col, name);
310 } /* while (tradestodo-- >0) */
312 /*----- that's done adding these trades to the LP problem -----*/
321 if (lpx_get_num_cols(lp)) {
323 lpx_write_cpxlp(lp, (char*)DEBUG_DEV);
325 int ipr= lpx_simplex(lp);
326 assert(ipr==LPX_E_OK);
329 lpx_print_sol(lp, (char*)DEBUG_DEV);
331 int lpst= lpx_get_status(lp);
332 assert(lpst == LPX_OPT);
333 profit= lpx_get_obj_val(lp);
342 void setup_value(void) {
346 commodstablesz= sql_single_int("SELECT max(commodid) FROM commods") + 1;
347 commodstable= mmalloc(sizeof(*commodstable)*commodstablesz);
348 for (i=0; i<commodstablesz; i++)
349 commodstable[i].mass= commodstable[i].volu= -1;
351 itradeends= mcalloc(sizeof(*itradeends) * islandtablesz);
354 "SELECT commodid,unitmass,unitvolume FROM commods");
355 while (SQL_STEP(sst)) {
356 int id= sqlite3_column_int(sst,0);
357 assert(id>=0 && id<commodstablesz);
358 commodstable[id].mass= sqlite3_column_int(sst,1);
359 commodstable[id].volu= sqlite3_column_int(sst,2);
361 sqlite3_finalize(sst);
363 SQL_PREPARE(ss_ipair_dist,
364 " SELECT dist FROM dists\n"
365 " WHERE aiid=? and biid=?");
367 SQL_PREPARE(ss_ipair_trades,
369 " sell.commodid commodid,\n"
370 " sell.price src_price,\n"
371 " buy.price dst_price\n"
372 " FROM sell JOIN buy\n"
373 " ON sell.commodid = buy.commodid\n"
374 " AND buy.price > sell.price\n"
375 " WHERE sell.islandid=?\n"
376 " AND buy.islandid=?");
379 SQL_PREPARE(ss_ite_##bs, \
383 " WHERE islandid=?\n" \
384 " AND commodid=?\n" \
390 ipairs= mcalloc(sizeof(*ipairs) * islandtablesz);