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;
112 add_constraint(startrow+leg, value);
115 static IslandPair *ipair_get(int si, int di) {
116 IslandPair *ip, **ipa;
118 assert(si < nislands);
119 assert(di < nislands);
121 if (!(ipa= ipairs[si])) {
122 ipa= ipairs[si]= mcalloc(sizeof(*ipa) * nislands);
127 ipa[di]= ip= mmalloc(sizeof(*ip));
130 int inblock= TRADES_PER_BLOCK;
131 TradesBlock *block= 0;
133 debugf("VALUE ipair_get(%d,%d) running...\n", si,di);
134 SQL_MUST( sqlite3_bind_int(ss_ipair_dist, 1, si) );
135 SQL_MUST( sqlite3_bind_int(ss_ipair_dist, 2, di) );
136 assert(SQL_STEP(ss_ipair_dist));
137 int dist= sqlite3_column_int(ss_ipair_dist, 0);
138 ip->distance_loss_factor= pow(distance_loss_factor_per_league, dist);
139 sqlite3_reset(ss_ipair_dist);
141 SQL_MUST( sqlite3_bind_int(ss_ipair_trades, 1, si) );
142 SQL_MUST( sqlite3_bind_int(ss_ipair_trades, 2, di) );
144 while (SQL_STEP(ss_ipair_trades)) {
145 if (inblock == TRADES_PER_BLOCK) {
146 block= mmalloc(sizeof(*block));
147 block->next= ip->trades;
152 for (i=0, irp=&block->t[inblock].commodid; i<5; i++, irp++)
153 *irp= sqlite3_column_int(ss_ipair_trades, i);
157 if (inblock < TRADES_PER_BLOCK)
158 block->t[inblock].commodid= -1;
160 sqlite3_reset(ss_ipair_trades);
165 void value_route(int nislands, const int *islands) {
168 /* We need to construct the LP problem. GLPK talks
169 * about rows and columns, which are numbered from 1.
171 * Each column is a `structural variable' ie one of the entries in
172 * the objective function. In our case the set of structural
173 * variable is, for each port, the set of Trades which collect at
174 * that island. (We use `port' to mean `specific visit to an
175 * island' so if an island appears more than once so do its trades.)
176 * We don't need to worry about crossing with all the possible
177 * delivery locations as we always deliver on the first port.
178 * We will call such a structural variable a Flow, for brevity.
180 * We iterate over the possible Flows adding them as columns as we
181 * go, and also adding their entries to the various constraints.
183 * Each row is an `auxiliary variable' ie one of the constraints.
184 * We have two kinds of constraint:
185 * - mass/volume/capital: one constraint for each sailed leg
186 * (unless relevant constraint is not satisfied)
187 * - quantity of commodity available for collection
188 * or delivery at particular price and island
189 * The former are numbered predictably: we have first all the mass
190 * limits, then all the volume limits, then all the capital limits
191 * (as applicable) - one for each leg, ie one for each entry
192 * in islands except the first.
194 * The latter are added as needed and the row numbers are stored in
195 * a data structure for later reuse.
198 assert(nislands >= 1);
200 char *free_to_reset_obstack= obstack_alloc(&ites_obstack, 1);
203 IslandTradeEnds ites[nislands], *iteps[nislands];
205 for (s=0; s<nislands; s++) {
206 IslandTradeEnds *ite;
209 for (i=0, ite=ites; i<nites; i++, ite++)
210 if (ite->islandid==si)
212 /* not found, add new */
213 assert(ite == &ites[nites]);
215 ite->collect= ite->deliver= 0;
222 lp= lpx_create_prob();
223 lpx_set_obj_dir(lp, LPX_MAX);
225 lpx_set_prob_name(lp,(char*)"value_route");
226 lpx_set_obj_name(lp,(char*)"profit");
229 int legs= nislands-1;
230 int mass_constraints= setup_leg_constraints(max_mass, legs, "mass");
231 int volu_constraints= setup_leg_constraints(max_volu, legs, "volu");
232 int capi_constraints= setup_leg_constraints(max_capi, legs, "capi");
234 double delay_slot_loss_factor= 1.0;
237 s++, delay_slot_loss_factor *= LOSS_FACTOR_PER_DELAY_SLOT) {
240 for (d=s; d<nislands; d++) {
243 for (already_d=s+1; already_d<d; already_d++)
244 if (islands[already_d] == di)
245 /* visited this island already since we left s, uninteresting */
249 /* route has returned to si, no need to think more about s */
252 /*----- actually add these trades to the LP problem -----*/
254 IslandPair *ip= ipair_get(islands[s], islands[d]);
255 TradesBlock *block= ip->trades;
256 int tradestodo= ip->ntrades;
261 int col= lpx_add_cols(lp,ip->ntrades);
263 double loss_factor= delay_slot_loss_factor * ip->distance_loss_factor;
265 while (tradestodo-- >0) {
266 if (inblock >= TRADES_PER_BLOCK) {
270 Trade *t= &block->t[inblock++];
272 debugf(" TRADE %d#%d..%d#%d %d %d-%d\n",
273 si,s, di,d, t->commodid, t->src_price, t->dst_price);
277 avail_constraint(t, &iteps[s]->collect, t->src_price,t->src_qty,"src");
278 avail_constraint(t, &iteps[d]->deliver, t->dst_price,t->dst_qty,"dst");
281 for (leg=s; leg<d; leg++) {
282 add_leg_c(mass_constraints, leg, commodstable[t->commodid].mass);
283 add_leg_c(volu_constraints, leg, commodstable[t->commodid].volu);
284 add_leg_c(capi_constraints, leg, t->src_price);
287 lpx_set_col_bnds(lp, col, LPX_LO, 0, 0);
288 lpx_set_obj_coef(lp, col,
289 (t->dst_price - t->src_price) * loss_factor);
290 lpx_set_mat_col(lp, col, nconstraint_rows,
291 constraint_rows, constraint_coeffs);
293 char *name= masprintf("trade_commod%d_port%d_at%d_port%d_at%d",
294 t->commodid, s, t->src_price, d, t->dst_price);
295 lpx_set_col_name(lp, col, name);
298 } /* while (tradestodo-- >0) */
300 /*----- that's done adding these trades to the LP problem -----*/
310 obstack_free(&ites_obstack, free_to_reset_obstack);
313 void setup_value(void) {
317 #define obstack_chunk_alloc mmalloc
318 #define obstack_chunk_free free
319 obstack_init(&ites_obstack);
321 nislands= sql_single_int("SELECT max(islandid) FROM islands") + 1;
322 debugf("VALUE nislands=%d\n",nislands);
324 commodstablesz= sql_single_int("SELECT max(commodid) FROM commods") + 1;
325 commodstable= mmalloc(sizeof(*commodstable)*commodstablesz);
326 for (i=0; i<commodstablesz; i++)
327 commodstable[i].mass= commodstable[i].volu= -1;
329 SQL_MUST( sqlite3_prepare(db,
330 "SELECT commodid,unitmass,unitvolume FROM commods", -1,&sst,0) );
331 while (SQL_STEP(sst)) {
332 int id= sqlite3_column_int(sst,0);
333 assert(id>=0 && id<commodstablesz);
334 commodstable[id].mass= sqlite3_column_int(sst,1);
335 commodstable[id].volu= sqlite3_column_int(sst,2);
337 sqlite3_finalize(sst);
339 SQL_MUST( sqlite3_prepare(db,
341 " sell.commodid commodid,\n"
342 " sell.price src_price,\n"
343 " sum(sell.qty) src_qty,\n"
344 " buy.price dst_price,\n"
345 " sum(buy.qty) dst_qty\n"
346 " FROM sell JOIN buy\n"
347 " ON sell.commodid = buy.commodid\n"
348 " AND buy.price > sell.price\n"
349 " WHERE sell.islandid=?\n"
350 " AND buy.islandid=?\n"
351 " GROUP BY sell.commodid, sell.price, buy.price",
352 -1, &ss_ipair_trades, 0) );
354 SQL_MUST( sqlite3_prepare(db,
355 " SELECT dist from dists where aiid=? and biid=?",
356 -1, &ss_ipair_dist, 0) );
358 ipairs= mcalloc(sizeof(*ipairs) * nislands);