package Simulation::Tools::SynSim;

use vars qw( $VERSION );
$VERSION = '0.9.1';

#################################################################################
#                                                                              	#
#  Copyright (C) 2000,2002 Wim Vanderbauwhede. All rights reserved.             #
#  This program is free software; you can redistribute it and/or modify it      #
#  under the same terms as Perl itself.                                         #
#                                                                              	#
#################################################################################

#headers
#
#Main module for SynSim simulation automation tool.
#The first part creates the module Loops.pm based on the data file;	
#this module is then called via eval() and used by Simulation::Tools::SynSim.pm 
#Loops calls &SynSim::main() at every pass through the loops.
#
#$Id: Simulation::Tools::SynSim.pm,v 1.6 2002/10/16 15:27:40 wim Exp $
#


use sigtrap qw(die untrapped normal-signals
               stack-trace any error-signals); 
use strict;
use Cwd;
use Exporter;
use lib '.';

@Simulation::Tools::SynSim::ISA = qw(Exporter);
@Simulation::Tools::SynSim::EXPORT = qw(
		     &synsim
		     &setup
                  );

sub synsim {
my $datafile=shift||'synsim.data';

################################################################################
#
#                     Create  module Simulation::Tools::SynSim::Loops.pm
#
################################################################################

my @flags=my ($batch,$interactive,$nosims,$plot,$verbose)=@{&preprocess_commandline($datafile)};
my $dataset=$datafile;
$dataset=~s/\.data//;
print STDERR "\nCreating Loops.pm...\n";

my $dataref=&allow_multiple_sims($datafile);
my $simref=&generate_loop_module($dataref,$dataset);

################################################################################
#
#                     Do the actual simulations
#
################################################################################

&execute_loop($datafile,$dataset,$simref,\@flags) && do {
unlink "Loops_$dataset.pm";
};

return 1;
}
#===============================================================================

################################################################################
##
##                    Subroutines
##
################################################################################

sub preprocess_commandline {
my $datafile=$_[0];
my ($batch,$interactive,$nosims,$plot,$verbose)=(0,0,0,0,0);
my $default=1;
if(@ARGV) {
my $dtf=0;
    foreach(@ARGV){
      if(/-f/){$dtf=1;next}
      if($dtf==1){
      $_[0]=$_;$datafile=$_;$default=0;$dtf=0;
}
      if(/-b/){$batch=1;next} 
      if(/-i/){$interactive=1;next}
      if(/-N/i){$nosims=1;next}

      if(/-p/){$plot=1;next}
      if(/-v/){$verbose=1;next}
      if(/-h|-\?/){ 
my $script=$0;
$script=~s/.*\///;
die <<"HELP";

The script must be executed in a subdirectory of the directory
containing the script.
This directory must contain at least a TEMPLATES/SIMTYPE subdir 
with the simulation templates, and a data file. See documentation for more information.

syntax: ../$script [-h -i -p -b -v -N -f datafile]

Possible switches:

none: defaults to -f $datafile
 -f [filename]: 'file input'. Expects a file containing info about simulation and device type.
 -i : interactive. Creates a plot on the screen after every iteration.
 -p : plot.  Not fully implemented yet.
 -v : 'verbose'. Sends simulator output to STDOUT, otherwise to [simulator].log file
 -N : 'No simulations'. Does only postprocessing
 -h, -? : this help
HELP
}
    } # foreach @ARGV

    if($default) {
print STDERR "Assuming $datafile as input data filename\n";
}
    } else {
print STDERR "No command line arguments given. Assuming $datafile as input data filename\n";
}

if(not(-e "./TEMPLATES" && -d "./TEMPLATES" && -e "./$datafile")) {
die  "
The script must be executed in a device directory. 
A device directory must contain a TEMPLATES subdir 
with the device and analysis templates, and a data file
";
}

return [$batch,$interactive,$nosims,$plot,$verbose];
} #END of preprocess_commandline

#-------------------------------------------------------------------------------
#
# This subroutine takes a reference to %specific as generated by allow_multiple_sims($datafile) and passes it on to fill_data_hash_multi;
# It gets back %data, which contains the list of parameters and their value-list for every simtype
#


