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;
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_BIND(ss_ite, 1, islandid);
83 SQL_BIND(ss_ite, 2, t->commodid);
84 SQL_BIND(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_c%d_%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<3; 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 double 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);
237 lpx_set_int_parm(lp, LPX_K_MSGLEV, DEBUGP(lp) ? 3 : 1);
240 lpx_set_prob_name(lp,(char*)"value_route");
241 lpx_set_obj_name(lp,(char*)"profit");
244 int legs= nislands-1;
245 int mass_constraints= setup_leg_constraints(max_mass, legs, "mass");
246 int volu_constraints= setup_leg_constraints(max_volu, legs, "volu");
247 int capi_constraints= setup_leg_constraints(max_capi, legs, "capi");
249 double delay_slot_loss_factor= 1.0;
252 s++, delay_slot_loss_factor *= LOSS_FACTOR_PER_DELAY_SLOT) {
255 for (d=s; d<nislands; d++) {
258 for (already_d=s+1; already_d<d; already_d++)
259 if (islands[already_d] == di)
260 /* visited this island already since we left s, uninteresting */
264 /* route has returned to si, no need to think more about s */
267 /*----- actually add these trades to the LP problem -----*/
269 IslandPair *ip= ipair_get(islands[s], islands[d]);
270 TradesBlock *block= ip->trades;
271 int tradestodo= ip->ntrades;
276 int col= lpx_add_cols(lp,ip->ntrades);
278 double loss_factor= delay_slot_loss_factor * ip->distance_loss_factor;
280 while (tradestodo-- >0) {
281 if (inblock >= TRADES_PER_BLOCK) {
285 Trade *t= &block->t[inblock++];
287 debugf(" TRADE %d#%d..%d#%d %d %d-%d\n",
288 si,s, di,d, t->commodid, t->src_price, t->dst_price);
292 avail_c(t, &iteps[s]->collect, t->src_price,"src", si, ss_ite_sell);
293 avail_c(t, &iteps[d]->deliver, t->dst_price,"dst", di, ss_ite_buy);
296 for (leg=s; leg<d; leg++) {
297 add_leg_c(mass_constraints, leg, commodstable[t->commodid].mass);
298 add_leg_c(volu_constraints, leg, commodstable[t->commodid].volu);
299 add_leg_c(capi_constraints, leg, t->src_price);
302 lpx_set_col_bnds(lp, col, LPX_LO, 0, 0);
303 lpx_set_obj_coef(lp, col,
304 (t->dst_price - t->src_price) * loss_factor);
305 lpx_set_mat_col(lp, col, nconstraint_rows,
306 constraint_rows, constraint_coeffs);
308 char *name= masprintf("c%d_p%d_%d_p%d_%d",
309 t->commodid, s, t->src_price, d, t->dst_price);
310 lpx_set_col_name(lp, col, name);
315 } /* while (tradestodo-- >0) */
317 /*----- that's done adding these trades to the LP problem -----*/
325 lpx_write_cpxlp(lp, (char*)"/dev/stdout");
327 int ipr= lpx_interior(lp);
328 assert(ipr==LPX_E_OK);
331 lpx_print_ips(lp, (char*)"/dev/stdout");
333 assert(lpx_ipt_status(lp) == LPX_T_OPT);
334 double profit= lpx_ipt_obj_val(lp);
342 void setup_value(void) {
346 nislands= sql_single_int("SELECT max(islandid) FROM islands") + 1;
347 debugf("VALUE nislands=%d\n",nislands);
349 commodstablesz= sql_single_int("SELECT max(commodid) FROM commods") + 1;
350 commodstable= mmalloc(sizeof(*commodstable)*commodstablesz);
351 for (i=0; i<commodstablesz; i++)
352 commodstable[i].mass= commodstable[i].volu= -1;
355 "SELECT commodid,unitmass,unitvolume FROM commods");
356 while (SQL_STEP(sst)) {
357 int id= sqlite3_column_int(sst,0);
358 assert(id>=0 && id<commodstablesz);
359 commodstable[id].mass= sqlite3_column_int(sst,1);
360 commodstable[id].volu= sqlite3_column_int(sst,2);
362 sqlite3_finalize(sst);
364 SQL_PREPARE(ss_ipair_dist,
365 " SELECT dist FROM dists\n"
366 " WHERE aiid=? and biid=?");
368 SQL_PREPARE(ss_ipair_trades,
370 " sell.commodid commodid,\n"
371 " sell.price src_price,\n"
372 " buy.price dst_price\n"
373 " FROM sell JOIN buy\n"
374 " ON sell.commodid = buy.commodid\n"
375 " AND buy.price > sell.price\n"
376 " WHERE sell.islandid=?\n"
377 " AND buy.islandid=?");
380 SQL_PREPARE(ss_ite_##bs, \
384 " WHERE islandid=?\n" \
385 " AND commodid=?\n" \
391 ipairs= mcalloc(sizeof(*ipairs) * nislands);