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();
49 % if (defined $max_mass || defined $max_volume) {
50 <strong>WARNING - VESSEL CAPACITY LIMIT NOT YET IMPLEMENTED</strong>
53 % if (defined $lossperleaguepct) {
54 <strong>WARNING - DEFINED LOSS PER LEAGUE NOT YET IMPLEMENTED</strong>
55 <% $lossperleaguepct |h %>
62 my $loss_per_league= 1e-7;
68 my $sd_condition= sub {
70 my $islandid= $islandids[$ix];
71 if (defined $islandid) {
72 return "${bs}.islandid = $islandid";
74 push @query_params, $archipelagoes[$ix];
75 return "${bs}_islands.archipelago = ?";
80 # $islandpair{$a,$b}= [ $start_island_ix, $end_island_ix ]
82 my $specific= !grep { !defined $_ } @islandids;
85 foreach my $src_i (0..$#islandids) {
86 my $src_isle= $islandids[$src_i];
87 my $src_cond= $sd_condition->('sell',$src_i);
89 foreach my $dst_i ($src_i..$#islandids) {
90 my $dst_isle= $islandids[$dst_i];
91 my $dst_cond= $sd_condition->('buy',$dst_i);
92 if ($dst_i==$src_i and !defined $src_isle) {
93 # we always want arbitrage, but mentioning an arch
94 # once shouldn't produce intra-arch trades
96 "($dst_cond AND sell.islandid = buy.islandid)";
98 push @dst_conds, $dst_cond;
100 if ($specific && !$confusing &&
101 # With a circular route, do not carry goods round the loop
102 !(($src_i==0 || $src_i==$#islandids) &&
103 $dst_i==$#islandids &&
104 $src_isle == $islandids[$dst_i])) {
105 if ($islandpair{$src_isle,$dst_isle}) {
107 print "confusing $src_i $src_isle $dst_i $dst_isle\n";
109 $islandpair{$src_isle,$dst_isle}=
114 push @flow_conds, "$src_cond AND (
121 SELECT sell_islands.islandname org_name,
122 sell_islands.islandid org_id,
123 sell.price org_price,
124 sell.qty org_qty_stall,
125 sell_stalls.stallname org_stallname,
126 sell.stallid org_stallid,
127 sell_uploads.timestamp org_timestamp,
128 buy_islands.islandname dst_name,
129 buy_islands.islandid dst_id,
131 buy.qty dst_qty_stall,
132 buy_stalls.stallname dst_stallname,
133 buy.stallid dst_stallid,
134 buy_uploads.timestamp dst_timestamp,
135 ".($qa->{ShowStalls} ? "
136 sell.qty org_qty_agg,
139 (SELECT sum(qty) FROM sell AS sell_agg
140 WHERE sell_agg.commodid = commods.commodid
141 AND sell_agg.islandid = sell.islandid
142 AND sell_agg.price = sell.price) org_qty_agg,
143 (SELECT sum(qty) FROM buy AS buy_agg
144 WHERE buy_agg.commodid = commods.commodid
145 AND buy_agg.islandid = buy.islandid
146 AND buy_agg.price = buy.price) dst_qty_agg,
148 commods.commodname commodname,
149 commods.commodid commodid,
150 commods.unitmass unitmass,
151 commods.unitvolume unitvolume,
153 buy.price - sell.price unitprofit
155 JOIN sell ON commods.commodid = sell.commodid
156 JOIN buy ON commods.commodid = buy.commodid
157 JOIN islands AS sell_islands ON sell.islandid = sell_islands.islandid
158 JOIN islands AS buy_islands ON buy.islandid = buy_islands.islandid
159 JOIN uploads AS sell_uploads ON sell.islandid = sell_uploads.islandid
160 JOIN uploads AS buy_uploads ON buy.islandid = buy_uploads.islandid
161 JOIN stalls AS sell_stalls ON sell.stallid = sell_stalls.stallid
162 JOIN stalls AS buy_stalls ON buy.stallid = buy_stalls.stallid
163 JOIN dists ON aiid = sell.islandid AND biid = buy.islandid
168 AND buy.price > sell.price
169 ORDER BY org_name, dst_name, commodname, unitprofit DESC,
170 org_price, dst_price DESC,
171 org_stallname, dst_stallname
174 my $sth= $dbh->prepare($stmt);
175 $sth->execute(@query_params);
178 my $distquery= $dbh->prepare("
179 SELECT dist FROM dists WHERE aiid = ? AND biid = ?
183 my $d= $dists{$from}{$to};
184 return $d if defined $d;
185 $distquery->execute($from,$to);
186 $d = $distquery->fetchrow_array();
187 defined $d or die "$from $to ?";
188 $dists{$from}{$to}= $d;
192 my @cols= ({ NoSort => 1 });
196 foreach my $name (@_) {
197 my $col= { Name => $name, %$base };
198 $col->{Numeric}=1 if !$col->{Text};
203 if ($qa->{ShowStalls}) {
204 $addcols->({ Text => 1 }, qw(
205 org_name org_stallname
206 dst_name dst_stallname
209 $addcols->({Text => 1 }, qw(
213 $addcols->({ Text => 1 }, qw(commodname));
214 $addcols->({ DoReverse => 1 },
215 qw( org_price org_qty_agg dst_price dst_qty_agg
217 $addcols->({ DoReverse => 1, SortColKey => 'MarginSortKey' },
220 $addcols->({ DoReverse => 1 },
221 qw( unitprofit MaxQty MaxCapital MaxProfit dist
223 foreach my $v (qw(MaxMass MaxVolume)) {
225 DoReverse => 1, Total => 0, SortColKey => "${v}SortKey" }, $v);
230 % if ($qa->{'debug'}) {
233 <% join(' | ',@query_params) |h %>
237 <& dumptable:start, qa => $qa, sth => $sth &>
240 % while ($got= $sth->fetchrow_hashref()) {
243 my $f= $flows[$#flows];
246 grep { $f->{$_} ne $got->{$_} }
247 qw(org_id org_price dst_id dst_price commodid)
249 # Make a new flow rather than adding to the existing one
252 Ix => scalar(@flows),
256 $f->{"org_stallid"}= $f->{"dst_stallid"}= 'all'
257 if !$qa->{ShowStalls};
260 foreach my $od (qw(org dst)) {
262 $got->{"${od}_stallname"}
264 $got->{"${od}_qty_stall"}
269 <& dumptable:row, qa => $qa, sth => $sth, row => $f &>
271 <& dumptable:end, qa => $qa &>
277 print 'No profitable trading opportunities were found.';
281 foreach my $f (@flows) {
283 $f->{MaxQty}= $f->{'org_qty_agg'} < $f->{'dst_qty_agg'}
284 ? $f->{'org_qty_agg'} : $f->{'dst_qty_agg'};
285 $f->{MaxProfit}= $f->{MaxQty} * $f->{'unitprofit'};
286 $f->{MaxCapital}= $f->{MaxQty} * $f->{'org_price'};
288 $f->{MaxMassSortKey}= $f->{MaxQty} * $f->{'unitmass'};
289 $f->{MaxVolumeSortKey}= $f->{MaxQty} * $f->{'unitvolume'};
290 foreach my $v (qw(Mass Volume)) {
291 $f->{"Max$v"}= sprintf "%.1f", $f->{"Max${v}SortKey"} * 1e-6;
294 $f->{MarginSortKey}= sprintf "%d",
295 $f->{'dst_price'} * 10000 / $f->{'org_price'};
296 $f->{Margin}= sprintf "%3.1f%%",
297 $f->{'dst_price'} * 100.0 / $f->{'org_price'} - 100.0;
299 $f->{ExpectedUnitProfit}=
300 $f->{'dst_price'} * (1.0 - $loss_per_league) ** $f->{'dist'}
303 $dists{'org_id'}{'dst_id'}= $f->{'dist'};
305 my @uid= $f->{commodid};
306 foreach my $od (qw(org dst)) {
311 $f->{"${od}_stallid"}
312 if $qa->{ShowStalls};
314 $f->{UidLong}= join '_', @uid;
322 my $this= $uue % $base;
323 print STDERR "uue=$uue this=$this ";
328 $cmpu .= chr($this + ($this < 26 ? ord('a') :
329 $this < 52 ? ord('A')-26
331 print STDERR " uue=$uue this=$this cmpu=$cmpu\n";
332 die "$cmpu $uue ?" if length $cmpu > 20;
336 $f->{UidShort}= $cmpu;
338 if ($qa->{'debug'}) {
343 my $v= m/^[a-z]/ ? ord($&)-ord('a') :
344 m/^[A-Z]/ ? ord($&)-ord('A')+26 :
345 m/^[0-9]/ ? ord($&)-ord('0')+52 :
351 #print STDERR "(next)\n";
353 die "$f->{UidShort} $_ ?" unless defined $mul;
354 $outuid[$#outuid] += $v * $mul;
356 #print STDERR "$f->{UidShort} $_ $& v=$v mul=$mul ord()=".ord($&).
357 # "[vs.".ord('a').",".ord('A').",".ord('0')."]".
358 # " outuid=@outuid\n";
363 my $recons_long= join '_', @outuid;
364 $f->{UidLong} eq $recons_long or
365 die "$f->{UidLong} = $f->{UidShort} = $recons_long ?";
368 if (defined $qa->{"R$f->{UidShort}"} &&
369 !defined $qa->{"T$f->{UidShort}"}) {
376 % my $optimise= $specific && !$confusing && @islandids>1;
380 % if (@islandids<=1) {
381 Route contains only one location.
384 Route contains archipelago(es), not just specific islands.
387 Route is complex - it visits the same island several times
388 and isn't a simple loop.
390 Therefore, optimal voyage trade plan not calculated.
392 % } else { # ========== OPTMISATION ==========
401 sprintf "%.20f %s", $_->{ExpectedUnitProfit}, $_->{Var}
408 foreach my $flow (@flows) {
409 if ($flow->{Suppress}) {
415 foreach my $od (qw(org dst)) {
416 my $cstname= join '_', (
421 $flow->{"${od}_price"},
422 $flow->{"${od}_stallid"},
425 push @{ $avail_csts{$cstname}{Flows} }, $flow->{Var};
426 $avail_csts{$cstname}{Qty}= $flow->{"${od}_qty_agg"};
429 foreach my $cstname (sort keys %avail_csts) {
430 my $c= $avail_csts{$cstname};
432 ". sprintf("%-30s","$cstname:")." ".
433 join("+", @{ $c->{Flows} }).
434 " <= ".$c->{Qty}."\n";
440 ", map { "$_->{Var} >= 0" } @flows)."
445 if ($qa->{'debug'}) {
454 my $input= pipethrough_prep();
455 print $input $cplex or die $!;
456 my $output= pipethrough_run_along($input, undef, 'glpsol',
457 qw(glpsol --cpxlp /dev/stdin -o /dev/stdout));
458 print "<pre>\n" if $qa->{'debug'};
459 my $found_section= 0;
463 print encode_entities($_) if $qa->{'debug'};
464 if (m/^\s*No\.\s+Column name\s+St\s+Activity\s/) {
465 die if $found_section>0;
469 next unless $found_section==1;
476 m/^\s*\d+\s+f(\d+)\s+\S+\s+(\d+)\s/ or die "$_ ?";
477 my $flow= $flows[$ix] or die;
478 $flow->{OptQty}= $qty;
479 $flow->{OptProfit}= $flow->{'unitprofit'} * $qty;
480 $flow->{OptCapital}= $flow->{OptQty} * $flow->{'org_price'};
482 print "</pre>\n" if $qa->{'debug'};
483 my $prerr= "\n=====\n$cplex\n=====\n$glpsol_out\n=====\n ";
484 pipethrough_run_finish($output,$prerr);
485 die $prerr unless $found_section;
488 $addcols->({ DoReverse => 1 }, qw(
491 $addcols->({ Total => 0, DoReverse => 1 }, qw(
497 % } # ========== OPTIMISATION ==========
501 % my $cdspan= $qa->{ShowStalls} ? ' colspan=2' : '';
502 % my $cdstall= $qa->{ShowStalls} ? '<th>Stall</th>' : '';
503 <table id="trades" rules=groups>
506 <% $qa->{ShowStalls} ? '<colgroup span=2>' : '' %>
518 <th<% $cdspan %>>Collect
519 <th<% $cdspan %>>Deliver
521 <th colspan=2>Collect
522 <th colspan=2>Deliver
528 <th colspan=3>Planned
533 <th>Island <% $cdstall %>
534 <th>Island <% $cdstall %>
555 <tr id="trades_sort">
556 % foreach my $col (@cols) {
560 % foreach my $flowix (0..$#flows) {
561 % my $flow= $flows[$flowix];
562 % my $rowid= "id_row_$flow->{UidShort}";
563 <tr id="<% $rowid %>" class="datarow<% $flowix & 1 %>">
564 <td><input type=hidden name=R<% $flow->{UidShort} %> value="">
565 <input type=checkbox name=T<% $flow->{UidShort} %> value=""
566 <% $flow->{Suppress} ? '' : 'checked' %> >
567 % foreach my $ci (1..$#cols) {
568 % my $col= $cols[$ci];
569 % my $v= $flow->{$col->{Name}};
570 % $col->{Total} += $v
571 % if defined $col->{Total} and not $flow->{Suppress};
572 % $v='' if !$col->{Text} && !$v;
573 % my $sortkey= $col->{SortColKey} ?
574 % $flow->{$col->{SortColKey}} : $v;
575 % $ts_sortkeys{$ci}{$rowid}= $sortkey;
576 <td <% $col->{Text} ? '' : 'align=right' %>><% $v |h %>
579 <tr id="trades_total">
582 % foreach my $ci (3..$#cols) {
583 % my $col= $cols[$ci];
585 % if (defined $col->{Total}) {
586 <% $col->{Total} |h %>
591 <&| tabsort, cols => \@cols, table => 'trades', rowclass => 'datarow',
592 throw => 'trades_sort', tbrow => 'trades_total' &>
593 ts_sortkeys= <% to_json_protecttags(\%ts_sortkeys) %>;
596 <input type=submit name=update value="Update">
598 % if ($optimise) { # ========== TRADING PLAN ==========
600 % my $iquery= $dbh->prepare('SELECT islandname FROM islands
601 % WHERE islandid = ?');
603 % my $total_total= 0;
606 <h1>Voyage trading plan</h1>
608 % foreach my $i (0..$#islandids) {
611 % $iquery->execute($islandids[$i]);
612 % my ($islandname) = $iquery->fetchrow_array();
614 <strong>Start at <% $islandname |h %></strong>
616 % my $this_dist= $distance->($islandids[$i-1],$islandids[$i]);
617 % $total_dist += $this_dist;
618 <strong>Sail to <% $islandname |h %></strong>
619 - <% $this_dist |h %> leagues </td>
624 foreach my $od (qw(org dst)) {
625 foreach my $f (@flows) {
626 next if $f->{Suppress};
627 next unless $f->{"${od}_id"} == $islandids[$i];
628 next unless $f->{OptQty};
629 my $arbitrage= $f->{'org_id'} == $f->{'dst_id'};
630 my $loop= $islandids[0] == $islandids[-1] &&
631 ($i==0 || $i==$#islandids);
632 next if $loop and ($arbitrage ? $i :
633 !!$i == !!($od eq 'org'));
634 my $price= $f->{"${od}_price"};
635 my $stallname= $f->{"${od}_stallname"};
636 my $todo= \$flowlists{$od}{
638 (sprintf "%07d", ($od eq 'dst' ?
639 9999999-$price : $price)),
647 $$todo->{'commodname'}= $f->{'commodname'};
648 $$todo->{'stallname'}= $stallname;
649 $$todo->{Price}= $price;
650 $$todo->{Timestamp}= $f->{"${od}_timestamp"};
651 $$todo->{Qty} += $f->{OptQty};
652 $$todo->{Total}= $$todo->{Price} * $$todo->{Qty};
653 $$todo->{Stalls}= $f->{"${od}Stalls"};
654 $$todo->{"${od}Arbitrage"}= 1 if $arbitrage;
660 my $show_flows= sub {
661 my ($od,$arbitrage,$collectdeliver) = @_;
664 % my $todo= $flowlists{$od};
665 % return unless $todo;
666 % foreach my $tkey (sort keys %$todo) {
667 % my $t= $todo->{$tkey};
668 % next if $t->{"${od}Arbitrage"} != $arbitrage;
669 % if (!$age_reported++) {
670 % my $age= $now - $t->{Timestamp};
671 % my $cellid= "da_${i}";
672 % $da_ages{$cellid}= $age;
674 (Data age: <span id="<% $cellid %>"><% prettyprint_age($age) %></span>)
675 % } elsif (!defined $total) {
679 % $total += $t->{Total};
680 % my $span= 0 + keys %{ $t->{Stalls} };
681 % my $td= "td rowspan=$span";
682 <tr class="datarow<% $dline %>">
683 <<% $td %>><% $collectdeliver %>
684 <<% $td %>><% $t->{'commodname'} |h %>
686 % my @stalls= sort keys %{ $t->{Stalls} };
688 % my $name= $stalls[$_[0]];
693 <<% $td %> align=right><% $t->{Price} |h %> poe ea.
694 <<% $td %> align=right><% $t->{Qty} |h %> unit(s)
695 <<% $td %> align=right><% $t->{Total} |h %> total
697 % foreach my $stallix (1..$#stalls) {
698 <tr class="datarow<% $dline %>">
699 % $pstall->($stallix);
705 % my $show_total= sub {
706 % my ($totaldesc, $sign)= @_;
707 % if (defined $total) {
710 <td colspan=2 align=right><% $totaldesc %>
711 <td align=right><% $total |h %> total
712 % $total_total += $sign * $total;
719 $show_flows->('dst',0,'Deliver'); $show_total->('Proceeds',1);
720 $show_flows->('org',1,'Collect'); $show_total->('(Arbitrage) outlay',-1);
721 $show_flows->('dst',1,'Deliver'); $show_total->('(Arbitrage) proceeds',1);
722 $show_flows->('org',0,'Collect'); $show_total->('Outlay',-1);
727 <td colspan=2>Total distance: <% $total_dist %> leagues.
728 <td colspan=3 align=right>Overall net cash flow
729 <td align=right><strong><%
730 $total_total < 0 ? -$total_total." loss" : $total_total." gain"
733 <& query_age:dataages, id2age => \%da_ages &>
735 % } # ========== TRADING PLAN ==========