sub generate_loop_module {
my $specificref=shift; #this is the reference to %specific, the hash of arrays of data for each sim
my $dataset=shift;

my $dataref=&fill_data_hash_multi($specificref);
my %data=%{$dataref};

open(MOD,">Loops_$dataset.pm");

print MOD &strip(<<"ENDHEAD");
*package Loops_$dataset;
*#
*################################################################################
*# Author:           WV                                                         #
*# Date  : 21/11/2000;01/08/2002                                                #
*#                                                                              #
*# Module to support script for SynSim simulations.                             #
*# The subroutine in this module generates the loop to do multiple simulations. #
*# This module is generated by Simulation::Tools::SynSim.pm                                     #
*#                                                                              #
*################################################################################
*
*use sigtrap qw(die untrapped normal-signals
*               stack-trace any error-signals); 
*use strict;
*
*use FileHandle;
*use Exporter;
*
*\@Loops_${dataset}::ISA = qw(Exporter);
*\@Loops_${dataset}::EXPORT = qw(
ENDHEAD

foreach my $sim (keys %data) {
print MOD &strip(
"*			execute_${sim}_loop\n");
}
print MOD &strip('
*                  );
*
');

my @sims=();
foreach my $sim (keys %data) { 
my $title=$data{$sim}{TITLE};
delete $data{$sim}{TITLE};

push @sims,$sim;
print MOD &strip(<<"ENDSUBHEAD");

*use lib '..','../..';
*use Simulation::Tools::SynSim::Main;
*use Simulation::Tools::SynSim::PostProcessors;
*
*sub execute_${sim}_loop {
*my \$dataset=shift;
*my \$dirname=\"${sim}-\$dataset\";
*my \$flagsref=shift;
*my \$i=0;
*my \$returnvalue;
*my \$resheader='';
*my \%last=();
*my \%sweepeddata=();

ENDSUBHEAD

# TITLE is treated separately
print MOD &strip(
"*my \$TITLE = '$title';\n"
);
# define vars
 foreach my $par (sort keys %{$data{$sim}}) {
if ($data{$sim}{$par}!~/,/) { # if just one item
$data{$sim}{$par}=~s/^\'//;
$data{$sim}{$par}=~s/\'$//;
print MOD &strip(
"*my \$${par} = '$data{$sim}{$par}';\n"
);
} 
  }
#assign common hash items
print MOD &strip(
"*my \%data=();\n"
);
print MOD &strip('
*	print STDERR "# SynSim configuration variables\n";
*	print STDERR "#","-" x 79,"\n#  TITLE : '.$title.'\n";
*	$resheader.= "# SynSim configuration variables\n";
*	$resheader.= "#"."-" x 79;
*	$resheader.= "\n#  TITLE : '.$title.'\n";
');
print MOD &strip(
"*\$data{TITLE}=\$TITLE;\n"
);
my $nsims=1;
my $prevkey='';
foreach my $par (sort keys %{$data{$sim}}) {
  if($par=~/^_/ && $prevkey!~/^_/) {
print MOD &strip('
*	print STDERR "#","-" x 79,"\n";
*	print STDERR "# Static parameters used in the simulation:\n";
*	print STDERR "#","-" x 79,"\n";
*	$resheader.= "#"."-" x 79;
*	$resheader.= "\n# Static parameters used in the simulation:\n";
*	$resheader.= "#"."-" x 79;
*	$resheader.= "\n";
');
  }

  if ($data{$sim}{$par}!~/,/) { # if just one item
    if($data{$sim}{$par}=~/(\d+)\s*\.\.\s*(\d+)/) {
      my $b=$1;
      my $e=$2;
      my $patt="$b .. $e";
      $nsims=$e-$b+1;
      print MOD &strip(
"*my \@tmp$par=($patt);
*\$data{$par} = [\@tmp$par];
*print STDERR \"# $par = \$$par\\n\";
*\$resheader.=  \"# $par = \$$par\\n\";
");

    } elsif($data{$sim}{$par}=~/;/) {
      my $tmp=$data{$sim}{$par};
      my $tmps=($tmp=~s/;/,/g);
      if($tmps>=$nsims){$nsims=$tmps+1}
      print MOD &strip(
"*my \@tmp$par=split(/;/,\$$par);
*\$data{$par} = [\@tmp$par];
*print STDERR \"# $par = \$$par\\n\";
*\$resheader.= \"# $par = \$$par\\n\";
");
    } else {
      if($par=~/^_/) {
	print MOD &strip(
"*\$data{$par} = [\$$par];
*print STDERR \"# $par = \$$par\\n\";
*\$resheader.= \"# $par = \$$par\\n\";
");
      } else {
	print MOD &strip(
"*\$data{$par} = \$$par; # no reason for array
*print STDERR \"#  $par : \$$par\\n\"; # no reason to print
*\$resheader.= \"#  $par : \$$par\\n\"; # no reason to print
");

      }
    }
  }
$prevkey=$par;
}

print MOD &strip(
"*my \$nsims=$nsims;\n"
);


foreach my $par (sort keys %{$data{$sim}}) {

  if ($data{$sim}{$par}=~/,/) { # if more than one item
my $parlist=$data{$sim}{$par};
$parlist=~s/,/ /g;
    print MOD &strip(
		     "*my \@${par}list = qw($parlist);
*\$last{$par}=\$${par}list[\@${par}list-1];
*foreach my \$${par} (\@${par}list) {\n"
		    );
  } 
}
print MOD &strip(
"*\$i++;
*open(RES,\">\$dirname\/${sim}_C\$i.res\")|| do {print STDERR \"Can\'t open \$dirname\/${sim}_\$i.res\";};
");
print MOD &strip('
*	print STDERR "#","-" x 79,"\n";
*	print STDERR "# Parameters for simulation run $i:\n";
*	print RES $resheader;
*	print RES "#"."-" x 79,"\n";
*	print RES "# Parameters for simulation run $i:\n";
');

foreach my $par (sort keys %{$data{$sim}}) {

if ($data{$sim}{$par}=~/,/) { # if more than one item

print MOD &strip(
"*\$data{$par} = [\$$par];
*\$sweepeddata{$par} = \$$par;
*print STDERR \"# $par = \$$par\\n\";
*print RES \"# $par = \$$par\\n\";
");
  } 
  }
print MOD &strip(
"* close RES;
*my \$dataref = [\$nsims,\\\%data];
*\$returnvalue=&main(\$dataset,\$i,\$dataref,\$flagsref);
*
");

my $simtempl=$data{$sim}{SIMTYPE};
my $anatempl=$data{$sim}{ANALYSIS_TEMPLATE};
# this makes generic names impossible.
#my $subref='gen_'.$simtempl.'_'.$anatempl;
# this is simpler and should be better
my $subref=$anatempl;

print MOD &strip(<<"ENDPP");
*chdir \$dirname;
*#my \$dataref = [\$nsims,\\\%data,\\\%sweepeddata,\\\%last];
*\$dataref = [\$nsims,\\\%data,\\\%sweepeddata,\\\%last];
*&Simulation::Tools::SynSim::PostProcessors::$subref(\$dataset,\$i,\$dataref,\$flagsref,\$returnvalue);
*chdir '..';
ENDPP

foreach my $par (reverse sort keys %{$data{$sim}}) {
  if ($data{$sim}{$par}=~/,/) {
    print MOD &strip(
		     "*} #END of $par\n"
		    );
  }
}

#my $simtempl=$data{$sim}{SIMTYPE};
#my $anatempl=$data{$sim}{ANALYSIS_TEMPLATE};
#my $subref='gen_'.$simtempl.'_'.$anatempl;
print MOD &strip(<<"ENDPP");
*chdir \$dirname;
*#\$dataref = [\$nsims,\\\%data,\\\%sweepeddata,\\\%last];
*my \$dataref = [\$nsims,\\\%data,\\\%sweepeddata,\\\%last];
*&Simulation::Tools::SynSim::PostProcessors::$subref(\$dataset,\$i,\$dataref,\$flagsref,1);
*chdir '..';
ENDPP
print MOD &strip(<<"ENDTAIL");
* return \$returnvalue;
*} #END of execute_${sim}_loop
ENDTAIL
$data{$sim}{TITLE}=$title;
} #END of loop over sims

close MOD;
print STDERR "...Done\n\n";
#return \@sims;

return \%data;
} #END of generate loop module

#-------------------------------------------------------------------------------
sub strip {
my $line=shift;
$line=~s/(^|\n)\*/$1/sg;
return $line;
}
#-------------------------------------------------------------------------------
#
# This subroutine takes a reference to %specific as generated by allow_multiple_sims($datafile)
# So  %multisimdata is actually %specific
# Then, it turns this into a hash of hashes:
# for every $sim, there's a hash with as key the parameter name and as value its value-list
# This is %data, which is returned to $dataref in  generate_loop_module()
# 
sub fill_data_hash_multi {
my $dataref=shift;
my %data=();
my %multisimdata=%$dataref;
foreach my $sim (keys %multisimdata) {

  foreach (@{$multisimdata{$sim}}){

  if(/^\s*_/) {
my @line=split(/\s*=\s*/,$_);

$line[1]=~s/\s*\,\s*/,/g;
$line[1]=~s/\s*\;\s*/;/g;
$data{$sim}{$line[0]}=$line[1];
} elsif (/:/) {
my @line=split(/\s*:\s*/,$_);
##strip leading _
#$line[0]=~s/^\s*_//;
#strip trailing spaces
$line[1]=~s/\s+$//;
$data{$sim}{$line[0]}=$line[1];

} #if
  } # foreach
}
return \%data;
} #END of fill_data_hash_multi

#-------------------------------------------------------------------------------
#
# this subroutine splits the datafile into a common part (@common) and a number
# of simtype-specific parts ( %specific{$simtype}); then, it pushes @common onto
# @{$specific{$simtype}} and returns \%specific
# So every key in %specific points to an array with all variables needed for that simtype
#
sub allow_multiple_sims {
my $datafile=shift;
my @sims=();
my $simpart=0;
my $simpatt='NOPATTERN';
my @common=();
my %specific=();
my $simtype='NOKEY';
my $skip=0;
open(DATA,"<$datafile")|| die "Can't open $datafile\n";

while(<DATA>) {

/^\s*\#/ && next;
/^\s*$/ && next;
chomp;
# allow include files for configuration variables
/INCL\s*:/ && do {
my $incl=$_;
$incl=~s/^.*\:\s*//;
$incl=~s/\s+$//;
my @incl=($incl=~/,/)?split(/\s*,\s*/,$incl):($incl);
foreach my $inclf (@incl) {
open(INCL,"<$inclf");
while(<INCL>){
/^\s*\#/ && next;
/^\s*$/ && next;
chomp;
# only configuration variables in include files!
/:/ && do {push @common,$_};
}
close INCL;
}
}; # END of allow INCL files

 s/(\#.*)//;
if(/SIMTYPE\s*:/) {
my $sims=$_;
(my $par,$simpatt)=split(/\s*:\s*/,$sims);
$simpatt=~s/\s*\,\s*/|/g;
$simpatt=~s/\s+//g;
@sims=split(/\|/,$simpatt);
$simpatt='('.$simpatt.')';
} elsif(/$simpatt/) {
$skip=0;
$simtype=$1;
$simpart=1
} elsif(/^\s*[a-zA-Z]/&&!/:/) {
$simpart=0;
$skip=1;
print STDERR "$_: Not present in simlist. Skipping data.\n";
}

if($simpart) {
push @{$specific{$simtype}},$_;
} elsif(!$skip) {
push @common,$_;
} else {
print STDERR "Skipped: $_\n" ;
}

} #while
close DATA;

foreach my $sim (@sims) {
push @{$specific{$sim}},@common;
}

return \%specific;
} #END of allow_multiple_sims

#===============================================================================

sub execute_loop {
my $datafilename=shift;
my $dataset=shift;

eval("
use Loops_$dataset;
");

my $simref=shift;
my @flags=@{shift(@_)};
my $nosims=$flags[2];

foreach my $sim (sort keys %{$simref}) {
# extension for template files
my $templ=${$simref}{$sim}->{TEMPL}||'.templ';
my $dev=${$simref}{$sim}->{DEVTYPE}||'';

my $dirname= "${sim}-$dataset";

  if(-e $dirname && -d $dirname && ($nosims==0)) {
print STDERR "\nRemoving old $dirname dir\n".`rm -Rf $dirname`;
}

  if (not -e "TEMPLATES/SIMTYPES/$sim$templ" ) {
print STDERR "No templates for simulation $sim. Skipped.\n";
next;
} else {

mkdir $dirname, 0755;
#WV1710: new organisation, allow both devices & simulations
#old:
#system("cp TEMPLATES/SIMTYPES/$sim.* $dirname");
#system("cp TEMPLATES/DEVTYPES/$sim.* $dirname");
#new:
if (-e "TEMPLATES/SIMTYPES/$sim$templ") {
system("cp TEMPLATES/SIMTYPES/$sim$templ $dirname");
} else {
die "There's no simulation template for $sim in TEMPLATES/SIMTYPES\n";
}
if($dev){
if (-e "TEMPLATES/DEVTYPES/$dev$templ") {
system("cp TEMPLATES/DEVTYPES/$dev$templ $dirname");
} else {
print STDERR "No device template for $dev in TEMPLATES/DEVTYPES.\n";
}
}
# any file with this pattern is copied to the rundir.
if (-d "SOURCES") {
system("cp SOURCES/$sim* $dirname");
} 
}
print STDERR "#" x 80,"\n";
print STDERR "#\n";
print STDERR "# Simulation type: $sim, device dir ".`pwd`."#\n";
print STDERR "#" x 80,"\n";

eval('&Loops_'.$dataset.'::execute_'.$sim.'_loop($dataset,\@flags);');

} #sims
return 1;
} #END of &execute_loop

################################################################################

# Create simulation directory etc.
sub setup {
  use File::Copy;
print "Simulation project name? [SynSimProject]:";
my $project=<STDIN>;
chomp $project;
if(not $project){$project='SynSimProject'}
my $HOME=$ENV{HOME};

print "Creating $project directory structure ...\n";
mkdir "$HOME/$project", 0755;
mkdir "$HOME/$project/SOURCES", 0755;
mkdir "$HOME/$project/TEMPLATES", 0755;
mkdir "$HOME/$project/TEMPLATES/DEVTYPES", 0755;
mkdir "$HOME/$project/TEMPLATES/SIMTYPES", 0755;
  if(-d "eg"){
    if(-e "eg/synsim"){
copy("eg/synsim","$HOME/$project/synsim");
}
    if(-e "eg/synsim.data"){
copy("eg/synsim.data","$HOME/$project/synsim.data");
}
  }
print "Creating local  SynSim directory $HOME/Simulation/Tools/SynSim ...\n";
  if(not -d  "$HOME/Simulation"){
mkdir "$HOME/Simulation", 0755;
}
  if(not -d  "$HOME/Simulation/Tools"){
mkdir "$HOME/Simulation/Tools", 0755;
}
  if(not -d  "$HOME/Simulation/Tools/SynSim"){
mkdir "$HOME/Simulation/Tools/SynSim", 0755;
}
  if(-d "SynSim") { 
if( -e "SynSim/PostProcessors.pm"){
copy("SynSim/PostProcessors.pm", "$HOME/Simulation/Tools/SynSim/PostProcessors.pm");
}
if( -e "SynSim/Dictionary.pm"){
copy("SynSim/Dictionary.pm", "$HOME/Simulation/Tools/SynSim/Dictionary.pm");
}
}
} # END of setup()

######################## User Documentation ##########################


## To format the following documentation into a more readable format,
## use one of these programs: perldoc; pod2man; pod2html; pod2text.
## For example, to nicely format this documentation for printing, you
## may use pod2man and groff to convert to postscript:
##   pod2man SynSim.pod | groff -man -Tps > SynSim.ps


=head1 NAME

SynSim - a simulation automation tool

=head1 REQUIREMENTS

=over

=item *

a unix-like system

=item *

perl 5

=item *

gnuplot for postprocessing (optional)

=back

=head1 SYNOPSIS

       use Simulation::Tools::SynSim;

       &synsim();

=head1 DESCRIPTION

SynSim is a generic template-driven simulation automation tool. It works with any simulator that accepts text input files and generates text output. It executes thousands of simulations with different input files automatically, and processes the results. Postprocessing facilities include basic statistical analysis and automatic generation of PostScript plots with Gnuplot. SynSim is entirely modular, making it easy to add your own analysis and postprocessing routines.

=head1 INSTALLATION

=over

=item 1.
Download the gzipped tar file F<SynSim-0.9.1.tar.gz>

=item 2.
Extract the archive:

	tar -xvf SynSim-0.9.1.tar.gz

=item 3.
Create the Makefile:

	cd SynSim-0.9.1
	perl Makefile.PL

=item 4.
Make SynSim:

	 make

=item 5.
Test SynSim:

	 make test

=item 6.
Install SynSim:

	 make install

=item 6.
Setup your local SynSim project:

	 make setup

=back

The archive structure is as follows:

	README    
	Makefile.PL	  
        SynSim.pm
	SynSim/
                Main.pm
        	PostProcLib.pm
                Analysis.pm
		Dictionary.pm
             	PostProcessors.pm

	eg/
		synsim	
		synsim.data
		ErrorFlags.data
		Histogram.data
		SOURCES/
			bufsim3.cc
			MersenneTwister.h
		TEMPLATES/		
			DEVTYPES/
			SIMTYPES/
				bufsim3.templ


=head1 CONFIGURATION

SynSim must be configured for use with your simulator. This is done by providing template and source files, creating (or modifying) datafiles and (optionally) customizing some modules for postprocessing the simulation results. All files must be put in a particilar directory structure:

=head2 Directory structure

You can use "make setup"  to create a SynSim directory structure. If you want to create it manually, this is the structure:

	YourProject/
			synsim	
			YourDataFile.data
			[SOURCES/]
			TEMPLATES/		
				 [DEVTYPES/]
				 SIMTYPES/
					YourSimTempl.templ

	[Simulation/Tools/SynSim/]
				[Dictionary.pm]
				[PostProcessors.pm]			

The synsim script contains the 2 lines from the L<SYNOPSIS>. 
The local Simulation/Tools/SynSim modules are only required if you want to customize the postprocessing (highly recommended). 
 
=head2 Source files

Copy all files which are needed "read-only" by your simulator (e.g. header files, library files) to F<SOURCES/>. This directory is optional.

=head2 Template files

Template files are files in which simulation variables will be substituted by their values to create the input file for your simulator. SynSim can create an input file by combining two different template files, generally called device templates and simulation templates. This is useful in case you want to run different types of simulations on different devices, e.g. DC analysis, transient simulations, small-signal and noise analysis  on 4 different types of operation amplifiers. In total, this requires 16 different input files, but only 8 different template files (4 for the simulation type, 4 for the device types).

=over

=item 1.

To create a template file, start from an existing input file for your simulator. Replace the values of the variables to be modified by SynSim by a SynSim variable name (e.g. 
var1 = 2.5 => var1 = _VAR1). 

=item 2.

Put the template files in F<TEMPLATES/SIMTYPES> and F<TEMPLATES/DEVTYPES>.


There must be at least one template file in F<SIMTYPES>; files in F<DEVTYPES> are optional.
SynSim will check both directories for files as defined in the datafile. If a matching file is found in F<DEVTYPES>, it will be prepended to the simulation template from F<SIMTYPES>. This is useful if the datafile defines multiple simulation types on a particular device (See L<DATAFILE DESCRIPTION> for more information).

=back

B<NOTE:>

SynSim creates a run directory ath the same level as the SOURCES and TEMPLATES directories. All commands (compilations etc.) are executed in that directory. As a consequence, paths to source files (e.g. header files) should be "C<../SOURCES/>I<sourcefilename>".


=head2 datafile

The datafile is the input file for synsim. It contains the list of simulation variables and their values to be substituted in the template files, as well as a number of configuration variables (See L<DATAFILE DESCRIPTION> for more information).

=head2 Postprocessing (optional)

The F<PostProcessing.pm> module contains routines to perform postprocessing on the simulation results. A number of generic routines are provided, as well as a library of functions to make it easier to develop your own postprocessing routines. See L<POSTPROCESSING> for a full description).

=head2 Dictionary (optional)

The F<Dictionary.pm> module contains descriptions of the parameters used in the simulation. These descriptions are used by the postprocessing routines to make the simulation results more readable. See L<DICTIONARY> for a full description).

=head1 DATAFILE DESCRIPTION

The datafile defines which simulations to run, with which parameter values to use, and how to run the simulation. By convention, it has the extension C<.data>.

=head2 Syntax

The datafile is a case-sensitive text file with following syntax:

=over

=item Comments and blanks

Comments are preceded by '#'. 
Comments, blanks and empty lines are ignored

=item Simulation variables 

Simulation variables ("parameters") are in UPPERCASE with a leading '_', and must be separated from their values with a '='.

=item Configuration variables 

Configuration variables ("keywords") are in UPPERCASE, and must be separated from their values with a ':'.

=item Lists of values

Lists of values have one or more items. Valid list separators are ',',';' and, for a 2-element list, '..'.

=item Section headers for multiple simulation types

These must be lines containing only the simulation type 

=back

=head2 Simulation variables 

The main purpose of the datafile is to provide a list of all variables and their values to be substituted in the template files. 
The lists of values for the variables can be used in two different ways: 

=over

=item Comma-separated list: combine values

A simulation will be performed for every possible combination of the values for all parameters. 

Example:

	_PAR1 = 1,2
	_PAR2 = 3,4,5

defines 6 simulations: (_PAR1,_PAR2)=(1,3),(1,4),(1,5),(2,3),(2,4),(2,5)

Simulation results for all values in ','-separated list are stored in a separate files.


=item Semicolon-separated list: pair values

If more than one ';'-separated list exists, they must have the same number of items. The values of all parameters at the same position in the list will be used.

Example:

	_PAR1 = 0;1;2
	_PAR2 = 3;4;5

defines 3 simulations: (_PAR1,_PAR2)=(0,3);(1,4);(2,5)

Values from ';'-separated lists are processed one after another while are values for all others parameters are kept constant. In other words, the ';'-separated list is the innermost of all nested loops.

Simulation results for all values in the ';'-separated list are stored in a common file. For this reason, ';'-separated lists are preferred as sweep variables (X-axis values), whereas ','-separated lists are more suited for parameters (sets of curves).

Example: consider simulation of packet loss vs number of buffers with 3 types of buffer and 2 different traffic distributions.

	_NBUFS = 4;8;16;32;64;128
	_BUFTYPE = 1,2,3
	_TRAFDIST = 1,2

This will produces 6 files, each file containing the simulation results for all values of _NBUFS. A plot of this simulation would show a set of 6 curves, with _NBUFS as X-axis variable.

=item Double dotted list

This is a shorthand for a ';'-separated list if the value increase in steps of 1. E.g. 0..7 is equivalent to 0;1;2;3;4;5;6;7.

=back

=head2 Configuration variables

A number of variables are provided to configure SynSim's behaviour:

=over

=item INCLUDE (optional)

If the value of INCLUDE is an exisiting filename, this datafile will be included on the spot.

=item COMMAND

The program that runs the input file, i.e. the simulator command (default: perl).

=item EXT

Extension of input file (default: .pl)

=item TEMPL

Extension of template files (default: .templ)

=item SIMTYPE

The type of simulation to perform. This can be a ','-separated list. SynSim will look in TEMPLATES/SIMTYPES for a file with TEMPL and SIMTYPE

=item DEVTYPE (optional)

The name of the device on which to perform the simulation. If defined, SynSim will look in TEMPLATES/DEVTYPES for a file with TEMPL and DEVTYPE, and prepend this file to the simulation template before parsing.

=item OUTPUT_FILTER_PATTERN

A Perl regular expression to filter the output of the simulation (default : .*).

=item ANALYSIS_TEMPLATE

Name of the routine to be used for the result analysis (postprocessing). This routine must be defined in PostProcessors.pm (default: SweepVar, a generic routine which assumes a sweep for one variable and uses all others as parameters).

=item SWEEPVAR (optional)

The name of the variable to be sweeped. Mandatory if the postprocessing routine is SweepVar. 

=item DATACOL (optional)

The column in the output file which contains simulation results (default: 2). Mandatory if using any of the generic postprocessing routines. 

=item TITLE (optional)

String describing the simulation, for use in the postprocessing.

=item YAXIS, LOGSCALE

Variables to allow more flexibility in the customization of the plots. YLABEL is the Y axis label. LOGSCALE is either X, Y or XY, and results in a logarithmic scale for the chosen axis.

=item XTICS, YTICS, XSTART, XSTOP, YSTART, YSTOP

Variables to allow more flexibility in the customization of the plots. NOT IMPLEMENTED YET!

=back


The next sections (L<DICTIONARY> and L<POSTPROCESSING>) are optional. For instructions on how to run SynSim, go to L<RUNNING SYNSIM>.



=head1 DICTIONARY

The F<Dictionary.pm> module contains descriptions of the parameters used in the simulation. These descriptions are used by the postprocessing routines to make the simulation results more readable. The dictionary is stored in an associative array called C<make_nice>. The description of the variable is stored in a field called 'title'; Descriptions of values are stored in fields indexed by the values.

Following example illustrates the syntax:

	# Translate the parameter names and values into something meaningful
	%Dictionary::make_nice=(
	
	_BUFTYPE => {
	title=>'Buffer type',
		     0=>'Adjustable',
		     1=>'Fixed-length',
		     2=>'Multi-exit',
		    },
	_YOURVAR1 => {
	title=>'Your description for variable 1',
	},
	
	_YOURVAR2 => {
	title=>'Your description for variable 2',
'val1' => 'First value of _YOURVAR2',
'val3' => 'Second value of _YOURVAR2',
	},

	);

=head1 POSTPROCESSING

Postprocessing of the simulation results is handled by routines in the C<PostProcessors.pm> module. This module uses the C<PostProcLib.pm> and C<Analysis.pm>.

=head2 PostProcessors

Routines to perform analysis on the simulation results in the PostProcessors module. In general you will have to create your own routines, but the version of C<PostProcessors.pm> in the distribution contains a number of more or less generic postprocessing routines:

=over

=item SweepVar

Creates a plot using C<SWEEPVAR> as X-axis and all other variables as paramters. This routine is completely generic.

=item ErrorFlags 

Calculates average and 95% confidence intervals and plots error flags. (Will be generic soon, more info then :-)

=item Histogram

Creates a histogram of the simulation results.  (Will be generic soon, more info then  :-)

=back

=head2 PostProcLib

In a lot of cases you will want to create your own postprocessing routines. To make this easier, a library of functions is at your disposal. This library resides in the C<PostProcLib.pm> module. 

Following functions are exported:

			   &prepare_plot	# does what it says. see example below
			   &gnuplot		# idem. Just pipes the first argument string to gnuplot. The option -persist can be added to keep the plot window after gnuplot exits.
			   &gnuplot_combined	# See example, most useful to create nice plots. Looks for all files matching ${simtempl}-${anatempl}-*.res, and creates a line in the gnuplot script based on a template you provide.	

Following variables are exported:

			   %simdata		# contains all simulation variables and their value lists
			   @results		# an array of all results for a sweep (i.e. a var with a ';'-sep. value list
			   $sweepvar		# SWEEPVAR
			   $sweepvals		# string containing all names and values of parameters for the sweep, joined with '-'
			   $datacol		# DATACOL
			   $count		# cfr. OUTPUT FILES section
			   $simtempl		# SIMTYPE
			   $anatempl		# ANALYSIS_TEMPLATE
			   $dirname		# name of run directory. cfr. OUTPUT FILES section
			   $last		# indicates end of a sweep
			   $verylast		# indicates end of all simulations
			   $sweepvartitle	# title for SWEEPVAR (from Dictionary.pm) 
			   $title		# TITLE 
			   $legend		# plot legend (uses Dictionary.pm)
			   $legendtitle		# plot legend title (uses Dictionary.pm)
                           $ylabel		# YLABEL	
                           $logscale		# LOGSCALE
			   $plot		# corresponds to -p flag
			   $interactive		# corresponds to -i flag

An example of how all this is used:

	sub YourRoutine {
	## Unless you want to dig really deep into the code, start all your routines like this:
	## Get all arguments, to whit: $datafilename,$count,$dataref,$flagsref,$returnvalue
	my @args=@_; 
	## But don't bother with these, following function does all the processing for you:
	&prepare_plot(@args);
	
	## this makes all above-listed variables available
	
	## Define your own variables.
	## As every variable can have a list of values, 
	## $simdata{'_YOURVAR1'} is an array reference.
	
	my $yourvar=${$simdata{'_YOURVAR1'}}[0];
	
	my @sweepvarvals=@{$simdata{$sweepvar}};
	
	## $verylast indicates the end of all simulations
	if($verylast==0) {
	
	## what to do for all simulations
	
	## example: parse SynSim .res file and put into final files for gnuplot
	
	open(HEAD,">${simtempl}-${anatempl}-${sweepvals}.res");
	open(IN,"<${simtempl}_C$count.res");
	while(<IN>) {
		/\#/ && !/Parameters|$sweepvar/ && do {
		## do something with $_
		print HEAD $_
		};
	}
	close IN;
	close HEAD;

	my $i=0;
	foreach my $sweepvarval ( @sweepvarvals ) {
		open(RES,">>${simtempl}-${anatempl}-${sweepvals}.res");
		print RES "$sweepvarval\t$results[$i]";
		close RES;
		$i++;
	}

	## $last indicates the end of a sweep
	if($last) {
	  ## $interactive corresponds to the -i flag
		  if($interactive) {
		    ## do something, typically plot intermediate results
		my $gnuplotscript=<<"ENDS";
		# your gnuplot script here
		ENDS
	
		&gnuplot($gnuplotscript);
	
		}		# if interactive
	  }			# if last
	} else {
	 ## On the very last run, collect the results into one nice plot
	
	## You must provide a template line for gnuplot. Next line is a good working example.
	## This line will be eval()'ed by the &gnuplot_combined() routine. 
	## This means the variables $filename and $legend are defined in the scope of this routine. 
	## Don't locally scoped put variables in there, use the substitution trick as below or some other way.
	
	#this is very critical. The quotes really matter!
	# as a rule, quotes inside gnuplot commands must be escaped
	
	my $plotlinetempl=q["\'$filename\' using (\$1*1):(\$_DATACOL) title \"$legend\" with lines"];
	$plotlinetempl=~s/_DATACOL/$datacol/; ##this is a trick, you might try to eval() the previous line or something. TIMTOWDI :-)
	
	my $firstplotline=<<"ENDH";
	# header for your gnuplot script here
	ENDH
	
	&gnuplot_combined($firstplotline,$plotlinetempl);
	}
	
	} #END of YourRoutine()


=head2 Statistical analysis

A module for basic statistical analysis is also available (C<Analysis.pm>). Currently, the module provides 2 routines: 

=over

=item calc_statistics()

To calculate average, standard deviation, min. and max. of a set of values.

Arguments:

	$file: name of the results file. The routine requires the data to be in whitespace-separated columns.  	
	$par: Determines if the data will be differentiated before processing ($par='DIFF') or not (any other value for $par). Differentiation is defined as subtracting the previous value in the array form the current value. A '0' is prepended to the array to avoid an undefined first point.
	$datacol: column to use for data
	$title: optional, a title for the histogram 
	$log: optional, log of values before calculating histogram or not ('LOG' or '')

Use:
	my $file="your_results_file.res";
	my $par='YOURPAR';
	my $datacol=2;
	my %stats=%{&calc_statistics($file,[$par, $datacol])};

	my $avg=$stats{$par}{AVG}; # average
	my $stdev=$stats{$par}{STDEV}; # standard deviation
	my $min=$stats{$par}{MIN}; # min. value in set
	my $max=$stats{$par}{MAX}; # max. value in set

=item build_histograms()

To build histograms. There are 3 extra arguments:

	$nbins: number of bins in the histogram
	$min: force the value of the smallest bin (optional)
	$max: force the value of the largest bin (optional)

use:
	my $par='DATA';
	my %hists=%{&build_histograms("your_results_file.res",[$par,$datacol],$title,$log,$nbins,$min,$max)};

NOTE: Because the extra arguments are last, the $title and $log arguments can not be omitted. If not needed, supply ''.

=back


=head1 RUNNING SYNSIM

The SynSim script must be executed in a subdirectory of the SynSim
directory which contains the TEMPLATES subdir and the datafile (like the Example directory in the distribution).

The command line is as follows:

	../synsim [-h -i -p -b -v -N -f datafile]

The C<synsim> script supports following command line options:

	none: defaults to -f synsim.data
	 -f [filename]: 'file input'. Expects a file containing info about simulation and device type. 
	 -p : plot. This enables generation of postscript plots via gnuplot. A postprocessing routine is required to generate the plots.
	 -i : interactive. Enables generation of a plot on the screen after every iteration. Assumes -p.  A postprocessing routine is required to generate the plots.
	 -v : 'verbose'. Sends simulator output to STDOUT, otherwise to [simulator].log file
	 -N : 'No simulations'. Perform only postprocessing.
	 -h, -? : short help message

=head1 OUTPUT FILES

SynSim creates a run directory C<{SIMTYPE}->I<[datafile without .data]>. It copies all necessary template files and source files to this directory; all output files are generated in this directory.

SynSim generates following files:

=over

=item *

Output files for all simulation runs. 

The names of these files are are C<{SIMTYPE}_C>I<[counter]_[simulation number]>C<.out>

I<counter> is increased with every new combination of variables in ','-separated lists 

I<simulation number> is the position of the value in the ';'-separated list. 

=item *

Combined output file for all values in a ';'-separated list. 

The names of these files are are C<{SIMTYPE}_C>I<[counter]>C<_.out> 

I<counter> is increased with every new combination of variables in ','-separated lists. 

Only the lines matching C</OUTPUT_FILTER_PATTERN/> (treated as a Perl regular expression) are put in this file.

=item *

Combined output file for all values in a ';'-separated list, with a header detailing all values for all variables. 

The names of these files are are C<{SIMTYPE}_C>I<[counter]>C<.res>, 

I<counter> is increased with every new combination of variables in ','-separated lists.  

Only the lines in the C<.out> files matching C</OUTPUT_FILTER_PATTERN/> (treated as a Perl regular expression) are put in this file.


=item *

Separate input files for every item in a ';'-separated list. 

The names of these files are are C<{SIMTYPE}_>I<[simulation number]>C<.{EXT}>

I<simulation number> is the position of the value in the list. 

These files are overwritten for every combination of variables in ','-separated lists.

=back

=head1 AUTHOR

Wim Vanderbauwhede <wim@motherearth.org>

=head1 COPYRIGHT

Copyright (c) 2002 Wim Vanderbauwhede. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

=head1 SEE ALSO

gnuplot L<http://www.ucc.ie/gnuplot/gnuplot.html>

=cut
