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, src_qty, dst_price, dst_qty;
22 #define TRADES_PER_BLOCK 10
24 typedef struct TradesBlock{
25 struct TradesBlock *next;
26 Trade t[TRADES_PER_BLOCK];
30 double distance_loss_factor;
36 IslandPair ***ipairs; /* ipairs[sislandid][dislandid] */
38 typedef struct IslandTradeEnd {
39 struct IslandTradeEnd *next;
42 unsigned long generation;
44 } IslandTradeEnd, *IslandDirnTradeEnds;
48 IslandDirnTradeEnds collect, deliver;
52 static unsigned long generation;
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] ) */
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;
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;
71 for (search= *trades; search; search=search->next)
72 if (search->commodid==t->commodid && search->price==price)
74 /* not found, add new row */
76 search= mmalloc(sizeof(*search));
77 search->commodid= t->commodid;
79 search->next= *trades;
80 search->generation= 0;
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) );
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);
97 char *name= masprintf("%s_commod%d_price%d",srcdst,t->commodid,price);
98 lpx_set_row_name(lp,search->rownum,name);
101 search->generation= generation;
104 add_constraint(search->rownum, 1.0);
107 static int setup_leg_constraints(double max_thing, int legs, const char *wh) {
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);
115 char *name= masprintf("max_leg%d_%s",leg,wh);
116 lpx_set_row_name(lp,row,name);
123 static void add_leg_c(int startrow, int leg, double value) {
124 if (startrow<=0) return;
126 add_constraint(startrow+leg, value);
129 static IslandPair *ipair_get(int si, int di) {
130 IslandPair *ip, **ipa;
132 assert(si < nislands);
133 assert(di < nislands);
135 if (!(ipa= ipairs[si])) {
136 ipa= ipairs[si]= mcalloc(sizeof(*ipa) * nislands);
141 ipa[di]= ip= mmalloc(sizeof(*ip));
144 int inblock= TRADES_PER_BLOCK;
145 TradesBlock *block= 0;
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);
155 SQL_MUST( sqlite3_bind_int(ss_ipair_trades, 1, si) );
156 SQL_MUST( sqlite3_bind_int(ss_ipair_trades, 2, di) );
158 while (SQL_STEP(ss_ipair_trades)) {
159 if (inblock == TRADES_PER_BLOCK) {
160 block= mmalloc(sizeof(*block));
161 block->next= ip->trades;
166 for (i=0, irp=&block->t[inblock].commodid; i<5; i++, irp++)
167 *irp= sqlite3_column_int(ss_ipair_trades, i);
171 if (inblock < TRADES_PER_BLOCK)
172 block->t[inblock].commodid= -1;
174 sqlite3_reset(ss_ipair_trades);
179 void value_route(int nislands, const int *islands) {
182 /* We need to construct the LP problem. GLPK talks
183 * about rows and columns, which are numbered from 1.
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.
194 * We iterate over the possible Flows adding them as columns as we
195 * go, and also adding their entries to the various constraints.
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.
208 * The latter are added as needed and the row numbers are stored in
209 * a data structure for later reuse.
212 assert(nislands >= 1);
213 assert(++generation);
216 IslandTradeEnds ites[nislands], *iteps[nislands];
218 for (s=0; s<nislands; s++) {
219 IslandTradeEnds *ite;
222 for (i=0, ite=ites; i<nites; i++, ite++)
223 if (ite->islandid==si)
225 /* not found, add new */
226 assert(ite == &ites[nites]);
228 ite->collect= ite->deliver= 0;
235 lp= lpx_create_prob();
236 lpx_set_obj_dir(lp, LPX_MAX);
238 lpx_set_prob_name(lp,(char*)"value_route");
239 lpx_set_obj_name(lp,(char*)"profit");
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");
247 double delay_slot_loss_factor= 1.0;
250 s++, delay_slot_loss_factor *= LOSS_FACTOR_PER_DELAY_SLOT) {
253 for (d=s; d<nislands; 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 */
262 /* route has returned to si, no need to think more about s */
265 /*----- actually add these trades to the LP problem -----*/
267 IslandPair *ip= ipair_get(islands[s], islands[d]);
268 TradesBlock *block= ip->trades;
269 int tradestodo= ip->ntrades;
274 int col= lpx_add_cols(lp,ip->ntrades);
276 double loss_factor= delay_slot_loss_factor * ip->distance_loss_factor;
278 while (tradestodo-- >0) {
279 if (inblock >= TRADES_PER_BLOCK) {
283 Trade *t= &block->t[inblock++];
285 debugf(" TRADE %d#%d..%d#%d %d %d-%d\n",
286 si,s, di,d, t->commodid, t->src_price, t->dst_price);
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);
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);
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);
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);
311 } /* while (tradestodo-- >0) */
313 /*----- that's done adding these trades to the LP problem -----*/
324 void setup_value(void) {
328 nislands= sql_single_int("SELECT max(islandid) FROM islands") + 1;
329 debugf("VALUE nislands=%d\n",nislands);
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;
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);
344 sqlite3_finalize(sst);
346 SQL_MUST( sqlite3_prepare(db,
347 " SELECT dist from dists where aiid=? and biid=?",
348 -1, &ss_ipair_dist, 0) );
350 SQL_MUST( sqlite3_prepare(db,
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) );
363 SQL_MUST( sqlite3_prepare(db, \
367 " WHERE islandid=?\n" \
368 " AND commodid=?\n" \
370 -1, &ss_ite_##bs, 0) );
375 ipairs= mcalloc(sizeof(*ipairs) * nislands);