chiark / gitweb /
routesearch: abandon higher granuarities when tables become full
[ypp-sc-tools.db-test.git] / yarrg / rsvalue.c
index 67785239c473297ac1201f39cfca51834d36d8f6..8fe5f229b04b00355817b7225475a9068e8d9621 100644 (file)
 /**/
 
+#include <glpk.h>
+
 #include "rscommon.h"
 
-void value_route(int nislands, const int *islands) {
-  char stmt[1024+80*nislands+40*nislands*nislands], *sp;
-  int s,d;
+DEBUG_DEFINE_DEBUGF(value);
+
+typedef struct { int mass, volu; } CommodInfo;
+static int commodstabsz;
+static CommodInfo *commodstab;
+
+static sqlite3_stmt *ss_ipair_dist;
+static sqlite3_stmt *ss_ite_buy, *ss_ite_sell;
+
+
+#define MAX_LEGS (MAX_ROUTELEN-1)
+
+typedef struct {
+  int commodid, src_price, dst_price;
+} Trade;
+
+#define TRADES_PER_BLOCK 10
+
+typedef struct TradesBlock {
+  struct TradesBlock *next;
+  int ntrades;
+  Trade t[TRADES_PER_BLOCK];
+} TradesBlock;
+
+static IslandPair ***ipairs; /* ipairs[sislandid][dislandid] */
+
+typedef struct IslandTradeEnd {
+  struct IslandTradeEnd *next;
+  /* key: */
+  int commodid, price;
+  /* values: */
+  int qty;
+  unsigned long generation;
+  int rownum;
+} IslandTradeEnd;
+
+typedef struct {
+  IslandTradeEnd *src, *dst;
+} IslandTradeEndHeads;
+
+IslandTradeEndHeads *itradeends;
+  /* itradeends[islandid].{src,dst}->commodid etc. */
+
+static LPX *lp;
+static unsigned long generation;
+
+static int nconstraint_rows;
+static int constraint_rows[1+2+3*MAX_LEGS];
+static double constraint_coeffs[1+2+3*MAX_LEGS];
+      /* dummy0, src, dst, for_each_leg( [mass], [volume], [capital] ) */
+
+static void add_constraint(int row, double coefficient) {
+  nconstraint_rows++; /* glpk indices start from 1 !!! */
+  constraint_rows  [nconstraint_rows]= row;
+  constraint_coeffs[nconstraint_rows]= coefficient;
+}
+
+static void avail_c(const Trade *t, IslandTradeEnd **trades,
+                   int price, const char *srcdst,
+                   int islandid, sqlite3_stmt *ss_ite) {
+  /* find row number of trade availability constraint */
+  IslandTradeEnd *search;
+
+  for (search= *trades; search; search=search->next)
+    if (search->commodid==t->commodid && search->price==price)
+      goto found;
+  abort();
   
-  sp= stmt;
-  sp += sprintf(sp,
-               "SELECT\n"
-               " sell.islandid         src_id,\n"
-               " sell.price            src_price,\n"
-               " sum(sell.qty)         src_qty,\n"
-               " buy.islandid          dst_id,\n"
-               " buy.price             dst_price,\n"
-               " sum(buy.qty)          dst_qty,\n"
-               " commods.commodid      commodid,\n"
-               " commods.unitmass      unitmass,\n"
-               " commods.unitvolume    unitvolume,\n"
-               " dist                  dist,\n"
-               " buy.price-sell.price  unitprofit\n"
-               " FROM commods\n"
-               " JOIN sell ON commods.commodid = sell.commodid\n"
-               " JOIN buy  ON commods.commodid = buy.commodid\n"
-               " JOIN dists ON aiid = sell.islandid AND biid = buy.islandid\n"
-               " WHERE buy.price > sell.price\n"
-               "       AND (");
-  for (s=0; s<nislands; s++) {
-    sp += sprintf(sp, "%s(sell.islandid=%d AND (",
-                 !s ? "" : "\n   OR ",
-                 islands[s]);
-    for (d=s; d<nislands; d++) {
-      sp += sprintf(sp, "%sbuy.islandid=%d",
-                   d==s ? "" : " OR ",
-                   islands[d]);
+ found:;
+  if (search->generation != generation) {
+    search->rownum= lpx_add_rows(lp, 1);
+    lpx_set_row_bnds(lp, search->rownum, LPX_UP, 0, search->qty);
+
+    if (DEBUGP(value) || DEBUGP(check)) {
+      char *name= masprintf("%s_i%d_c%d_%d_all",
+                           srcdst, islandid, t->commodid, price);
+      lpx_set_row_name(lp,search->rownum,name);
+
+      if (DEBUGP(check)) {
+       int nrows= lpx_get_num_rows(lp);
+       assert(search->rownum == nrows);
+       int i;
+       for (i=1; i<nrows; i++)
+         assert(strcmp(name, lpx_get_row_name(lp,i)));
+      }
+      free(name);
     }
-    sp += sprintf(sp, "))");
+    search->generation= generation;
+  }
+
+  add_constraint(search->rownum, 1.0);
+}
+
+static int setup_leg_constraints(double max_thing, int legs, const char *wh) {
+  int leg, startrow;
+  if (max_thing < 0 || !legs) return -1;
+  startrow= lpx_add_rows(lp, legs);
+  for (leg=0; leg<legs; leg++) {
+    int row= leg+startrow;
+    lpx_set_row_bnds(lp, row, LPX_UP, 0, max_thing);
+    if (DEBUGP(value)) {
+      char *name= masprintf("%s_%d",wh,leg);
+      lpx_set_row_name(lp,row,name);
+      free(name);
+    }
+  }
+  return startrow;
+}
+
+static void add_leg_c(int startrow, int leg, double value) {
+  if (startrow<=0) return;
+  assert(value > 0);
+  add_constraint(startrow+leg, value);
+}
+
+IslandPair *ipair_get_maybe(int si, int di) {
+  IslandPair **ipa;
+
+  assert(si < islandtablesz);
+  assert(di < islandtablesz);
+
+  if (!(ipa= ipairs[si])) return 0;
+  return ipa[di];
+}
+
+static IslandPair *ipair_get_create(int si, int di) {
+  IslandPair *ip, **ipa;
+
+  assert(si < islandtablesz);
+  assert(di < islandtablesz);
+
+  if (!(ipa= ipairs[si])) {
+    ipairs[si]= MCALLOC(ipa, islandtablesz);
+  }
+  if ((ip= ipa[di]))
+    return ip;
+
+  ipa[di]= NEW(ip);
+  ip->trades= 0;
+  ip->route_tail_value= -1;
+
+  if (si==di) ctr_islands_arbitrage++;
+  else ctr_ipairs_relevant++;
+
+  debugf("VALUE ipair_get(i%d,i%d) running...\n", si,di);
+  SQL_MUST( sqlite3_bind_int(ss_ipair_dist, 1, si) );
+  SQL_MUST( sqlite3_bind_int(ss_ipair_dist, 2, di) );
+  assert(SQL_STEP(ss_ipair_dist));
+  int dist= sqlite3_column_int(ss_ipair_dist, 0);
+  ip->distance_loss_factor= pow(distance_loss_factor_per_league, dist);
+  sqlite3_reset(ss_ipair_dist);
+  
+  return ip;
+}
+
+double value_route(int nislands, const int *islands, int exclude_arbitrage) {
+  int s,d;
+
+  ctr_subroutes_valued++;
+
+  /* We need to construct the LP problem.  GLPK talks
+   * about rows and columns, which are numbered from 1.
+   *
+   * Each column is a `structural variable' ie one of the entries in
+   * the objective function.  In our case the set of structural
+   * variable is, for each port, the set of Trades which collect at
+   * that island.  (We use `port' to mean `specific visit to an
+   * island' so if an island appears more than once so do its trades.)
+   * We don't need to worry about crossing with all the possible
+   * delivery locations as we always deliver on the first port.
+   * We will call such a structural variable a Flow, for brevity.
+   *
+   * We iterate over the possible Flows adding them as columns as we
+   * go, and also adding their entries to the various constraints.
+   *
+   * Each row is an `auxiliary variable' ie one of the constraints.
+   * We have two kinds of constraint:
+   *   - mass/volume/capital: one constraint for each sailed leg
+   *       (unless relevant constraint is not satisfied)
+   *   - quantity of commodity available for collection
+   *       or delivery at particular price and island
+   * The former are numbered predictably: we have first all the mass
+   * limits, then all the volume limits, then all the capital limits
+   * (as applicable) - one for each leg, ie one for each entry
+   * in islands except the first.
+   *
+   * The latter are added as needed and the row numbers are stored in
+   * a data structure for later reuse.
+   */
+
+  assert(nislands >= 1);
+  assert(++generation);
+
+  assert(!lp);
+  lp= lpx_create_prob();
+  lpx_set_obj_dir(lp, LPX_MAX);
+  lpx_set_int_parm(lp, LPX_K_MSGLEV, DEBUGP(lp) ? 3 : 1);
+  lpx_set_int_parm(lp, LPX_K_PRESOL, 1);
+
+  if (DEBUGP(value)) {
+    lpx_set_prob_name(lp,(char*)"value_route");
+    lpx_set_obj_name(lp,(char*)"profit");
+  }
+
+  int legs= nislands-1;
+  int mass_constraints= setup_leg_constraints(max_mass, legs, "mass");
+  int volu_constraints= setup_leg_constraints(max_volu, legs, "volu");
+  int capi_constraints= setup_leg_constraints(max_capi, legs, "capi");
+
+  double delay_slot_loss_factor= 1.0;
+  for (s=0;
+       s<nislands;
+       s++, delay_slot_loss_factor *= LOSS_FACTOR_PER_DELAY_SLOT) {
+    int si= islands[s];
+    
+    for (d= s + exclude_arbitrage;
+        d < nislands;
+        d++) {
+      int di= islands[d];
+      int already_d;
+      for (already_d=s+1; already_d<d; already_d++)
+       if (islands[already_d] == di)
+         /* visited this island already since we left s, uninteresting */
+         goto next_d;
+
+      if (d>s && di==si)
+       /* route has returned to si, no need to think more about s */
+       goto next_s;
+
+      /*----- actually add these trades to the LP problem -----*/
+      
+      IslandPair *ip= ipair_get_maybe(islands[s], islands[d]);
+
+      if (!ip || !ip->trades)
+       goto next_d;
+
+      double loss_factor= delay_slot_loss_factor * ip->distance_loss_factor;
+      debugf(" SOME   i%d#%d..i%d#%d  dslf=%g dlf=%g  lf=%g\n",
+            si,s, di,d,
+            delay_slot_loss_factor, ip->distance_loss_factor, loss_factor);
+
+      TradesBlock *block;
+      for (block=ip->trades; block; block=block->next) {
+       int inblock;
+       for (inblock=0; inblock<block->ntrades; inblock++) {
+         Trade *t= &block->t[inblock];
+
+         debugf("  TRADE i%d#%d..i%d#%d c%d %d-%d  ",
+                si,s, di,d, t->commodid, t->src_price, t->dst_price);
+
+         nconstraint_rows=0;
+
+         avail_c(t, &itradeends[si].src, t->src_price, "src", si,ss_ite_sell);
+         avail_c(t, &itradeends[di].dst, t->dst_price, "dst", di,ss_ite_buy);
+
+         int leg;
+         for (leg=s; leg<d; leg++) {
+           add_leg_c(mass_constraints,leg, commodstab[t->commodid].mass*1e-3);
+           add_leg_c(volu_constraints,leg, commodstab[t->commodid].volu*1e-3);
+           add_leg_c(capi_constraints,leg, t->src_price);
+         }
+
+         double unit_profit= t->dst_price * loss_factor - t->src_price;
+         debugf("    unit profit %f\n", unit_profit);
+         if (unit_profit <= 0) continue;
+
+         int col= lpx_add_cols(lp,1);
+         lpx_set_col_bnds(lp, col, LPX_LO, 0, 0);
+         lpx_set_obj_coef(lp, col, unit_profit);
+         lpx_set_mat_col(lp, col, nconstraint_rows,
+                         constraint_rows, constraint_coeffs);
+
+         if (DEBUGP(value)) {
+           char *name= masprintf("c%d_p%d_%d_p%d_%d", t->commodid,
+                                 s, t->src_price, d, t->dst_price);
+           lpx_set_col_name(lp, col, name);
+           free(name);
+         }
+       } /* inblock */
+      } /* block */
+      
+      /*----- that's done adding these trades to the LP problem -----*/
+      
+    next_d:;
+    } /* for (d) */
+  next_s:;
+  } /* for (s) */
+
+  double profit= 0;
+
+  if (lpx_get_num_cols(lp)) {
+    ctr_subroutes_nonempty++;
+    
+    if (DEBUGP(lp))
+      lpx_write_cpxlp(lp, (char*)DEBUG_DEV);
+
+    int ipr= lpx_simplex(lp);
+    assert(ipr==LPX_E_OK);
+
+    if (DEBUGP(lp))
+      lpx_print_sol(lp, (char*)DEBUG_DEV);
+
+    int lpst= lpx_get_status(lp);
+    assert(lpst == LPX_OPT);
+    profit= lpx_get_obj_val(lp);
+  }
+
+  lpx_delete_prob(lp);
+  lp= 0;
+
+  return profit;
+}
+
+#define TRADE_FROM                                                     \
+    "  FROM sell, buy\n"                                               \
+    "  WHERE sell.commodid=buy.commodid AND sell.price < buy.price\n"
+             
+static void read_trades(void) {
+  /* We would like to use DISTINCT but sqlite3 is too stupid
+   * to notice that it could use the index to do the DISTINCT
+   * which makes it rather slow. */
+  sqlite3_stmt *ss_trades;
+
+#define TRADE_COLS \
+    "sell.commodid, sell.islandid, sell.price, buy.islandid, buy.price"
+  SQL_PREPARE(ss_trades,
+             " SELECT " TRADE_COLS "\n"
+             TRADE_FROM
+             "  ORDER BY " TRADE_COLS);
+
+  SQL_DISTINCT_DECL(cols,5);
+  while (SQL_DISTINCT_STEP(ss_trades,cols,5)) {    
+    ctr_trades_loaded++;
+    IslandPair *ip= ipair_get_create(cols[1], cols[3]);
+    TradesBlock *block= ip->trades;
+    if (!block || ip->trades->ntrades >= TRADES_PER_BLOCK) {
+      NEW(block);
+      block->next= ip->trades;
+      ip->trades= block;
+      block->ntrades= 0;
+    }
+    Trade *trade= &block->t[block->ntrades];
+    trade->commodid=  cols[0];
+    trade->src_price= cols[2];
+    trade->dst_price= cols[4];
+    block->ntrades++;
+  }
+  sqlite3_finalize(ss_trades);
+}
+
+static void read_islandtradeends(const char *bs, int srcdstoff) {
+
+#define TRADEEND_KEYCOLS "%s.commodid, %s.islandid, %s.stallid"
+  char *stmt= masprintf(" SELECT " TRADEEND_KEYCOLS ", %s.price, %s.qty\n"
+                       TRADE_FROM
+                       "  ORDER BY "  TRADEEND_KEYCOLS,
+                       bs,bs,bs,bs,bs, bs,bs,bs);
+  char *stmt_id= masprintf("qtys (%s)",bs);
+  sqlite3_stmt *ss= sql_prepare(stmt, stmt_id);
+  free(stmt); free(stmt_id);
+
+  SQL_DISTINCT_DECL(cols,5);
+  while (SQL_DISTINCT_STEP(ss,cols,3)) {
+    ctr_quantities_loaded++;
+    IslandTradeEnd *search;
+
+    int commodid= cols[0];
+    int islandid= cols[1];
+    int price= cols[3];
+    int qty= cols[4];
+
+    IslandTradeEnd **trades= (void*)((char*)&itradeends[islandid] + srcdstoff);
+
+    for (search= *trades; search; search=search->next)
+      if (search->commodid==commodid && search->price==price)
+       goto found;
+    /* not found, add new end */
+
+    NEW(search);
+    search->commodid= commodid;
+    search->price= price;
+    search->next= *trades;
+    search->generation= 0;
+    search->qty= 0;
+    *trades= search;
+
+  found:
+    search->qty += qty;
+  }
+  sqlite3_finalize(ss);
+}
+
+void setup_value(void) {
+  sqlite3_stmt *sst;
+
+  commodstabsz= sql_single_int("SELECT max(commodid) FROM commods") + 1;
+  MCALLOC_INITEACH(commodstab, commodstabsz,
+                  this->mass= this->volu= -1
+                  );
+
+  SQL_PREPARE(sst,
+             "SELECT commodid,unitmass,unitvolume FROM commods");
+  while (SQL_STEP(sst)) {
+    ctr_commodities_loaded++;
+    int id= sqlite3_column_int(sst,0);
+    assert(id>=0 && id<commodstabsz);
+    commodstab[id].mass= sqlite3_column_int(sst,1);
+    commodstab[id].volu= sqlite3_column_int(sst,2);
   }
-  sp += sprintf(sp,
-               ")\n"
-               " GROUP BY commods.commodid,\n"
-               "       sell.islandid, sell.price,\n"
-               "       buy.islandid, buy.price\n"
-               );
+  sqlite3_finalize(sst);
 
-  assert(sp < stmt + sizeof(stmt) - 1);
+  MCALLOC(ipairs, islandtablesz);
+  MCALLOC(itradeends, islandtablesz);
 
-  printf("SQL\n[\n%s\n]\n", stmt);
+  SQL_PREPARE(ss_ipair_dist,
+             " SELECT dist FROM dists\n"
+             "  WHERE aiid=? and biid=?");
 
-  //char *tail;
-  //struct sqlite_vm *sth;
-  //r= sqlite_compile(db, stmt, &tail, &sth, 
+  read_trades();
+  read_islandtradeends("sell", offsetof(IslandTradeEndHeads, src));
+  read_islandtradeends("buy",  offsetof(IslandTradeEndHeads, dst));
 }