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:37 <ceb> if tehre are 2 rows which take the same object and sell it for the
39 same profit at two other islands, choose the shortest route as the
41 16:37 <ceb> coconut buy 10 sell 16, at luthien or jorvik, in that example
42 16:38 <ceb> Do you see what I mean?
44 16:38 <ceb> I don't know how hard this is, but can you show only the suggested
45 trades to start ith and have a button to show all?
46 16:39 <ceb> Also, maybe colour to highlight the suggested trades?
48 16:40 <ceb> can it give a total investment/profit for the suggested trades?
49 16:40 <ceb> columns should be sortable with the small arrows as before
51 16:46 <Diziet> Oh the unticking has become broken.
53 16:51 <ceb> YPP interfaces have price then qty. You have qty then price. This
55 16:51 <ceb> the max column ordering is OK
56 16:51 <ceb> (alo profit and suggested are OK)
57 16:52 <Diziet> Err, you want qty on the left in those two but on the right in
59 16:53 <ceb> Yes (price and capital are not the same thing)
61 16:53 <ceb> for max the order in which you want to think about it is 'I need to
62 buy ten of them and that will cost me $total price)
65 16:46 <ceb> Also trading plan not functional but I guess you know that :-)
68 - potential cost of losses
71 ========== TODO ==========
85 my $sd_condition= sub {
87 my $islandid= $islandids[$ix];
88 if (defined $islandid) {
89 return "${bs}.islandid = $islandid";
91 push @query_params, $archipelagoes[$ix];
92 return "${bs}_islands.archipelago = ?";
97 # $islandpair{$a,$b}= [ $start_island_ix, $end_island_ix ]
99 my $specific= !grep { !defined $_ } @islandids;
102 foreach my $src_i (0..$#islandids) {
103 my $src_isle= $islandids[$src_i];
104 my $src_cond= $sd_condition->('sell',$src_i);
106 foreach my $dst_i ($src_i..$#islandids) {
107 my $dst_isle= $islandids[$dst_i];
108 my $dst_cond= $sd_condition->('buy',$dst_i);
109 if ($dst_i==$src_i and !defined $src_isle) {
110 # we always want arbitrage, but mentioning an arch
111 # once shouldn't produce intra-arch trades
113 "($dst_cond AND sell.islandid = buy.islandid)";
115 push @dst_conds, $dst_cond;
117 if ($specific && !$confusing &&
118 # With a circular route, do not carry goods round the loop
119 !($src_i==0 && $dst_i==$#islandids &&
120 $src_isle == $islandids[$dst_i])) {
121 if ($islandpair{$src_isle,$dst_isle}) {
124 $islandpair{$src_isle,$dst_isle}=
129 push @flow_conds, "$src_cond AND (
136 SELECT sell_islands.islandname org_name,
137 sell_islands.islandid org_id,
138 sell.price org_price,
139 buy_islands.islandname dst_name,
140 buy_islands.islandid dst_id,
142 ".($qa->{ShowStalls} ? "
143 sell.stallid org_stallid,
144 sell_stalls.stallname org_stallname,
146 buy.stallid dst_stallid,
147 buy_stalls.stallname dst_stallname,
150 sum(sell.qty) org_qty,
151 sum(buy.qty) dst_qty,
153 commods.commodname commodname,
154 commods.commodid commodid,
155 commods.unitmass unitmass,
156 commods.unitvolume unitvolume,
157 buy.price - sell.price unitprofit
159 JOIN buy on commods.commodid = buy.commodid
160 JOIN sell on commods.commodid = sell.commodid
161 JOIN islands as sell_islands on sell.islandid = sell_islands.islandid
162 JOIN islands as buy_islands on buy.islandid = buy_islands.islandid
163 ".($qa->{ShowStalls} ? "
164 JOIN stalls as sell_stalls on sell.stallid = sell_stalls.stallid
165 JOIN stalls as buy_stalls on buy.stallid = buy_stalls.stallid
171 AND buy.price > sell.price
172 ".($qa->{ShowStalls} ? "" : "
173 GROUP BY commods.commodid, org_id, org_price, dst_id, dst_price
175 ORDER BY org_name, dst_name, commodname, unitprofit DESC,
176 org_price, dst_price DESC
179 my $sth= $dbh->prepare($stmt);
180 $sth->execute(@query_params);
187 foreach my $name (@_) {
188 push @cols, { Name => $name, %$base };
192 if ($qa->{ShowStalls}) {
193 $addcols->({ Text => 1 }, qw(
194 org_name org_stallname
195 dst_name dst_stallname
198 $addcols->({Text => 1 }, qw(
202 $addcols->({ Text => 1 }, qw(commodname));
204 qw( org_qty org_price dst_qty dst_price
205 Margin unitprofit MaxQty
211 % if ($qa->{'debug'}) {
214 <% join(' | ',@query_params) |h %>
218 <& dumptable:start, qa => $qa, sth => $sth &>
221 % while ($f= $sth->fetchrow_hashref()) {
225 $f->{Var}= "f$f->{Ix}";
227 $f->{MaxQty}= $f->{'org_qty'} < $f->{'dst_qty'}
228 ? $f->{'org_qty'} : $f->{'dst_qty'};
229 $f->{MaxProfit}= $f->{MaxQty} * $f->{'unitprofit'};
230 $f->{MaxCapital}= $f->{MaxQty} * $f->{'org_price'};
232 $f->{Margin}= sprintf "%3.1f%%",
233 $f->{'dst_price'} * 100.0 / $f->{'org_price'} - 100.0;
235 $f->{"org_stallid"}= $f->{"dst_stallid"}= 'all'
236 if !$qa->{ShowStalls};
238 my @uid= $f->{commodid};
239 foreach my $od (qw(org dst)) {
244 $f->{"${od}_stallid"}
245 if $qa->{ShowStalls};
247 $f->{UidLong}= join '_', @uid;
255 my $this= $uue % $base;
256 print STDERR "uue=$uue this=$this ";
261 $cmpu .= chr($this + ($this < 26 ? ord('a') :
262 $this < 52 ? ord('A')-26
264 print STDERR " uue=$uue this=$this cmpu=$cmpu\n";
265 die "$cmpu $uue ?" if length $cmpu > 20;
269 $f->{UidShort}= $cmpu;
271 if ($qa->{'debug'}) {
276 my $v= m/^[a-z]/ ? ord($&)-ord('a') :
277 m/^[A-Z]/ ? ord($&)-ord('A')+26 :
278 m/^[0-9]/ ? ord($&)-ord('0')+52 :
284 #print STDERR "(next)\n";
286 die "$f->{UidShort} $_ ?" unless defined $mul;
287 $outuid[$#outuid] += $v * $mul;
289 #print STDERR "$f->{UidShort} $_ $& v=$v mul=$mul ord()=".ord($&).
290 # "[vs.".ord('a').",".ord('A').",".ord('0')."]".
291 # " outuid=@outuid\n";
296 my $recons_long= join '_', @outuid;
297 $f->{UidLong} eq $recons_long or
298 die "$f->{UidLong} = $f->{UidShort} = $recons_long ?";
301 if ($qa->{"R$f->{UidShort}"} && !$qa->{"T$f->{UidShort}"}) {
308 <& dumptable:row, qa => $qa, sth => $sth, row => $f &>
310 <& dumptable:end, qa => $qa &>
313 % my $optimise= $specific && !$confusing && @islandids>1;
317 % if (@islandids<=1) {
321 Route contains archipelago(es), not just specific islands.
324 Route is complex - it visits the same island several times
325 and isn't a simple loop.
327 Therefore, optimal trade pattern not calculated.
329 % } else { # ========== OPTMISATION ==========
337 ", map { "$_->{unitprofit} $_->{Var}" } @flows)."
343 foreach my $flow (@flows) {
344 if ($flow->{Suppress}) {
350 foreach my $od (qw(org dst)) {
351 my $cstname= join '_', (
356 $flow->{"${od}_price"},
357 $flow->{"${od}_stallid"},
360 push @{ $avail_csts{$cstname}{Flows} }, $flow->{Var};
361 $avail_csts{$cstname}{Qty}= $flow->{"${od}_qty"};
364 foreach my $cstname (sort keys %avail_csts) {
365 my $c= $avail_csts{$cstname};
367 ". sprintf("%-30s","$cstname:")." ".
368 join("+", @{ $c->{Flows} }).
369 " <= ".$c->{Qty}."\n";
375 ", map { "$_->{Var} >= 0" } @flows)."
380 if ($qa->{'debug'}) {
389 my $input= pipethrough_prep();
390 print $input $cplex or die $!;
391 my $output= pipethrough_run_along($input, undef, 'glpsol',
392 qw(glpsol --cpxlp /dev/stdin -o /dev/stdout));
393 print "<pre>\n" if $qa->{'debug'};
394 my $found_section= 0;
396 print encode_entities($_) if $qa->{'debug'};
397 if (m/^\s*No\.\s+Column name\s+St\s+Activity\s/) {
398 die if $found_section>0;
402 next unless $found_section==1;
409 m/^\s*\d+\s+f(\d+)\s+\S+\s+(\d+)\s/ or die "$_ ?";
410 my $flow= $flows[$ix] or die;
411 $flow->{OptQty}= $qty;
412 $flow->{OptProfit}= $flow->{'unitprofit'} * $qty;
413 $flow->{OptCapital}= $flow->{OptQty} * $flow->{'org_price'};
415 print "</pre>\n" if $qa->{'debug'};
416 pipethrough_run_finish($output, 'glpsol');
417 die unless $found_section;
423 $addcols->({ Total => 0 }, qw(
429 % } # ========== OPTIMISATION ==========
432 % my $cdspan= $qa->{ShowStalls} ? ' colspan=2' : '';
433 % my $cdstall= $qa->{ShowStalls} ? '<th>Stall</th>' : '';
437 <% $qa->{ShowStalls} ? '<colgroup span=2>' : '' %>
448 <th<% $cdspan %>>Collect
449 <th<% $cdspan %>>Deliver
451 <th colspan=2>Collect
452 <th colspan=2>Deliver
456 <th colspan=3>Suggested
461 <th>Island <% $cdstall %>
462 <th>Island <% $cdstall %>
480 % foreach my $flow (@flows) {
482 <td><input type=hidden name=R<% $flow->{UidShort} %> value="">
483 <input type=checkbox name=T<% $flow->{UidShort} %> value=""
484 <% $flow->{Suppress} ? '' : 'checked' %> >
485 % foreach my $ci (0..$#cols) {
486 % my $col= $cols[$ci];
487 % my $v= $flow->{$col->{Name}};
488 % $col->{Total} += $v if defined $col->{Total};
489 % $v='' if !$col->{Text} && !$v;
490 <td <% $col->{Text} ? '' : 'align=right' %>><% $v |h %>
496 % foreach my $ci (2..$#cols) {
497 % my $col= $cols[$ci];
499 % if (defined $col->{Total}) {
500 <% $col->{Total} |h %>
505 <input type=submit name=update value="Update">
507 % if ($optimise) { # ========== TRADING PLAN ==========
509 % my $iquery= $dbh->prepare('SELECT islandname FROM islands
510 % WHERE islandid = ?');
512 <h1>Voyage trading plan</h1>
514 % foreach my $i (0..$#islandids) {
515 <tr><td colspan=4><strong>
516 % $iquery->execute($islandids[$i]);
517 % my ($islandname) = $iquery->fetchrow_array();
519 Start at <% $islandname |h %>
521 Sail to <% $islandname |h %>
524 % foreach my $od (qw(dst org)) {
525 % my $sign= $od eq 'dst' ? -1 : +1;
526 % foreach my $f (sort {
527 % $a->{'commodname'} cmp $b->{'commodname'}
528 % or $sign * ($a->{"${od}_price"} <=> $b->{"${od}_price"})
529 % or $a->{"${od}_stallname"} cmp $b->{"${od}_stallname"}
531 % next if $f->{Suppress};
532 % next unless $f->{"${od}_id"} == $islandids[$i];
533 % next unless $f->{OptQty};
540 % } # ========== TRADING PLAN ==========