#!/usr/bin/perl -w
#a little script for demonstrating cobwebbing (in the nonlinear dynamics sense)
#by Thomas Orgis <thomas@orgis.org>, licensed under the Artistic License

#~/lib/perl ist the first place to look!
use lib $ENV{HOME}.'/lib';
use lib $ENV{HOME}.'/lib/perl';

use Param;

my $const = Param::Parse
(
	{'info', 'Cobwebbing. You give me parameters (some iteration formula would be good), I spit data points out to STDOUT that you may plot with Gnuplot or whatever sane program is out there for that stuff.'},
	[
		'begin',0.1,'b','start value',
		'nit',10,'n','number of iterations',
		'formula','$r*$x*(1-$x)','f','the formula in PERL syntax with $x being the last x value',
		'gnuplot',0,'g','make gnuplot script including the map and y=x',
		'gp4syntax',1,'y','use Gnuplot 4 syntax instead of Gnuplot 3.7 syntax (concerns "set key off" vs. "unset key" only...)',
		'range','0:1','r','range to plot in',
		'samples',1000,'s','number of samples for plot',
		'param','2.8','p','an array of parameters that you can use as array @A in the formula (comma-separeted list), first ralue is also called $r'
	]
);

my @A = eval '('.$const->{param}.')';
my $r = defined $A[0] ? $A[0] : 0;

if($const->{gnuplot})
{
	print "set xrange [$const->{range}]\n";
	print "set samples $const->{samples}\n";
	print $const->{gp4syntax} ? "unset key\n" : "set key off\n";
	my $func = $const->{formula};
	$func =~ s/\$x/x/g;
	$func =~ s/\$r/$r/g;
	$func =~ s/\$A\[(\d+)\]/$A[$1]/;
	print "plot $func w l, x w l, '-' w l\n";
}

$x = eval($const->{begin});
print "$x\t0\n";
my $nx = eval($const->{formula});
print "$x\t$nx\n";
$x = $nx;

for(my $i = 1; $i <= $const->{nit}; ++$i)
{
	$nx = eval($const->{formula});
	print "$x\t$x\n$x\t$nx\n";
	$x = $nx;
}

if($const->{gnuplot}){ print "e\n"; }
