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 16:46 <ceb> Also trading plan not functional but I guess you know that :-)
40 use POST for update. Hrrm.
44 adjustable potential cost of losses (rather than fixed 1e-BIG per league)
48 ========== TODO ==========
59 my $loss_per_league= 1e-7;
64 my $sd_condition= sub {
66 my $islandid= $islandids[$ix];
67 if (defined $islandid) {
68 return "${bs}.islandid = $islandid";
70 push @query_params, $archipelagoes[$ix];
71 return "${bs}_islands.archipelago = ?";
76 # $islandpair{$a,$b}= [ $start_island_ix, $end_island_ix ]
78 my $specific= !grep { !defined $_ } @islandids;
81 foreach my $src_i (0..$#islandids) {
82 my $src_isle= $islandids[$src_i];
83 my $src_cond= $sd_condition->('sell',$src_i);
85 foreach my $dst_i ($src_i..$#islandids) {
86 my $dst_isle= $islandids[$dst_i];
87 my $dst_cond= $sd_condition->('buy',$dst_i);
88 if ($dst_i==$src_i and !defined $src_isle) {
89 # we always want arbitrage, but mentioning an arch
90 # once shouldn't produce intra-arch trades
92 "($dst_cond AND sell.islandid = buy.islandid)";
94 push @dst_conds, $dst_cond;
96 if ($specific && !$confusing &&
97 # With a circular route, do not carry goods round the loop
98 !($src_i==0 && $dst_i==$#islandids &&
99 $src_isle == $islandids[$dst_i])) {
100 if ($islandpair{$src_isle,$dst_isle}) {
103 $islandpair{$src_isle,$dst_isle}=
108 push @flow_conds, "$src_cond AND (
115 SELECT sell_islands.islandname org_name,
116 sell_islands.islandid org_id,
117 sell.price org_price,
118 sell_uploads.timestamp org_timestamp,
119 buy_islands.islandname dst_name,
120 buy_islands.islandid dst_id,
122 buy_uploads.timestamp dst_timestamp,
123 ".($qa->{ShowStalls} ? "
124 sell.stallid org_stallid,
125 sell_stalls.stallname org_stallname,
127 buy.stallid dst_stallid,
128 buy_stalls.stallname dst_stallname,
131 sum(sell.qty) org_qty,
132 sum(buy.qty) dst_qty,
134 commods.commodname commodname,
135 commods.commodid commodid,
136 commods.unitmass unitmass,
137 commods.unitvolume unitvolume,
139 buy.price - sell.price unitprofit
141 JOIN buy ON commods.commodid = buy.commodid
142 JOIN sell ON commods.commodid = sell.commodid
143 JOIN islands AS sell_islands ON sell.islandid = sell_islands.islandid
144 JOIN islands AS buy_islands ON buy.islandid = buy_islands.islandid
145 JOIN uploads AS sell_uploads ON sell.islandid = sell_uploads.islandid
146 JOIN uploads AS buy_uploads ON buy.islandid = buy_uploads.islandid
147 ".($qa->{ShowStalls} ? "
148 JOIN stalls AS sell_stalls ON sell.stallid = sell_stalls.stallid
149 JOIN stalls AS buy_stalls ON buy.stallid = buy_stalls.stallid
151 JOIN dists ON aiid = sell.islandid AND biid = buy.islandid
156 AND buy.price > sell.price
157 ".($qa->{ShowStalls} ? "" : "
158 GROUP BY commods.commodid, org_id, org_price, dst_id, dst_price
160 ORDER BY org_name, dst_name, commodname, unitprofit DESC,
161 org_price, dst_price DESC
164 my $sth= $dbh->prepare($stmt);
165 $sth->execute(@query_params);
168 my @cols= ({ NoSort => 1 });
172 foreach my $name (@_) {
173 my $col= { Name => $name, %$base };
174 $col->{Numeric}=1 if !$col->{Text};
179 if ($qa->{ShowStalls}) {
180 $addcols->({ Text => 1 }, qw(
181 org_name org_stallname
182 dst_name dst_stallname
185 $addcols->({Text => 1 }, qw(
189 $addcols->({ Text => 1 }, qw(commodname));
190 $addcols->({ DoReverse => 1 },
191 qw( org_price org_qty dst_price dst_qty
192 Margin unitprofit MaxQty
198 % if ($qa->{'debug'}) {
201 <% join(' | ',@query_params) |h %>
205 <& dumptable:start, qa => $qa, sth => $sth &>
208 % while ($f= $sth->fetchrow_hashref()) {
212 $f->{Var}= "f$f->{Ix}";
214 $f->{MaxQty}= $f->{'org_qty'} < $f->{'dst_qty'}
215 ? $f->{'org_qty'} : $f->{'dst_qty'};
216 $f->{MaxProfit}= $f->{MaxQty} * $f->{'unitprofit'};
217 $f->{MaxCapital}= $f->{MaxQty} * $f->{'org_price'};
219 $f->{Margin}= sprintf "%3.1f%%",
220 $f->{'dst_price'} * 100.0 / $f->{'org_price'} - 100.0;
222 $f->{"org_stallid"}= $f->{"dst_stallid"}= 'all'
223 if !$qa->{ShowStalls};
225 $f->{ExpectedUnitProfit}=
226 $f->{'dst_price'} * (1.0 - $loss_per_league) ** $f->{'dist'}
229 my @uid= $f->{commodid};
230 foreach my $od (qw(org dst)) {
235 $f->{"${od}_stallid"}
236 if $qa->{ShowStalls};
238 $f->{UidLong}= join '_', @uid;
246 my $this= $uue % $base;
247 print STDERR "uue=$uue this=$this ";
252 $cmpu .= chr($this + ($this < 26 ? ord('a') :
253 $this < 52 ? ord('A')-26
255 print STDERR " uue=$uue this=$this cmpu=$cmpu\n";
256 die "$cmpu $uue ?" if length $cmpu > 20;
260 $f->{UidShort}= $cmpu;
262 if ($qa->{'debug'}) {
267 my $v= m/^[a-z]/ ? ord($&)-ord('a') :
268 m/^[A-Z]/ ? ord($&)-ord('A')+26 :
269 m/^[0-9]/ ? ord($&)-ord('0')+52 :
275 #print STDERR "(next)\n";
277 die "$f->{UidShort} $_ ?" unless defined $mul;
278 $outuid[$#outuid] += $v * $mul;
280 #print STDERR "$f->{UidShort} $_ $& v=$v mul=$mul ord()=".ord($&).
281 # "[vs.".ord('a').",".ord('A').",".ord('0')."]".
282 # " outuid=@outuid\n";
287 my $recons_long= join '_', @outuid;
288 $f->{UidLong} eq $recons_long or
289 die "$f->{UidLong} = $f->{UidShort} = $recons_long ?";
292 if (defined $qa->{"R$f->{UidShort}"} &&
293 !defined $qa->{"T$f->{UidShort}"}) {
300 <& dumptable:row, qa => $qa, sth => $sth, row => $f &>
302 <& dumptable:end, qa => $qa &>
305 % my $optimise= $specific && !$confusing && @islandids>1;
309 % if (@islandids<=1) {
313 Route contains archipelago(es), not just specific islands.
316 Route is complex - it visits the same island several times
317 and isn't a simple loop.
319 Therefore, optimal trade pattern not calculated.
321 % } else { # ========== OPTMISATION ==========
330 sprintf "%.20f %s", $_->{ExpectedUnitProfit}, $_->{Var}
337 foreach my $flow (@flows) {
338 if ($flow->{Suppress}) {
344 foreach my $od (qw(org dst)) {
345 my $cstname= join '_', (
350 $flow->{"${od}_price"},
351 $flow->{"${od}_stallid"},
354 push @{ $avail_csts{$cstname}{Flows} }, $flow->{Var};
355 $avail_csts{$cstname}{Qty}= $flow->{"${od}_qty"};
358 foreach my $cstname (sort keys %avail_csts) {
359 my $c= $avail_csts{$cstname};
361 ". sprintf("%-30s","$cstname:")." ".
362 join("+", @{ $c->{Flows} }).
363 " <= ".$c->{Qty}."\n";
369 ", map { "$_->{Var} >= 0" } @flows)."
374 if ($qa->{'debug'}) {
383 my $input= pipethrough_prep();
384 print $input $cplex or die $!;
385 my $output= pipethrough_run_along($input, undef, 'glpsol',
386 qw(glpsol --cpxlp /dev/stdin -o /dev/stdout));
387 print "<pre>\n" if $qa->{'debug'};
388 my $found_section= 0;
390 print encode_entities($_) if $qa->{'debug'};
391 if (m/^\s*No\.\s+Column name\s+St\s+Activity\s/) {
392 die if $found_section>0;
396 next unless $found_section==1;
403 m/^\s*\d+\s+f(\d+)\s+\S+\s+(\d+)\s/ or die "$_ ?";
404 my $flow= $flows[$ix] or die;
405 $flow->{OptQty}= $qty;
406 $flow->{OptProfit}= $flow->{'unitprofit'} * $qty;
407 $flow->{OptCapital}= $flow->{OptQty} * $flow->{'org_price'};
409 print "</pre>\n" if $qa->{'debug'};
410 pipethrough_run_finish($output, 'glpsol');
411 die unless $found_section;
414 $addcols->({ DoReverse => 1 }, qw(
417 $addcols->({ Total => 0, DoReverse => 1 }, qw(
423 % } # ========== OPTIMISATION ==========
427 % my $cdspan= $qa->{ShowStalls} ? ' colspan=2' : '';
428 % my $cdstall= $qa->{ShowStalls} ? '<th>Stall</th>' : '';
429 <table id="trades" rules=groups>
432 <% $qa->{ShowStalls} ? '<colgroup span=2>' : '' %>
443 <th<% $cdspan %>>Collect
444 <th<% $cdspan %>>Deliver
446 <th colspan=2>Collect
447 <th colspan=2>Deliver
451 <th colspan=3>Planned
456 <th>Island <% $cdstall %>
457 <th>Island <% $cdstall %>
475 <tr id="trades_sort">
476 % foreach my $col (@cols) {
480 % foreach my $flowix (0..$#flows) {
481 % my $flow= $flows[$flowix];
482 % my $rowid= "id_row_$flow->{UidShort}";
483 <tr id="<% $rowid %>" class="datarow<% $flowix & 1 %>">
484 <td><input type=hidden name=R<% $flow->{UidShort} %> value="">
485 <input type=checkbox name=T<% $flow->{UidShort} %> value=""
486 <% $flow->{Suppress} ? '' : 'checked' %> >
487 % foreach my $ci (1..$#cols) {
488 % my $col= $cols[$ci];
489 % my $v= $flow->{$col->{Name}};
490 % $col->{Total} += $v if defined $col->{Total};
491 % $v='' if !$col->{Text} && !$v;
492 % $ts_sortkeys{$ci}{$rowid}= $v;
493 <td <% $col->{Text} ? '' : 'align=right' %>><% $v |h %>
496 <tr id="trades_total">
499 % foreach my $ci (3..$#cols) {
500 % my $col= $cols[$ci];
502 % if (defined $col->{Total}) {
503 <% $col->{Total} |h %>
508 <& tabsort, cols => \@cols, table => 'trades', rowclass => 'datarow',
509 throw => 'trades_sort', tbrow => 'trades_total' &>
511 ts_sortkeys= <% to_json_protecttags(\%ts_sortkeys) %>;
512 function all_onload() {
515 window.onload= all_onload;
518 <input type=submit name=update value="Update">
520 % if ($optimise) { # ========== TRADING PLAN ==========
522 % my $iquery= $dbh->prepare('SELECT islandname FROM islands
523 % WHERE islandid = ?');
525 <h1>Voyage trading plan</h1>
527 % foreach my $i (0..$#islandids) {
528 <tr><td colspan=4><strong>
529 % $iquery->execute($islandids[$i]);
530 % my ($islandname) = $iquery->fetchrow_array();
532 Start at <% $islandname |h %>
534 Sail to <% $islandname |h %>
537 % foreach my $od (qw(dst org)) {
538 % my $sign= $od eq 'dst' ? -1 : +1;
540 % foreach my $f (@flows) {
541 % next if $f->{Suppress};
542 % next unless $f->{"${od}_id"} == $islandids[$i];
543 % next unless $f->{OptQty};
544 % my $price= $f->{"${od}_price"};
545 % my $stallname= $f->{"${od}_stallname"};
546 % my $todo= \$todo{ $f->{'commodname'},
547 % (sprintf "%07d", $price),
549 % $$todo= { } unless $$todo;
550 % $$todo->{'commodname'}= $f->{'commodname'};
551 % $$todo->{'stallname'}= $stallname;
552 % $$todo->{Price} += $price;
553 % $$todo->{Qty} += $f->{OptQty};
554 % $$todo->{Total} = $$todo->{Price} * $$todo->{Qty};
555 % $$todo->{Timestamp} = $f->{"${od}_timestamp"};
559 % foreach my $tkey (sort keys %todo) {
560 % my $t= $todo{$tkey};
561 % $total += $t->{Total};
562 <tr class="datarow<% $dline %>"><td>
563 % if ($od eq 'org') {
568 <td><% $t->{'commodname'} |h %>
569 <td align=right><% $t->{Price} |h %> each
570 % if ($qa->{ShowStalls}) {
571 <td><% $t->{'stallname'} |h %>
573 <td align=right><% $t->{Qty} |h %> unit(s)
574 <td align=right><% $t->{Total} |h %> total
579 <td colspan=<% 2+!!$qa->{ShowStalls} %>>
580 <% (values %todo)[0]->{Timestamp} %>
582 % if ($od eq 'org') {
587 <td align=right><% $total |h %> total
593 % } # ========== TRADING PLAN ==========