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];
30 double distance_loss_factor;
35 IslandPair ***ipairs; /* ipairs[sislandid][dislandid] */
37 typedef struct IslandTradeEnd {
38 struct IslandTradeEnd *next;
41 unsigned long generation;
43 } IslandTradeEnd, *IslandDirnTradeEnds;
47 IslandDirnTradeEnds collect, deliver;
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, IslandDirnTradeEnds *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)
73 /* not found, add new row */
75 search= mmalloc(sizeof(*search));
76 search->commodid= t->commodid;
78 search->next= *trades;
79 search->generation= 0;
81 SQL_BIND(ss_ite, 1, islandid);
82 SQL_BIND(ss_ite, 2, t->commodid);
83 SQL_BIND(ss_ite, 3, price);
84 assert(SQL_STEP(ss_ite));
85 search->qty= sqlite3_column_int(ss_ite, 0);
86 SQL_MUST( sqlite3_reset(ss_ite) );
91 if (search->generation != generation) {
92 search->rownum= lpx_add_rows(lp, 1);
93 lpx_set_row_bnds(lp, search->rownum, LPX_UP, 0, search->qty);
96 char *name= masprintf("%s_c%d_%d",srcdst,t->commodid,price);
97 lpx_set_row_name(lp,search->rownum,name);
100 search->generation= generation;
103 add_constraint(search->rownum, 1.0);
106 static int setup_leg_constraints(double max_thing, int legs, const char *wh) {
108 if (max_thing < 0 || !legs) return -1;
109 startrow= lpx_add_rows(lp, legs);
110 for (leg=0; leg<legs; leg++) {
111 int row= leg+startrow;
112 lpx_set_row_bnds(lp, row, LPX_UP, 0, max_thing);
114 char *name= masprintf("max_leg%d_%s",leg,wh);
115 lpx_set_row_name(lp,row,name);
122 static void add_leg_c(int startrow, int leg, double value) {
123 if (startrow<=0) return;
125 add_constraint(startrow+leg, value);
128 static IslandPair *ipair_get(int si, int di) {
129 IslandPair *ip, **ipa;
131 assert(si < islandtablesz);
132 assert(di < islandtablesz);
134 if (!(ipa= ipairs[si])) {
135 ipa= ipairs[si]= mcalloc(sizeof(*ipa) * islandtablesz);
140 ipa[di]= ip= mmalloc(sizeof(*ip));
143 int inblock= TRADES_PER_BLOCK;
144 TradesBlock *block= 0;
146 debugf("VALUE ipair_get(%d,%d) running...\n", si,di);
147 SQL_MUST( sqlite3_bind_int(ss_ipair_dist, 1, si) );
148 SQL_MUST( sqlite3_bind_int(ss_ipair_dist, 2, di) );
149 assert(SQL_STEP(ss_ipair_dist));
150 int dist= sqlite3_column_int(ss_ipair_dist, 0);
151 ip->distance_loss_factor= pow(distance_loss_factor_per_league, dist);
152 sqlite3_reset(ss_ipair_dist);
154 SQL_MUST( sqlite3_bind_int(ss_ipair_trades, 1, si) );
155 SQL_MUST( sqlite3_bind_int(ss_ipair_trades, 2, di) );
157 while (SQL_STEP(ss_ipair_trades)) {
158 if (inblock == TRADES_PER_BLOCK) {
159 block= mmalloc(sizeof(*block));
160 block->next= ip->trades;
165 for (i=0, irp=&block->t[inblock].commodid; i<3; i++, irp++)
166 *irp= sqlite3_column_int(ss_ipair_trades, i);
170 if (inblock < TRADES_PER_BLOCK)
171 block->t[inblock].commodid= -1;
173 sqlite3_reset(ss_ipair_trades);
178 double value_route(int nislands, const int *islands) {
181 /* We need to construct the LP problem. GLPK talks
182 * about rows and columns, which are numbered from 1.
184 * Each column is a `structural variable' ie one of the entries in
185 * the objective function. In our case the set of structural
186 * variable is, for each port, the set of Trades which collect at
187 * that island. (We use `port' to mean `specific visit to an
188 * island' so if an island appears more than once so do its trades.)
189 * We don't need to worry about crossing with all the possible
190 * delivery locations as we always deliver on the first port.
191 * We will call such a structural variable a Flow, for brevity.
193 * We iterate over the possible Flows adding them as columns as we
194 * go, and also adding their entries to the various constraints.
196 * Each row is an `auxiliary variable' ie one of the constraints.
197 * We have two kinds of constraint:
198 * - mass/volume/capital: one constraint for each sailed leg
199 * (unless relevant constraint is not satisfied)
200 * - quantity of commodity available for collection
201 * or delivery at particular price and island
202 * The former are numbered predictably: we have first all the mass
203 * limits, then all the volume limits, then all the capital limits
204 * (as applicable) - one for each leg, ie one for each entry
205 * in islands except the first.
207 * The latter are added as needed and the row numbers are stored in
208 * a data structure for later reuse.
211 assert(nislands >= 1);
212 assert(++generation);
215 IslandTradeEnds ites[nislands], *iteps[nislands];
217 for (s=0; s<nislands; s++) {
218 IslandTradeEnds *ite;
221 for (i=0, ite=ites; i<nites; i++, ite++)
222 if (ite->islandid==si)
224 /* not found, add new */
225 assert(ite == &ites[nites]);
227 ite->collect= ite->deliver= 0;
234 lp= lpx_create_prob();
235 lpx_set_obj_dir(lp, LPX_MAX);
236 lpx_set_int_parm(lp, LPX_K_MSGLEV, DEBUGP(lp) ? 3 : 1);
239 lpx_set_prob_name(lp,(char*)"value_route");
240 lpx_set_obj_name(lp,(char*)"profit");
243 int legs= nislands-1;
244 int mass_constraints= setup_leg_constraints(max_mass, legs, "mass");
245 int volu_constraints= setup_leg_constraints(max_volu, legs, "volu");
246 int capi_constraints= setup_leg_constraints(max_capi, legs, "capi");
248 double delay_slot_loss_factor= 1.0;
251 s++, delay_slot_loss_factor *= LOSS_FACTOR_PER_DELAY_SLOT) {
254 for (d=s; d<nislands; d++) {
257 for (already_d=s+1; already_d<d; already_d++)
258 if (islands[already_d] == di)
259 /* visited this island already since we left s, uninteresting */
263 /* route has returned to si, no need to think more about s */
266 /*----- actually add these trades to the LP problem -----*/
268 IslandPair *ip= ipair_get(islands[s], islands[d]);
269 TradesBlock *block= ip->trades;
270 int tradestodo= ip->ntrades;
275 int col= lpx_add_cols(lp,ip->ntrades);
277 double loss_factor= delay_slot_loss_factor * ip->distance_loss_factor;
279 while (tradestodo-- >0) {
280 if (inblock >= TRADES_PER_BLOCK) {
284 Trade *t= &block->t[inblock++];
286 debugf(" TRADE %d#%d..%d#%d %d %d-%d\n",
287 si,s, di,d, t->commodid, t->src_price, t->dst_price);
291 avail_c(t, &iteps[s]->collect, t->src_price,"src", si, ss_ite_sell);
292 avail_c(t, &iteps[d]->deliver, t->dst_price,"dst", di, ss_ite_buy);
295 for (leg=s; leg<d; leg++) {
296 add_leg_c(mass_constraints, leg, commodstable[t->commodid].mass);
297 add_leg_c(volu_constraints, leg, commodstable[t->commodid].volu);
298 add_leg_c(capi_constraints, leg, t->src_price);
301 double unit_profit= (t->dst_price - t->src_price) * loss_factor;
302 debugf(" unit profit %f\n", unit_profit);
304 lpx_set_col_bnds(lp, col, LPX_LO, 0, 0);
305 lpx_set_obj_coef(lp, col, unit_profit);
306 lpx_set_mat_col(lp, col, nconstraint_rows,
307 constraint_rows, constraint_coeffs);
310 char *name= masprintf("c%d_p%d_%d_p%d_%d",
311 t->commodid, s, t->src_price, d, t->dst_price);
312 lpx_set_col_name(lp, col, name);
317 } /* while (tradestodo-- >0) */
319 /*----- that's done adding these trades to the LP problem -----*/
328 if (lpx_get_num_cols(lp)) {
330 lpx_write_cpxlp(lp, (char*)DEBUG_DEV);
332 int ipr= lpx_interior(lp);
333 assert(ipr==LPX_E_OK);
336 lpx_print_ips(lp, (char*)DEBUG_DEV);
338 assert(lpx_ipt_status(lp) == LPX_T_OPT);
339 profit= lpx_ipt_obj_val(lp);
348 void setup_value(void) {
352 commodstablesz= sql_single_int("SELECT max(commodid) FROM commods") + 1;
353 commodstable= mmalloc(sizeof(*commodstable)*commodstablesz);
354 for (i=0; i<commodstablesz; i++)
355 commodstable[i].mass= commodstable[i].volu= -1;
358 "SELECT commodid,unitmass,unitvolume FROM commods");
359 while (SQL_STEP(sst)) {
360 int id= sqlite3_column_int(sst,0);
361 assert(id>=0 && id<commodstablesz);
362 commodstable[id].mass= sqlite3_column_int(sst,1);
363 commodstable[id].volu= sqlite3_column_int(sst,2);
365 sqlite3_finalize(sst);
367 SQL_PREPARE(ss_ipair_dist,
368 " SELECT dist FROM dists\n"
369 " WHERE aiid=? and biid=?");
371 SQL_PREPARE(ss_ipair_trades,
373 " sell.commodid commodid,\n"
374 " sell.price src_price,\n"
375 " buy.price dst_price\n"
376 " FROM sell JOIN buy\n"
377 " ON sell.commodid = buy.commodid\n"
378 " AND buy.price > sell.price\n"
379 " WHERE sell.islandid=?\n"
380 " AND buy.islandid=?");
383 SQL_PREPARE(ss_ite_##bs, \
387 " WHERE islandid=?\n" \
388 " AND commodid=?\n" \
394 ipairs= mcalloc(sizeof(*ipairs) * islandtablesz);