3 This is part of the YARRG website. YARRG is a tool and website
4 for assisting players of Yohoho Puzzle Pirates.
6 Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
7 Copyright (C) 2009 Clare Boothby
9 YARRG's client code etc. is covered by the ordinary GNU GPL (v3 or later).
10 The YARRG website is covered by the GNU Affero GPL v3 or later, which
11 basically means that every installation of the website will let you
14 This program is free software: you can redistribute it and/or modify
15 it under the terms of the GNU Affero General Public License as
16 published by the Free Software Foundation, either version 3 of the
17 License, or (at your option) any later version.
19 This program is distributed in the hope that it will be useful,
20 but WITHOUT ANY WARRANTY; without even the implied warranty of
21 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 GNU Affero General Public License for more details.
24 You should have received a copy of the GNU Affero General Public License
25 along with this program. If not, see <http://www.gnu.org/licenses/>.
27 Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
28 are used without permission. This program is not endorsed or
29 sponsored by Three Rings.
32 This Mason component is the core trade planner for a specific route.
35 ========== TODO ==========
36 16:36 <ceb> alpha,byrne,papaya,turtle,jorvik,luthien is my example
38 use POST for update. Hrrm.
42 adjustable potential cost of losses (rather than fixed 1e-BIG per league)
46 ========== TODO ==========
56 da_pageload= Date.now();
62 my $loss_per_league= 1e-7;
67 my $sd_condition= sub {
69 my $islandid= $islandids[$ix];
70 if (defined $islandid) {
71 return "${bs}.islandid = $islandid";
73 push @query_params, $archipelagoes[$ix];
74 return "${bs}_islands.archipelago = ?";
79 # $islandpair{$a,$b}= [ $start_island_ix, $end_island_ix ]
81 my $specific= !grep { !defined $_ } @islandids;
84 foreach my $src_i (0..$#islandids) {
85 my $src_isle= $islandids[$src_i];
86 my $src_cond= $sd_condition->('sell',$src_i);
88 foreach my $dst_i ($src_i..$#islandids) {
89 my $dst_isle= $islandids[$dst_i];
90 my $dst_cond= $sd_condition->('buy',$dst_i);
91 if ($dst_i==$src_i and !defined $src_isle) {
92 # we always want arbitrage, but mentioning an arch
93 # once shouldn't produce intra-arch trades
95 "($dst_cond AND sell.islandid = buy.islandid)";
97 push @dst_conds, $dst_cond;
99 if ($specific && !$confusing &&
100 # With a circular route, do not carry goods round the loop
101 !($src_i==0 && $dst_i==$#islandids &&
102 $src_isle == $islandids[$dst_i])) {
103 if ($islandpair{$src_isle,$dst_isle}) {
106 $islandpair{$src_isle,$dst_isle}=
111 push @flow_conds, "$src_cond AND (
118 SELECT sell_islands.islandname org_name,
119 sell_islands.islandid org_id,
120 sell.price org_price,
121 sell_uploads.timestamp org_timestamp,
122 buy_islands.islandname dst_name,
123 buy_islands.islandid dst_id,
125 buy_uploads.timestamp dst_timestamp,
126 ".($qa->{ShowStalls} ? "
127 sell.stallid org_stallid,
128 sell_stalls.stallname org_stallname,
130 buy.stallid dst_stallid,
131 buy_stalls.stallname dst_stallname,
134 sum(sell.qty) org_qty,
135 sum(buy.qty) dst_qty,
137 commods.commodname commodname,
138 commods.commodid commodid,
139 commods.unitmass unitmass,
140 commods.unitvolume unitvolume,
142 buy.price - sell.price unitprofit
144 JOIN buy ON commods.commodid = buy.commodid
145 JOIN sell ON commods.commodid = sell.commodid
146 JOIN islands AS sell_islands ON sell.islandid = sell_islands.islandid
147 JOIN islands AS buy_islands ON buy.islandid = buy_islands.islandid
148 JOIN uploads AS sell_uploads ON sell.islandid = sell_uploads.islandid
149 JOIN uploads AS buy_uploads ON buy.islandid = buy_uploads.islandid
150 ".($qa->{ShowStalls} ? "
151 JOIN stalls AS sell_stalls ON sell.stallid = sell_stalls.stallid
152 JOIN stalls AS buy_stalls ON buy.stallid = buy_stalls.stallid
154 JOIN dists ON aiid = sell.islandid AND biid = buy.islandid
159 AND buy.price > sell.price
160 ".($qa->{ShowStalls} ? "" : "
161 GROUP BY commods.commodid, org_id, org_price, dst_id, dst_price
163 ORDER BY org_name, dst_name, commodname, unitprofit DESC,
164 org_price, dst_price DESC
167 my $sth= $dbh->prepare($stmt);
168 $sth->execute(@query_params);
171 my @cols= ({ NoSort => 1 });
175 foreach my $name (@_) {
176 my $col= { Name => $name, %$base };
177 $col->{Numeric}=1 if !$col->{Text};
182 if ($qa->{ShowStalls}) {
183 $addcols->({ Text => 1 }, qw(
184 org_name org_stallname
185 dst_name dst_stallname
188 $addcols->({Text => 1 }, qw(
192 $addcols->({ Text => 1 }, qw(commodname));
193 $addcols->({ DoReverse => 1 },
194 qw( org_price org_qty dst_price dst_qty
196 $addcols->({ DoReverse => 1, SortColKey => 'MarginSortKey' },
199 $addcols->({ DoReverse => 1 },
200 qw( unitprofit MaxQty
206 % if ($qa->{'debug'}) {
209 <% join(' | ',@query_params) |h %>
213 <& dumptable:start, qa => $qa, sth => $sth &>
216 % while ($f= $sth->fetchrow_hashref()) {
220 $f->{Var}= "f$f->{Ix}";
222 $f->{MaxQty}= $f->{'org_qty'} < $f->{'dst_qty'}
223 ? $f->{'org_qty'} : $f->{'dst_qty'};
224 $f->{MaxProfit}= $f->{MaxQty} * $f->{'unitprofit'};
225 $f->{MaxCapital}= $f->{MaxQty} * $f->{'org_price'};
227 $f->{MarginSortKey}= sprintf "%d",
228 $f->{'dst_price'} * 10000 / $f->{'org_price'};
229 $f->{Margin}= sprintf "%3.1f%%",
230 $f->{'dst_price'} * 100.0 / $f->{'org_price'} - 100.0;
232 $f->{"org_stallid"}= $f->{"dst_stallid"}= 'all'
233 if !$qa->{ShowStalls};
235 $f->{ExpectedUnitProfit}=
236 $f->{'dst_price'} * (1.0 - $loss_per_league) ** $f->{'dist'}
239 my @uid= $f->{commodid};
240 foreach my $od (qw(org dst)) {
245 $f->{"${od}_stallid"}
246 if $qa->{ShowStalls};
248 $f->{UidLong}= join '_', @uid;
256 my $this= $uue % $base;
257 print STDERR "uue=$uue this=$this ";
262 $cmpu .= chr($this + ($this < 26 ? ord('a') :
263 $this < 52 ? ord('A')-26
265 print STDERR " uue=$uue this=$this cmpu=$cmpu\n";
266 die "$cmpu $uue ?" if length $cmpu > 20;
270 $f->{UidShort}= $cmpu;
272 if ($qa->{'debug'}) {
277 my $v= m/^[a-z]/ ? ord($&)-ord('a') :
278 m/^[A-Z]/ ? ord($&)-ord('A')+26 :
279 m/^[0-9]/ ? ord($&)-ord('0')+52 :
285 #print STDERR "(next)\n";
287 die "$f->{UidShort} $_ ?" unless defined $mul;
288 $outuid[$#outuid] += $v * $mul;
290 #print STDERR "$f->{UidShort} $_ $& v=$v mul=$mul ord()=".ord($&).
291 # "[vs.".ord('a').",".ord('A').",".ord('0')."]".
292 # " outuid=@outuid\n";
297 my $recons_long= join '_', @outuid;
298 $f->{UidLong} eq $recons_long or
299 die "$f->{UidLong} = $f->{UidShort} = $recons_long ?";
302 if (defined $qa->{"R$f->{UidShort}"} &&
303 !defined $qa->{"T$f->{UidShort}"}) {
310 <& dumptable:row, qa => $qa, sth => $sth, row => $f &>
312 <& dumptable:end, qa => $qa &>
315 % my $optimise= $specific && !$confusing && @islandids>1;
319 % if (@islandids<=1) {
323 Route contains archipelago(es), not just specific islands.
326 Route is complex - it visits the same island several times
327 and isn't a simple loop.
329 Therefore, optimal trade pattern not calculated.
331 % } else { # ========== OPTMISATION ==========
340 sprintf "%.20f %s", $_->{ExpectedUnitProfit}, $_->{Var}
347 foreach my $flow (@flows) {
348 if ($flow->{Suppress}) {
354 foreach my $od (qw(org dst)) {
355 my $cstname= join '_', (
360 $flow->{"${od}_price"},
361 $flow->{"${od}_stallid"},
364 push @{ $avail_csts{$cstname}{Flows} }, $flow->{Var};
365 $avail_csts{$cstname}{Qty}= $flow->{"${od}_qty"};
368 foreach my $cstname (sort keys %avail_csts) {
369 my $c= $avail_csts{$cstname};
371 ". sprintf("%-30s","$cstname:")." ".
372 join("+", @{ $c->{Flows} }).
373 " <= ".$c->{Qty}."\n";
379 ", map { "$_->{Var} >= 0" } @flows)."
384 if ($qa->{'debug'}) {
393 my $input= pipethrough_prep();
394 print $input $cplex or die $!;
395 my $output= pipethrough_run_along($input, undef, 'glpsol',
396 qw(glpsol --cpxlp /dev/stdin -o /dev/stdout));
397 print "<pre>\n" if $qa->{'debug'};
398 my $found_section= 0;
400 print encode_entities($_) if $qa->{'debug'};
401 if (m/^\s*No\.\s+Column name\s+St\s+Activity\s/) {
402 die if $found_section>0;
406 next unless $found_section==1;
413 m/^\s*\d+\s+f(\d+)\s+\S+\s+(\d+)\s/ or die "$_ ?";
414 my $flow= $flows[$ix] or die;
415 $flow->{OptQty}= $qty;
416 $flow->{OptProfit}= $flow->{'unitprofit'} * $qty;
417 $flow->{OptCapital}= $flow->{OptQty} * $flow->{'org_price'};
419 print "</pre>\n" if $qa->{'debug'};
420 pipethrough_run_finish($output, 'glpsol');
421 die unless $found_section;
424 $addcols->({ DoReverse => 1 }, qw(
427 $addcols->({ Total => 0, DoReverse => 1 }, qw(
433 % } # ========== OPTIMISATION ==========
437 % my $cdspan= $qa->{ShowStalls} ? ' colspan=2' : '';
438 % my $cdstall= $qa->{ShowStalls} ? '<th>Stall</th>' : '';
439 <table id="trades" rules=groups>
442 <% $qa->{ShowStalls} ? '<colgroup span=2>' : '' %>
453 <th<% $cdspan %>>Collect
454 <th<% $cdspan %>>Deliver
456 <th colspan=2>Collect
457 <th colspan=2>Deliver
461 <th colspan=3>Planned
466 <th>Island <% $cdstall %>
467 <th>Island <% $cdstall %>
485 <tr id="trades_sort">
486 % foreach my $col (@cols) {
490 % foreach my $flowix (0..$#flows) {
491 % my $flow= $flows[$flowix];
492 % my $rowid= "id_row_$flow->{UidShort}";
493 <tr id="<% $rowid %>" class="datarow<% $flowix & 1 %>">
494 <td><input type=hidden name=R<% $flow->{UidShort} %> value="">
495 <input type=checkbox name=T<% $flow->{UidShort} %> value=""
496 <% $flow->{Suppress} ? '' : 'checked' %> >
497 % foreach my $ci (1..$#cols) {
498 % my $col= $cols[$ci];
499 % my $v= $flow->{$col->{Name}};
500 % $col->{Total} += $v if defined $col->{Total};
501 % $v='' if !$col->{Text} && !$v;
502 % my $sortkey= $col->{SortColKey} ?
503 % $flow->{$col->{SortColKey}} : $v;
504 % $ts_sortkeys{$ci}{$rowid}= $sortkey;
505 <td <% $col->{Text} ? '' : 'align=right' %>><% $v |h %>
508 <tr id="trades_total">
511 % foreach my $ci (3..$#cols) {
512 % my $col= $cols[$ci];
514 % if (defined $col->{Total}) {
515 <% $col->{Total} |h %>
520 <& tabsort, cols => \@cols, table => 'trades', rowclass => 'datarow',
521 throw => 'trades_sort', tbrow => 'trades_total' &>
523 ts_sortkeys= <% to_json_protecttags(\%ts_sortkeys) %>;
524 function all_onload() {
527 window.onload= all_onload;
530 <input type=submit name=update value="Update">
532 % if ($optimise) { # ========== TRADING PLAN ==========
534 % my $iquery= $dbh->prepare('SELECT islandname FROM islands
535 % WHERE islandid = ?');
538 <h1>Voyage trading plan</h1>
540 % foreach my $i (0..$#islandids) {
541 <tr><td colspan=<% 2+!!$qa->{ShowStalls} %>><strong>
542 % $iquery->execute($islandids[$i]);
543 % my ($islandname) = $iquery->fetchrow_array();
545 Start at <% $islandname |h %>
547 Sail to <% $islandname |h %>
550 % my $age_reported= 0;
551 % foreach my $od (qw(dst org)) {
552 % my $sign= $od eq 'dst' ? -1 : +1;
554 % foreach my $f (@flows) {
555 % next if $f->{Suppress};
556 % next unless $f->{"${od}_id"} == $islandids[$i];
557 % next unless $f->{OptQty};
558 % my $price= $f->{"${od}_price"};
559 % my $stallname= $f->{"${od}_stallname"};
560 % my $todo= \$todo{ $f->{'commodname'},
561 % (sprintf "%07d", $price),
563 % $$todo= { } unless $$todo;
564 % $$todo->{'commodname'}= $f->{'commodname'};
565 % $$todo->{'stallname'}= $stallname;
566 % $$todo->{Price}= $price;
567 % $$todo->{Timestamp}= $f->{"${od}_timestamp"};
568 % $$todo->{Qty} += $f->{OptQty};
569 % $$todo->{Total}= $$todo->{Price} * $$todo->{Qty};
571 % if (%todo && !$age_reported++) {
573 % my $age= $now - (values %todo)[0]->{Timestamp};
574 % my $cellid= "da_${i}";
575 % $da_ages{$cellid}= $age;
576 (Data age: <span id="<% $cellid %>"><% prettyprint_age($age) %></span>)
580 % foreach my $tkey (sort keys %todo) {
581 % my $t= $todo{$tkey};
582 % $total += $t->{Total};
583 <tr class="datarow<% $dline %>"><td>
584 % if ($od eq 'org') {
589 <td><% $t->{'commodname'} |h %>
590 <td align=right><% $t->{Price} |h %> each
591 % if ($qa->{ShowStalls}) {
592 <td><% $t->{'stallname'} |h %>
594 <td align=right><% $t->{Qty} |h %> unit(s)
595 <td align=right><% $t->{Total} |h %> total
600 <td colspan=<% 3+!!$qa->{ShowStalls} %>>
602 % if ($od eq 'org') {
607 <td align=right><% $total |h %> total
612 <& query_age:dataages, id2age => \%da_ages &>
614 % } # ========== TRADING PLAN ==========