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.
43 da_pageload= Date.now();
49 my $loss_per_league= 1e-7;
54 my $sd_condition= sub {
56 my $islandid= $islandids[$ix];
57 if (defined $islandid) {
58 return "${bs}.islandid = $islandid";
60 push @query_params, $archipelagoes[$ix];
61 return "${bs}_islands.archipelago = ?";
66 # $islandpair{$a,$b}= [ $start_island_ix, $end_island_ix ]
68 my $specific= !grep { !defined $_ } @islandids;
71 foreach my $src_i (0..$#islandids) {
72 my $src_isle= $islandids[$src_i];
73 my $src_cond= $sd_condition->('sell',$src_i);
75 foreach my $dst_i ($src_i..$#islandids) {
76 my $dst_isle= $islandids[$dst_i];
77 my $dst_cond= $sd_condition->('buy',$dst_i);
78 if ($dst_i==$src_i and !defined $src_isle) {
79 # we always want arbitrage, but mentioning an arch
80 # once shouldn't produce intra-arch trades
82 "($dst_cond AND sell.islandid = buy.islandid)";
84 push @dst_conds, $dst_cond;
86 if ($specific && !$confusing &&
87 # With a circular route, do not carry goods round the loop
88 !($src_i==0 && $dst_i==$#islandids &&
89 $src_isle == $islandids[$dst_i])) {
90 if ($islandpair{$src_isle,$dst_isle}) {
93 $islandpair{$src_isle,$dst_isle}=
98 push @flow_conds, "$src_cond AND (
105 SELECT sell_islands.islandname org_name,
106 sell_islands.islandid org_id,
107 sell.price org_price,
108 sell.qty org_qty_stall,
109 sell_stalls.stallname org_stallname,
110 sell.stallid org_stallid,
111 sell_uploads.timestamp org_timestamp,
112 buy_islands.islandname dst_name,
113 buy_islands.islandid dst_id,
115 buy.qty dst_qty_stall,
116 buy_stalls.stallname dst_stallname,
117 buy.stallid dst_stallid,
118 buy_uploads.timestamp dst_timestamp,
119 ".($qa->{ShowStalls} ? "
120 sell.qty org_qty_agg,
123 (SELECT sum(qty) FROM sell AS sell_agg
124 WHERE sell_agg.commodid = commods.commodid
125 AND sell_agg.islandid = sell.islandid
126 AND sell_agg.price = sell.price) org_qty_agg,
127 (SELECT sum(qty) FROM buy AS buy_agg
128 WHERE buy_agg.commodid = commods.commodid
129 AND buy_agg.islandid = buy.islandid
130 AND buy_agg.price = buy.price) dst_qty_agg,
132 commods.commodname commodname,
133 commods.commodid commodid,
134 commods.unitmass unitmass,
135 commods.unitvolume unitvolume,
137 buy.price - sell.price unitprofit
139 JOIN sell ON commods.commodid = sell.commodid
140 JOIN buy ON commods.commodid = buy.commodid
141 JOIN islands AS sell_islands ON sell.islandid = sell_islands.islandid
142 JOIN islands AS buy_islands ON buy.islandid = buy_islands.islandid
143 JOIN uploads AS sell_uploads ON sell.islandid = sell_uploads.islandid
144 JOIN uploads AS buy_uploads ON buy.islandid = buy_uploads.islandid
145 JOIN stalls AS sell_stalls ON sell.stallid = sell_stalls.stallid
146 JOIN stalls AS buy_stalls ON buy.stallid = buy_stalls.stallid
147 JOIN dists ON aiid = sell.islandid AND biid = buy.islandid
152 AND buy.price > sell.price
153 ORDER BY org_name, dst_name, commodname, unitprofit DESC,
154 org_price, dst_price DESC,
155 org_stallname, dst_stallname
158 my $sth= $dbh->prepare($stmt);
159 $sth->execute(@query_params);
162 my @cols= ({ NoSort => 1 });
166 foreach my $name (@_) {
167 my $col= { Name => $name, %$base };
168 $col->{Numeric}=1 if !$col->{Text};
173 if ($qa->{ShowStalls}) {
174 $addcols->({ Text => 1 }, qw(
175 org_name org_stallname
176 dst_name dst_stallname
179 $addcols->({Text => 1 }, qw(
183 $addcols->({ Text => 1 }, qw(commodname));
184 $addcols->({ DoReverse => 1 },
185 qw( org_price org_qty_agg dst_price dst_qty_agg
187 $addcols->({ DoReverse => 1, SortColKey => 'MarginSortKey' },
190 $addcols->({ DoReverse => 1 },
191 qw( unitprofit MaxQty
197 % if ($qa->{'debug'}) {
200 <% join(' | ',@query_params) |h %>
204 <& dumptable:start, qa => $qa, sth => $sth &>
207 % while ($got= $sth->fetchrow_hashref()) {
210 my $f= $flows[$#flows];
213 grep { $f->{$_} ne $got->{$_} }
214 qw(org_id org_price dst_id dst_price commodid)
216 # Make a new flow rather than adding to the existing one
219 Ix => scalar(@flows),
223 $f->{"org_stallid"}= $f->{"dst_stallid"}= 'all'
224 if !$qa->{ShowStalls};
227 foreach my $od (qw(org dst)) {
229 $got->{"${od}_stallname"}
231 $got->{"${od}_qty_stall"}
236 <& dumptable:row, qa => $qa, sth => $sth, row => $f &>
238 <& dumptable:end, qa => $qa &>
242 foreach my $f (@flows) {
244 $f->{MaxQty}= $f->{'org_qty_agg'} < $f->{'dst_qty_agg'}
245 ? $f->{'org_qty_agg'} : $f->{'dst_qty_agg'};
246 $f->{MaxProfit}= $f->{MaxQty} * $f->{'unitprofit'};
247 $f->{MaxCapital}= $f->{MaxQty} * $f->{'org_price'};
249 $f->{MarginSortKey}= sprintf "%d",
250 $f->{'dst_price'} * 10000 / $f->{'org_price'};
251 $f->{Margin}= sprintf "%3.1f%%",
252 $f->{'dst_price'} * 100.0 / $f->{'org_price'} - 100.0;
254 $f->{ExpectedUnitProfit}=
255 $f->{'dst_price'} * (1.0 - $loss_per_league) ** $f->{'dist'}
258 my @uid= $f->{commodid};
259 foreach my $od (qw(org dst)) {
264 $f->{"${od}_stallid"}
265 if $qa->{ShowStalls};
267 $f->{UidLong}= join '_', @uid;
275 my $this= $uue % $base;
276 print STDERR "uue=$uue this=$this ";
281 $cmpu .= chr($this + ($this < 26 ? ord('a') :
282 $this < 52 ? ord('A')-26
284 print STDERR " uue=$uue this=$this cmpu=$cmpu\n";
285 die "$cmpu $uue ?" if length $cmpu > 20;
289 $f->{UidShort}= $cmpu;
291 if ($qa->{'debug'}) {
296 my $v= m/^[a-z]/ ? ord($&)-ord('a') :
297 m/^[A-Z]/ ? ord($&)-ord('A')+26 :
298 m/^[0-9]/ ? ord($&)-ord('0')+52 :
304 #print STDERR "(next)\n";
306 die "$f->{UidShort} $_ ?" unless defined $mul;
307 $outuid[$#outuid] += $v * $mul;
309 #print STDERR "$f->{UidShort} $_ $& v=$v mul=$mul ord()=".ord($&).
310 # "[vs.".ord('a').",".ord('A').",".ord('0')."]".
311 # " outuid=@outuid\n";
316 my $recons_long= join '_', @outuid;
317 $f->{UidLong} eq $recons_long or
318 die "$f->{UidLong} = $f->{UidShort} = $recons_long ?";
321 if (defined $qa->{"R$f->{UidShort}"} &&
322 !defined $qa->{"T$f->{UidShort}"}) {
329 % my $optimise= $specific && !$confusing && @islandids>1;
333 % if (@islandids<=1) {
337 Route contains archipelago(es), not just specific islands.
340 Route is complex - it visits the same island several times
341 and isn't a simple loop.
343 Therefore, optimal trade pattern not calculated.
345 % } else { # ========== OPTMISATION ==========
354 sprintf "%.20f %s", $_->{ExpectedUnitProfit}, $_->{Var}
361 foreach my $flow (@flows) {
362 if ($flow->{Suppress}) {
368 foreach my $od (qw(org dst)) {
369 my $cstname= join '_', (
374 $flow->{"${od}_price"},
375 $flow->{"${od}_stallid"},
378 push @{ $avail_csts{$cstname}{Flows} }, $flow->{Var};
379 $avail_csts{$cstname}{Qty}= $flow->{"${od}_qty_agg"};
382 foreach my $cstname (sort keys %avail_csts) {
383 my $c= $avail_csts{$cstname};
385 ". sprintf("%-30s","$cstname:")." ".
386 join("+", @{ $c->{Flows} }).
387 " <= ".$c->{Qty}."\n";
393 ", map { "$_->{Var} >= 0" } @flows)."
398 if ($qa->{'debug'}) {
407 my $input= pipethrough_prep();
408 print $input $cplex or die $!;
409 my $output= pipethrough_run_along($input, undef, 'glpsol',
410 qw(glpsol --cpxlp /dev/stdin -o /dev/stdout));
411 print "<pre>\n" if $qa->{'debug'};
412 my $found_section= 0;
416 print encode_entities($_) if $qa->{'debug'};
417 if (m/^\s*No\.\s+Column name\s+St\s+Activity\s/) {
418 die if $found_section>0;
422 next unless $found_section==1;
429 m/^\s*\d+\s+f(\d+)\s+\S+\s+(\d+)\s/ or die "$_ ?";
430 my $flow= $flows[$ix] or die;
431 $flow->{OptQty}= $qty;
432 $flow->{OptProfit}= $flow->{'unitprofit'} * $qty;
433 $flow->{OptCapital}= $flow->{OptQty} * $flow->{'org_price'};
435 print "</pre>\n" if $qa->{'debug'};
436 my $prerr= "\n=====\n$cplex\n=====\n$glpsol_out\n=====\n ";
437 pipethrough_run_finish($output,$prerr);
438 die $prerr unless $found_section;
441 $addcols->({ DoReverse => 1 }, qw(
444 $addcols->({ Total => 0, DoReverse => 1 }, qw(
450 % } # ========== OPTIMISATION ==========
454 % my $cdspan= $qa->{ShowStalls} ? ' colspan=2' : '';
455 % my $cdstall= $qa->{ShowStalls} ? '<th>Stall</th>' : '';
456 <table id="trades" rules=groups>
459 <% $qa->{ShowStalls} ? '<colgroup span=2>' : '' %>
470 <th<% $cdspan %>>Collect
471 <th<% $cdspan %>>Deliver
473 <th colspan=2>Collect
474 <th colspan=2>Deliver
478 <th colspan=3>Planned
483 <th>Island <% $cdstall %>
484 <th>Island <% $cdstall %>
502 <tr id="trades_sort">
503 % foreach my $col (@cols) {
507 % foreach my $flowix (0..$#flows) {
508 % my $flow= $flows[$flowix];
509 % my $rowid= "id_row_$flow->{UidShort}";
510 <tr id="<% $rowid %>" class="datarow<% $flowix & 1 %>">
511 <td><input type=hidden name=R<% $flow->{UidShort} %> value="">
512 <input type=checkbox name=T<% $flow->{UidShort} %> value=""
513 <% $flow->{Suppress} ? '' : 'checked' %> >
514 % foreach my $ci (1..$#cols) {
515 % my $col= $cols[$ci];
516 % my $v= $flow->{$col->{Name}};
517 % $col->{Total} += $v if defined $col->{Total};
518 % $v='' if !$col->{Text} && !$v;
519 % my $sortkey= $col->{SortColKey} ?
520 % $flow->{$col->{SortColKey}} : $v;
521 % $ts_sortkeys{$ci}{$rowid}= $sortkey;
522 <td <% $col->{Text} ? '' : 'align=right' %>><% $v |h %>
525 <tr id="trades_total">
528 % foreach my $ci (3..$#cols) {
529 % my $col= $cols[$ci];
531 % if (defined $col->{Total}) {
532 <% $col->{Total} |h %>
537 <& tabsort, cols => \@cols, table => 'trades', rowclass => 'datarow',
538 throw => 'trades_sort', tbrow => 'trades_total' &>
540 ts_sortkeys= <% to_json_protecttags(\%ts_sortkeys) %>;
541 function all_onload() {
544 window.onload= all_onload;
547 <input type=submit name=update value="Update">
549 % if ($optimise) { # ========== TRADING PLAN ==========
551 % my $iquery= $dbh->prepare('SELECT islandname FROM islands
552 % WHERE islandid = ?');
555 <h1>Voyage trading plan</h1>
557 % foreach my $i (0..$#islandids) {
559 <tr><td colspan=3><strong>
560 % $iquery->execute($islandids[$i]);
561 % my ($islandname) = $iquery->fetchrow_array();
563 Start at <% $islandname |h %>
565 Sail to <% $islandname |h %>
571 foreach my $od (qw(org dst)) {
572 foreach my $f (@flows) {
573 next if $f->{Suppress};
574 next unless $f->{"${od}_id"} == $islandids[$i];
575 next unless $f->{OptQty};
576 my $price= $f->{"${od}_price"};
577 my $stallname= $f->{"${od}_stallname"};
578 my $todo= \$flowlists{$od}{
580 (sprintf "%07d", ($od eq 'dst' ?
581 9999999-$price : $price)),
589 $$todo->{'commodname'}= $f->{'commodname'};
590 $$todo->{'stallname'}= $stallname;
591 $$todo->{Price}= $price;
592 $$todo->{Timestamp}= $f->{"${od}_timestamp"};
593 $$todo->{Qty} += $f->{OptQty};
594 $$todo->{Total}= $$todo->{Price} * $$todo->{Qty};
595 $$todo->{Stalls}= $f->{"${od}Stalls"};
596 if ($f->{'org_id'} == $f->{'dst_id'}) {
597 $$todo->{"${od}Arbitrage"}= 1;
604 my $show_flows= sub {
605 my ($od,$arbitrage,$collectdeliver) = @_;
608 % my $todo= $flowlists{$od};
609 % return unless $todo;
610 % foreach my $tkey (sort keys %$todo) {
611 % my $t= $todo->{$tkey};
612 % next if $t->{"${od}Arbitrage"} != $arbitrage;
613 % if (!$age_reported++) {
614 % my $age= $now - $t->{Timestamp};
615 % my $cellid= "da_${i}";
616 % $da_ages{$cellid}= $age;
618 (Data age: <span id="<% $cellid %>"><% prettyprint_age($age) %></span>)
619 % } elsif (!defined $total) {
623 % $total += $t->{Total};
624 % my $span= 0 + keys %{ $t->{Stalls} };
625 % my $td= "td rowspan=$span";
626 <tr class="datarow<% $dline %>">
627 <<% $td %>><% $collectdeliver %>
628 <<% $td %>><% $t->{'commodname'} |h %>
630 % my @stalls= sort keys %{ $t->{Stalls} };
632 % my $name= $stalls[$_[0]];
637 <<% $td %> align=right><% $t->{Price} |h %> poe ea.
638 <<% $td %> align=right><% $t->{Qty} |h %> unit(s)
639 <<% $td %> align=right><% $t->{Total} |h %> total
641 % foreach my $stallix (1..$#stalls) {
642 <tr class="datarow<% $dline %>">
643 % $pstall->($stallix);
649 % my $show_total= sub {
650 % my ($totaldesc)= @_;
651 % if (defined $total) {
654 <td colspan=2 align=right><% $totaldesc %>
655 <td align=right><% $total |h %> total
662 $show_flows->('dst',0,'Deliver'); $show_total->('Proceeds');
663 $show_flows->('org',1,'Collect'); $show_total->('(Arbitrage) outlay');
664 $show_flows->('dst',1,'Deliver'); $show_total->('(Arbitrage) proceeds');
665 $show_flows->('org',0,'Collect'); $show_total->('Outlay');
670 <& query_age:dataages, id2age => \%da_ages &>
672 % } # ========== TRADING PLAN ==========