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.
46 da_pageload= Date.now();
51 my $loss_per_league= defined $lossperleaguepct ? $lossperleaguepct*0.01 : 1e-7;
59 my $sd_condition= sub {
61 my $islandid= $islandids[$ix];
62 if (defined $islandid) {
63 return "${bs}.islandid = $islandid";
65 push @query_params, $archipelagoes[$ix];
66 return "${bs}_islands.archipelago = ?";
71 # $islandpair{$a,$b}= [ $start_island_ix, $end_island_ix ]
73 my $specific= !grep { !defined $_ } @islandids;
76 foreach my $src_i (0..$#islandids) {
77 my $src_isle= $islandids[$src_i];
78 my $src_cond= $sd_condition->('sell',$src_i);
80 foreach my $dst_i ($src_i..$#islandids) {
81 my $dst_isle= $islandids[$dst_i];
82 my $dst_cond= $sd_condition->('buy',$dst_i);
83 if ($dst_i==$src_i and !defined $src_isle) {
84 # we always want arbitrage, but mentioning an arch
85 # once shouldn't produce intra-arch trades
87 "($dst_cond AND sell.islandid = buy.islandid)";
89 push @dst_conds, $dst_cond;
91 if ($specific && !$confusing &&
92 # With a circular route, do not carry goods round the loop
93 !(($src_i==0 || $src_i==$#islandids) &&
94 $dst_i==$#islandids &&
95 $src_isle == $islandids[$dst_i])) {
96 if ($islandpair{$src_isle,$dst_isle}) {
98 print "confusing $src_i $src_isle $dst_i $dst_isle\n";
100 $islandpair{$src_isle,$dst_isle}=
105 push @flow_conds, "$src_cond AND (
112 SELECT sell_islands.islandname org_name,
113 sell_islands.islandid org_id,
114 sell.price org_price,
115 sell.qty org_qty_stall,
116 sell_stalls.stallname org_stallname,
117 sell.stallid org_stallid,
118 sell_uploads.timestamp org_timestamp,
119 buy_islands.islandname dst_name,
120 buy_islands.islandid dst_id,
122 buy.qty dst_qty_stall,
123 buy_stalls.stallname dst_stallname,
124 buy.stallid dst_stallid,
125 buy_uploads.timestamp dst_timestamp,
126 ".($qa->{ShowStalls} ? "
127 sell.qty org_qty_agg,
130 (SELECT sum(qty) FROM sell AS sell_agg
131 WHERE sell_agg.commodid = commods.commodid
132 AND sell_agg.islandid = sell.islandid
133 AND sell_agg.price = sell.price) org_qty_agg,
134 (SELECT sum(qty) FROM buy AS buy_agg
135 WHERE buy_agg.commodid = commods.commodid
136 AND buy_agg.islandid = buy.islandid
137 AND buy_agg.price = buy.price) dst_qty_agg,
139 commods.commodname commodname,
140 commods.commodid commodid,
141 commods.unitmass unitmass,
142 commods.unitvolume unitvolume,
144 buy.price - sell.price unitprofit
146 JOIN sell ON commods.commodid = sell.commodid
147 JOIN buy ON commods.commodid = buy.commodid
148 JOIN islands AS sell_islands ON sell.islandid = sell_islands.islandid
149 JOIN islands AS buy_islands ON buy.islandid = buy_islands.islandid
150 JOIN uploads AS sell_uploads ON sell.islandid = sell_uploads.islandid
151 JOIN uploads AS buy_uploads ON buy.islandid = buy_uploads.islandid
152 JOIN stalls AS sell_stalls ON sell.stallid = sell_stalls.stallid
153 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 ORDER BY org_name, dst_name, commodname, unitprofit DESC,
161 org_price, dst_price DESC,
162 org_stallname, dst_stallname
165 my $sth= $dbh->prepare($stmt);
166 $sth->execute(@query_params);
169 my $distquery= $dbh->prepare("
170 SELECT dist FROM dists WHERE aiid = ? AND biid = ?
174 my $d= $dists{$from}{$to};
175 return $d if defined $d;
176 $distquery->execute($from,$to);
177 $d = $distquery->fetchrow_array();
178 defined $d or die "$from $to ?";
179 $dists{$from}{$to}= $d;
183 my @cols= ({ NoSort => 1 });
187 foreach my $name (@_) {
188 my $col= { Name => $name, %$base };
189 $col->{Numeric}=1 if !$col->{Text};
194 if ($qa->{ShowStalls}) {
195 $addcols->({ Text => 1 }, qw(
196 org_name org_stallname
197 dst_name dst_stallname
200 $addcols->({Text => 1 }, qw(
204 $addcols->({ Text => 1 }, qw(commodname));
205 $addcols->({ DoReverse => 1 },
206 qw( org_price org_qty_agg dst_price dst_qty_agg
208 $addcols->({ DoReverse => 1, SortColKey => 'MarginSortKey' },
211 $addcols->({ DoReverse => 1 },
212 qw( unitprofit MaxQty MaxCapital MaxProfit dist
214 foreach my $v (qw(MaxMass MaxVolume)) {
216 DoReverse => 1, Total => 0, SortColKey => "${v}SortKey" }, $v);
221 % if ($qa->{'debug'}) {
224 <% join(' | ',@query_params) |h %>
228 <& dumptable:start, qa => $qa, sth => $sth &>
231 % while ($got= $sth->fetchrow_hashref()) {
234 my $f= $flows[$#flows];
237 grep { $f->{$_} ne $got->{$_} }
238 qw(org_id org_price dst_id dst_price commodid)
240 # Make a new flow rather than adding to the existing one
243 Ix => scalar(@flows),
247 $f->{"org_stallid"}= $f->{"dst_stallid"}= 'all'
248 if !$qa->{ShowStalls};
251 foreach my $od (qw(org dst)) {
253 $got->{"${od}_stallname"}
255 $got->{"${od}_qty_stall"}
260 <& dumptable:row, qa => $qa, sth => $sth, row => $f &>
262 <& dumptable:end, qa => $qa &>
268 print 'No profitable trading opportunities were found.';
272 foreach my $f (@flows) {
274 $f->{MaxQty}= $f->{'org_qty_agg'} < $f->{'dst_qty_agg'}
275 ? $f->{'org_qty_agg'} : $f->{'dst_qty_agg'};
276 $f->{MaxProfit}= $f->{MaxQty} * $f->{'unitprofit'};
277 $f->{MaxCapital}= $f->{MaxQty} * $f->{'org_price'};
279 $f->{MaxMassSortKey}= $f->{MaxQty} * $f->{'unitmass'};
280 $f->{MaxVolumeSortKey}= $f->{MaxQty} * $f->{'unitvolume'};
281 foreach my $v (qw(Mass Volume)) {
282 $f->{"Max$v"}= sprintf "%.1f", $f->{"Max${v}SortKey"} * 1e-6;
285 $f->{MarginSortKey}= sprintf "%d",
286 $f->{'dst_price'} * 10000 / $f->{'org_price'};
287 $f->{Margin}= sprintf "%3.1f%%",
288 $f->{'dst_price'} * 100.0 / $f->{'org_price'} - 100.0;
290 $f->{ExpectedUnitProfit}=
291 $f->{'dst_price'} * (1.0 - $loss_per_league) ** $f->{'dist'}
294 $dists{'org_id'}{'dst_id'}= $f->{'dist'};
296 my @uid= $f->{commodid};
297 foreach my $od (qw(org dst)) {
302 $f->{"${od}_stallid"}
303 if $qa->{ShowStalls};
305 $f->{UidLong}= join '_', @uid;
313 my $this= $uue % $base;
314 print STDERR "uue=$uue this=$this ";
319 $cmpu .= chr($this + ($this < 26 ? ord('a') :
320 $this < 52 ? ord('A')-26
322 print STDERR " uue=$uue this=$this cmpu=$cmpu\n";
323 die "$cmpu $uue ?" if length $cmpu > 20;
327 $f->{UidShort}= $cmpu;
329 if ($qa->{'debug'}) {
334 my $v= m/^[a-z]/ ? ord($&)-ord('a') :
335 m/^[A-Z]/ ? ord($&)-ord('A')+26 :
336 m/^[0-9]/ ? ord($&)-ord('0')+52 :
342 #print STDERR "(next)\n";
344 die "$f->{UidShort} $_ ?" unless defined $mul;
345 $outuid[$#outuid] += $v * $mul;
347 #print STDERR "$f->{UidShort} $_ $& v=$v mul=$mul ord()=".ord($&).
348 # "[vs.".ord('a').",".ord('A').",".ord('0')."]".
349 # " outuid=@outuid\n";
354 my $recons_long= join '_', @outuid;
355 $f->{UidLong} eq $recons_long or
356 die "$f->{UidLong} = $f->{UidShort} = $recons_long ?";
359 if (defined $qa->{"R$f->{UidShort}"} &&
360 !defined $qa->{"T$f->{UidShort}"}) {
367 % my $optimise= $specific && !$confusing && @islandids>1;
371 % if (@islandids<=1) {
372 Route contains only one location.
375 Route contains archipelago(es), not just specific islands.
378 Route is complex - it visits the same island several times
379 and isn't a simple loop.
381 Therefore, optimal voyage trade plan not calculated.
383 % } else { # ========== OPTMISATION ==========
392 sprintf "%+.20f %s", $_->{ExpectedUnitProfit}, $_->{Var}
399 foreach my $flow (@flows) {
400 if ($flow->{Suppress}) {
406 foreach my $od (qw(org dst)) {
407 my $cstname= join '_', (
412 $flow->{"${od}_price"},
413 $flow->{"${od}_stallid"},
416 push @{ $avail_csts{$cstname}{Flows} }, $flow->{Var};
417 $avail_csts{$cstname}{Qty}= $flow->{"${od}_qty_agg"};
420 foreach my $cstname (sort keys %avail_csts) {
421 my $c= $avail_csts{$cstname};
423 ". sprintf("%-30s","$cstname:")." ".
424 join("+", @{ $c->{Flows} }).
425 " <= ".$c->{Qty}."\n";
428 foreach my $ci (0..($#islandids-1)) {
430 foreach my $f (@flows) {
431 next if $f->{Suppress};
432 next if $f->{'org_id'} == $f->{'dst_id'};
433 next unless grep { $f->{'org_id'} == $_ }
435 next unless grep { $f->{'dst_id'} == $_ }
436 @islandids[$ci+1..@islandids-1];
438 #print " RELEVANT $ci $f->{Ix} ";
440 #print " RELEVANT $ci COUNT ".scalar(@rel_flows)." ";
441 next unless @rel_flows;
442 foreach my $mv (qw(mass volume)) {
443 my $max_vn= "max_$mv";
444 my $max= $mv eq 'mass' ? $max_mass : $max_volume;
445 next unless defined $max;
446 #print " DEFINED MAX $mv $max ";
448 ". sprintf("%-10s","${mv}_$ci:")." ".
449 join(" + ", map { ($_->{"unit$mv"}*1e-3).' f'.$_->{Ix} } @rel_flows).
458 ", map { "$_->{Var} >= 0" } @flows)."
465 ", map { "f$_" } (0..$#flows))."
470 if ($qa->{'debug'}) {
479 my $input= pipethrough_prep();
480 print $input $cplex or die $!;
481 my $output= pipethrough_run_along($input, undef, 'glpsol',
482 qw(glpsol --cpxlp /dev/stdin -o /dev/stdout));
483 print "<pre>\n" if $qa->{'debug'};
484 my $found_section= 0;
488 print encode_entities($_) if $qa->{'debug'};
489 if (m/^\s*No\.\s+Column name\s+(?:St\s+)?Activity\s/) {
490 die if $found_section>0;
494 next unless $found_section==1;
501 m/^\s*\d+\s+f(\d+)\s+\S+\s+(\d+)\s/ or die "$_ ?";
502 my $flow= $flows[$ix] or die;
503 $flow->{OptQty}= $qty;
504 $flow->{OptProfit}= $flow->{'unitprofit'} * $qty;
505 $flow->{OptCapital}= $flow->{OptQty} * $flow->{'org_price'};
507 print "</pre>\n" if $qa->{'debug'};
508 my $prerr= "\n=====\n$cplex\n=====\n$glpsol_out\n=====\n ";
509 pipethrough_run_finish($output,$prerr);
510 die $prerr unless $found_section;
513 $addcols->({ DoReverse => 1, Special => sub {
514 my ($flow,$col,$v,$spec) = @_;
515 if ($flow->{ExpectedUnitProfit} < 0) {
517 $spec->{String}= '(Small margin)';
518 $spec->{Align}= 'align=center';
523 $addcols->({ Total => 0, DoReverse => 1 }, qw(
529 % } # ========== OPTIMISATION ==========
533 % my $cdspan= $qa->{ShowStalls} ? ' colspan=2' : '';
534 % my $cdstall= $qa->{ShowStalls} ? '<th>Stall</th>' : '';
535 <table id="trades" rules=groups>
538 <% $qa->{ShowStalls} ? '<colgroup span=2>' : '' %>
550 <th<% $cdspan %>>Collect
551 <th<% $cdspan %>>Deliver
553 <th colspan=2>Collect
554 <th colspan=2>Deliver
560 <th colspan=3>Planned
565 <th>Island <% $cdstall %>
566 <th>Island <% $cdstall %>
587 <tr id="trades_sort">
588 % foreach my $col (@cols) {
592 % foreach my $flowix (0..$#flows) {
593 % my $flow= $flows[$flowix];
594 % my $rowid= "id_row_$flow->{UidShort}";
595 <tr id="<% $rowid %>" class="datarow<% $flowix & 1 %>">
596 <td><input type=hidden name=R<% $flow->{UidShort} %> value="">
597 <input type=checkbox name=T<% $flow->{UidShort} %> value=""
598 <% $flow->{Suppress} ? '' : 'checked' %> >
600 % while ($ci < @cols) {
601 % my $col= $cols[$ci];
604 % Align => ($col->{Text} ? '' : 'align=right')
606 % my $v= $flow->{$col->{Name}};
607 % if ($col->{Special}) { $col->{Special}($flow,$col,$v,$spec); }
608 % $col->{Total} += $v
609 % if defined $col->{Total} and not $flow->{Suppress};
610 % $v='' if !$col->{Text} && !$v;
611 % my $sortkey= $col->{SortColKey} ?
612 % $flow->{$col->{SortColKey}} : $v;
613 % $ts_sortkeys{$ci}{$rowid}= $sortkey;
614 <td <% $spec->{Span} ? "colspan=$spec->{Span}" : ''
616 %>><% exists $spec->{String} ? $spec->{String} : $v |h %>
617 % $ci += $spec->{Span};
620 <tr id="trades_total">
623 % foreach my $ci (3..$#cols) {
624 % my $col= $cols[$ci];
626 % if (defined $col->{Total}) {
627 <% $col->{Total} |h %>
632 <&| tabsort, cols => \@cols, table => 'trades', rowclass => 'datarow',
633 throw => 'trades_sort', tbrow => 'trades_total' &>
634 ts_sortkeys= <% to_json_protecttags(\%ts_sortkeys) %>;
637 <input type=submit name=update value="Update">
639 % if ($optimise) { # ========== TRADING PLAN ==========
641 % my $iquery= $dbh->prepare('SELECT islandname FROM islands
642 % WHERE islandid = ?');
644 % my $total_total= 0;
647 <h1>Voyage trading plan</h1>
649 % foreach my $i (0..$#islandids) {
652 % $iquery->execute($islandids[$i]);
653 % my ($islandname) = $iquery->fetchrow_array();
655 <strong>Start at <% $islandname |h %></strong>
657 % my $this_dist= $distance->($islandids[$i-1],$islandids[$i]);
658 % $total_dist += $this_dist;
659 <strong>Sail to <% $islandname |h %></strong>
660 - <% $this_dist |h %> leagues </td>
665 foreach my $od (qw(org dst)) {
666 foreach my $f (@flows) {
667 next if $f->{Suppress};
668 next unless $f->{"${od}_id"} == $islandids[$i];
669 next unless $f->{OptQty};
670 my $arbitrage= $f->{'org_id'} == $f->{'dst_id'};
671 my $loop= $islandids[0] == $islandids[-1] &&
672 ($i==0 || $i==$#islandids);
673 next if $loop and ($arbitrage ? $i :
674 !!$i == !!($od eq 'org'));
675 my $price= $f->{"${od}_price"};
676 my $stallname= $f->{"${od}_stallname"};
677 my $todo= \$flowlists{$od}{
679 (sprintf "%07d", ($od eq 'dst' ?
680 9999999-$price : $price)),
688 $$todo->{'commodname'}= $f->{'commodname'};
689 $$todo->{'stallname'}= $stallname;
690 $$todo->{Price}= $price;
691 $$todo->{Timestamp}= $f->{"${od}_timestamp"};
692 $$todo->{Qty} += $f->{OptQty};
693 $$todo->{Total}= $$todo->{Price} * $$todo->{Qty};
694 $$todo->{Stalls}= $f->{"${od}Stalls"};
695 $$todo->{"${od}Arbitrage"}= 1 if $arbitrage;
701 my $show_flows= sub {
702 my ($od,$arbitrage,$collectdeliver) = @_;
705 % my $todo= $flowlists{$od};
706 % return unless $todo;
707 % foreach my $tkey (sort keys %$todo) {
708 % my $t= $todo->{$tkey};
709 % next if $t->{"${od}Arbitrage"} != $arbitrage;
710 % if (!$age_reported++) {
711 % my $age= $now - $t->{Timestamp};
712 % my $cellid= "da_${i}";
713 % $da_ages{$cellid}= $age;
715 (Data age: <span id="<% $cellid %>"><% prettyprint_age($age) %></span>)
716 % } elsif (!defined $total) {
720 % $total += $t->{Total};
721 % my $span= 0 + keys %{ $t->{Stalls} };
722 % my $td= "td rowspan=$span";
723 <tr class="datarow<% $dline %>">
724 <<% $td %>><% $collectdeliver %>
725 <<% $td %>><% $t->{'commodname'} |h %>
727 % my @stalls= sort keys %{ $t->{Stalls} };
729 % my $name= $stalls[$_[0]];
734 <<% $td %> align=right><% $t->{Price} |h %> poe ea.
735 <<% $td %> align=right><% $t->{Qty} |h %> unit(s)
736 <<% $td %> align=right><% $t->{Total} |h %> total
738 % foreach my $stallix (1..$#stalls) {
739 <tr class="datarow<% $dline %>">
740 % $pstall->($stallix);
746 % my $show_total= sub {
747 % my ($totaldesc, $sign)= @_;
748 % if (defined $total) {
751 <td colspan=2 align=right><% $totaldesc %>
752 <td align=right><% $total |h %> total
753 % $total_total += $sign * $total;
760 $show_flows->('dst',0,'Deliver'); $show_total->('Proceeds',1);
761 $show_flows->('org',1,'Collect'); $show_total->('(Arbitrage) outlay',-1);
762 $show_flows->('dst',1,'Deliver'); $show_total->('(Arbitrage) proceeds',1);
763 $show_flows->('org',0,'Collect'); $show_total->('Outlay',-1);
768 <td colspan=2>Total distance: <% $total_dist %> leagues.
769 <td colspan=3 align=right>Overall net cash flow
770 <td align=right><strong><%
771 $total_total < 0 ? -$total_total." loss" : $total_total." gain"
774 <& query_age:dataages, id2age => \%da_ages &>
776 % } # ========== TRADING PLAN ==========