How to initialize TCL program in NS2?

By Admin on

To start a new simulator

  1. set ns [new Simulator]

From the above command we get that a variable ns is being initialized by using the set command. Here the code [new Simulator] is a instantiation of the class Simulator which uses the reserved word 'new'. So we can call all the methods present inside the class simulatorby using the variable ns.

Creating the output files

1    #To create the trace files we write


3     set tracefile1 [open out.tr w]

4     $ns trace-all $tracefile1


6    #To create the nam files we write


8     set namfile1 [open out.nam w]

9     $ns namtrace-all $namfile

In the above we create a output trace file out.tr and a nam visualization file out.nam. But in the Tcl script they are not called by their names declared,while they are called by the pointers initialized for them such as tracefile1 and namfile1 respectively.The line which starts with '#' are commented.The next line opens the file 'out.tr' which is used for writing is declared 'w'.The next line uses a simulator method trace-all by which we will trace all the events in a particular format.

The terminate the program 

01    # Defining the 'finish' procedure'


03    proc finish {} {

04         global ns tracefile1 namfile1

05         $ns flush-trace

06         close $tracefile

07         close $namfile

08         exec nam out.nam &

09         exit 0

10        }

In the above the word 'proc' is used to declare a procedure called 'finish'.The word 'global' is used to tell what variables are being used outside the procedure.

'flush-trace' is a simulator method that dumps the traces on the respective files.the command 'close' is used to close the trace files and the command 'exec' is used to execute the nam visualization.The command 'exit' closes the application and returns 0 as zero(0) is default for clean exit.

To implement the program

1    #end the program

2    $ns at 125.0 "finish"

To finish the simulation process

1    #start the simulation process

2    $ns run

SPIRO Google Plus