8 DEBUG_DEFINE_DEBUGF(value);
10 typedef struct { int mass, volu; } CommodInfo;
11 static int commodstablesz;
12 static CommodInfo *commodstable;
14 static sqlite3_stmt *ss_ipair_dist, *ss_ipair_trades;
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 } IslandTradeEnd, *IslandDirnTradeEnds;
46 IslandDirnTradeEnds collect, deliver;
49 static struct obstack ites_obstack;
52 static int nconstraint_rows;
53 static int constraint_rows[1+2+3*MAX_LEGS];
54 static double constraint_coeffs[1+2+3*MAX_LEGS];
55 /* dummy0, src, dst, for_each_leg( [mass], [volume], [capital] ) */
57 static void add_constraint(int row, double coefficient) {
58 nconstraint_rows++; /* glpk indices start from 1 !!! */
59 constraint_rows [nconstraint_rows]= row;
60 constraint_coeffs[nconstraint_rows]= coefficient;
63 static void avail_constraint(const Trade *t, IslandDirnTradeEnds *trades,
64 int price, int qty, const char *srcdst) {
65 /* find row number of trade availability constraint */
66 IslandTradeEnd *search;
68 for (search= *trades; search; search=search->next)
69 if (search->commodid==t->commodid && search->price==price) {
70 assert(search->qty == qty);
73 /* not found, add new row */
74 search= obstack_alloc(&ites_obstack, sizeof(*search));
75 search->commodid= t->commodid;
78 search->rownum= lpx_add_rows(lp, 1);
79 search->next= *trades;
81 char *name= masprintf("%s_commod%d_price%d",srcdst,t->commodid,price);
82 lpx_set_row_name(lp,search->rownum,name);
87 int rownum= search->rownum;
89 lpx_set_row_bnds(lp, rownum, LPX_UP, 0, qty);
90 add_constraint(rownum, 1.0);
93 static int setup_leg_constraints(double max_thing, int legs, const char *wh) {
95 if (max_thing < 0 || !legs) return -1;
96 startrow= lpx_add_rows(lp, legs);
97 for (leg=0; leg<nislands-1; leg++) {
98 int row= leg+startrow;
99 lpx_set_row_bnds(lp, row, LPX_UP, 0, max_thing);
101 char *name= masprintf("max_leg%d_%s",leg,wh);
102 lpx_set_row_name(lp,row,name);
109 static void add_leg_c(int startrow, int leg, double value) {
110 if (startrow<=0) return;
111 add_constraint(startrow+leg, value);
114 static IslandPair *ipair_get(int si, int di) {
115 IslandPair *ip, **ipa;
117 assert(si < nislands);
118 assert(di < nislands);
120 if (!(ipa= ipairs[si])) {
121 ipa= ipairs[si]= mcalloc(sizeof(*ipa) * nislands);
126 ipa[di]= ip= mmalloc(sizeof(*ip));
129 int inblock= TRADES_PER_BLOCK;
130 TradesBlock *block= 0;
132 debugf("VALUE ipair_get(%d,%d) running...\n", si,di);
133 SQL_MUST( sqlite3_bind_int(ss_ipair_dist, 1, si) );
134 SQL_MUST( sqlite3_bind_int(ss_ipair_dist, 2, di) );
135 assert(SQL_STEP(ss_ipair_dist));
136 int dist= sqlite3_column_int(ss_ipair_dist, 0);
137 ip->distance_loss_factor= pow(distance_loss_factor_per_league, dist);
138 sqlite3_reset(ss_ipair_dist);
140 SQL_MUST( sqlite3_bind_int(ss_ipair_trades, 1, si) );
141 SQL_MUST( sqlite3_bind_int(ss_ipair_trades, 2, di) );
143 while (SQL_STEP(ss_ipair_trades)) {
144 if (inblock == TRADES_PER_BLOCK) {
145 block= mmalloc(sizeof(*block));
146 block->next= ip->trades;
151 for (i=0, irp=&block->t[inblock].commodid; i<5; i++, irp++)
152 *irp= sqlite3_column_int(ss_ipair_trades, i);
156 if (inblock < TRADES_PER_BLOCK)
157 block->t[inblock].commodid= -1;
159 sqlite3_reset(ss_ipair_trades);
164 void value_route(int nislands, const int *islands) {
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);
199 char *free_to_reset_obstack= obstack_alloc(&ites_obstack, 1);
202 IslandTradeEnds ites[nislands], *iteps[nislands];
204 for (s=0; s<nislands; s++) {
205 IslandTradeEnds *ite;
208 for (i=0, ite=ites; i<nites; i++, ite++)
209 if (ite->islandid==si)
211 /* not found, add new */
212 assert(ite == &ites[nites]);
214 ite->collect= ite->deliver= 0;
221 lp= lpx_create_prob();
222 lpx_set_obj_dir(lp, LPX_MAX);
224 lpx_set_prob_name(lp,(char*)"value_route");
225 lpx_set_obj_name(lp,(char*)"profit");
228 int legs= nislands-1;
229 int mass_constraints= setup_leg_constraints(max_mass, legs, "mass");
230 int volu_constraints= setup_leg_constraints(max_volu, legs, "volu");
231 int capi_constraints= setup_leg_constraints(max_capi, legs, "capi");
233 double delay_slot_loss_factor= 1.0;
236 s++, delay_slot_loss_factor *= LOSS_FACTOR_PER_DELAY_SLOT) {
239 for (d=s; d<nislands; d++) {
242 for (already_d=s+1; already_d<d; already_d++)
243 if (islands[already_d] == di)
244 /* visited this island already since we left s, uninteresting */
247 /* route has returned to si, no need to think more about s */
250 /*----- actually add these trades to the LP problem -----*/
252 IslandPair *ip= ipair_get(islands[s], islands[d]);
253 TradesBlock *block= ip->trades;
254 int tradestodo= ip->ntrades;
256 int col= lpx_add_cols(lp,ip->ntrades);
258 double loss_factor= delay_slot_loss_factor * ip->distance_loss_factor;
260 while (tradestodo-- >0) {
261 if (inblock >= TRADES_PER_BLOCK) {
265 Trade *t= &block->t[inblock++];
267 debugf(" TRADE %d#%d..%d#%d %d %d-%d\n",
268 si,s, di,d, t->commodid, t->src_price, t->dst_price);
272 avail_constraint(t, &iteps[s]->collect, t->src_price,t->src_qty,"src");
273 avail_constraint(t, &iteps[d]->deliver, t->dst_price,t->dst_qty,"dst");
276 for (leg=s; leg<d; leg++) {
277 add_leg_c(mass_constraints, leg, commodstable[t->commodid].mass);
278 add_leg_c(volu_constraints, leg, commodstable[t->commodid].volu);
279 add_leg_c(capi_constraints, leg, t->src_price);
282 lpx_set_col_bnds(lp, col, LPX_LO, 0, 0);
283 lpx_set_obj_coef(lp, col,
284 (t->dst_price - t->src_price) * loss_factor);
285 lpx_set_mat_col(lp, col, nconstraint_rows,
286 constraint_rows, constraint_coeffs);
288 char *name= masprintf("trade_commod%d_port%d_at%d_port%d_at%d",
289 t->commodid, s, t->src_price, d, t->dst_price);
290 lpx_set_col_name(lp, col, name);
293 } /* while (tradestodo-- >0) */
295 /*----- that's done adding these trades to the LP problem -----*/
305 obstack_free(&ites_obstack, free_to_reset_obstack);
308 void setup_value(void) {
312 #define obstack_chunk_alloc mmalloc
313 #define obstack_chunk_free free
314 obstack_init(&ites_obstack);
316 nislands= sql_single_int("SELECT max(islandid) FROM islands") + 1;
317 debugf("VALUE nislands=%d\n",nislands);
319 commodstablesz= sql_single_int("SELECT max(commodid) FROM commods") + 1;
320 commodstable= mmalloc(sizeof(*commodstable)*commodstablesz);
321 for (i=0; i<commodstablesz; i++)
322 commodstable[i].mass= commodstable[i].volu= -1;
324 SQL_MUST( sqlite3_prepare(db,
325 "SELECT commodid,unitmass,unitvolume FROM commods", -1,&sst,0) );
326 while (SQL_STEP(sst)) {
327 int id= sqlite3_column_int(sst,0);
328 assert(id>=0 && id<commodstablesz);
329 commodstable[id].mass= sqlite3_column_int(sst,1);
330 commodstable[id].volu= sqlite3_column_int(sst,2);
332 sqlite3_finalize(sst);
334 SQL_MUST( sqlite3_prepare(db,
336 " sell.commodid commodid,\n"
337 " sell.price src_price,\n"
338 " sum(sell.qty) src_qty,\n"
339 " buy.price dst_price,\n"
340 " sum(buy.qty) dst_qty\n"
341 " FROM sell JOIN buy\n"
342 " ON sell.commodid = buy.commodid\n"
343 " AND buy.price > sell.price\n"
344 " WHERE sell.islandid=?\n"
345 " AND buy.islandid=?\n"
346 " GROUP BY sell.commodid, sell.price, buy.price",
347 -1, &ss_ipair_trades, 0) );
349 SQL_MUST( sqlite3_prepare(db,
350 " SELECT dist from dists where aiid=? and biid=?",
351 -1, &ss_ipair_dist, 0) );
353 ipairs= mcalloc(sizeof(*ipairs) * nislands);