pongsim
index
u:\f\project - pongsim\pongsim850\pongsim.py

PONGsim (Python Overlay Network Graphical Simulator)
Main module of the PONGsim framework
 
Version: 8.50
 
Nicklas Beijar, nbeijar@netlab.tkk.fi
Networking Laboratory, Helsinki University of Technology
 
######################################################################
 
PONGsim (Python Overlay Network Graphical Simulator)
 
Copyright (c) 2005-2010 Nicklas Beijar
 
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
 
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
 
######################################################################
 
To do:
- PyDoc compatible comments

 
Modules
       
FixTk
bisect
math
os
pongsim_delaymodel
random
string
sys
thread
time
_tkinter
traceback

 
Classes
       
Application
ButtonField
Counter
EventQueue
Log
Node
OutputFile
Scenario
ScenarioManager
Scheduler
Simulation
Simulator
Snapshot
StatisticsCounter
StatusField
World

 
class Application
    A framework of a simulated application.
 
This class provides the framework for overlay protocols and applications. These should
be implemented as subclasses of the Application class.
 
  Methods defined here:
__init__(self, node)
Initiate the application.
 
The original function MUST be called from an overriding function. A better approach
is to override the init() function.
draw(self, canvas, x, y)
Draw the graphical representation of this application. 
 
Implement your application by overriding this function.
getdetailedinfo(self)
Return the the node's description that is written in a separate window when the node is examined.
 
Implement your application by overriding this function. Call the overrided function to include the 
default info.
getdisplayinfo(self)
Return the text to be written beside the node.
 
Implement your application by overriding this function. Call the overrided function to include the 
default info.
init(self)
Initiate the application.
 
Implement your application by overriding this function.
receive(self, message)
Handle a received message.
 
Implement your application by overriding this function.
send(self, message, destination=None)
Send the given message to the given destination.

 
class ButtonField
    User-extendable set of buttons to control the simulation.
 
  Methods defined here:
__init__(self, frame)
Initialise the ButtonField and attach it to the given frame.
add(self, name, callback)
Add a button with a given name and a given callback function that is performed when the button is pressed.
redraw(self)

 
class Counter
    Lightweitht statistics utility for counting events of different type.
 
  Methods defined here:
__init__(self, active=True, eventfile=None)
__str__(self)
Return a string representation of this Counter.
activate(self)
Activate the counter.
add(self, name, value=1)
Increase the named counter with the given value (default 1).
add_override(self, name, value=1)
Increase the named counter with the given value (default 1) even if result collection has not started.
close(self)
Close this Counter and its related file.
counterlist(self)
Return the list of names of the counters.
deactivate(self)
Deactivate the counter.
delete(self, name)
Delete the named counter.
sum(self, name)
Return the value of the named counter, or None if it is not existing.

 
class EventQueue
    Queue for simulated events.
 
  Methods defined here:
__init__(self)
Initialize the EventQueue
dequeue(self)
Return the following event from the queue and remove it from the queue.
enqueue(self, eventtime, function, parameters, repeat)
Enqueue a given function at the location determined by the given time.
length(self)
Return the length of the queue.

 
class Log
    Log for storing and displaying errors and other messages.
 
  Methods defined here:
__init__(self, scheduler, logfile=None, mode='a')
Initialize the log and open the logfile (optional) for writing in the given mode (a=append, w=write).
close(self)
Close the log and its related file.
error(self, msg)
Log an error message.
simerror(self, msg)
Log an error message related to the simulation.
simstatus(self, msg)
Log a status message related to the simulation.
simwarning(self, msg)
Log a warning message related to the simulation.
status(self, msg)
Log a status message.
warning(self, msg)
Log a warning message.

 
class Node
    Class representing a simulated node.
 
An application can be attached to the node. A node must belong to a World.
 
  Methods defined here:
__init__(self, world, address=None, noderadius=5, color='#777', outline='#000', x=None, y=None)
Initialize this node.
 
Arguments:
world - The World to which the node belongs.
address - The address of the node. If None is specified, an automatically generated address is assigned. Default None. 
noderadius - The radius of the drawn node. Default 5.
color - The fill color of the drawn node. Default "#777".
outline - The outline color of the drawn node. Default "#000".
x - The x-coordinate of the drawn node. If None is specified, the coordinate is random. Default None.
y - The yx-coordinate of the drawn node. If None is specified, the coordinate is random. Default None.
__repr__(self)
Return the identifier of the node as the representation of this node.
__str__(self)
Return the address as the string representation of this node.
count(self, name, value=1)
Increase the named node-specific counter with the given value (default 1).
 
For compatibility.
count_override(self, name, value=1)
Increase the named node-specific counter with the given value (default 1) even if result collection has not started.
 
For compatibility.
draw(self, canvas)
Draw this node on the given canvas.
getaddress(self)
Return the address of this node.
getdetailedinfo(self)
Return the the node's description that is written in a separate window when the node is examined.
 
Implement your application by overriding this function. Call the overrided function to include the 
default info.
getdisplayinfo(self)
Return the text to be written beside the node.
 
Implement your application by overriding this function. Call the overrided function to include the 
default info.
getlastmessages(self)
getnoderadius(self)
Return the radius of this node.
getx(self)
Return the x-coordinate of this node.
gety(self)
Return the y-coordinate of this node.
inworld(self)
Returns True if this node is in the world, i.e. if the node exists.
receive(self, message)
Handles reception of the given message. Scheduled. 
 
Forwards the received message to the attached Application.
remove(self)
Remove this node.
send(self, message, destination, delay=None, internaldelay=1.0000000000000001e-05)
Sends the given message to the given destination with the given delay (default 20ms).
 
If the message is sent to the node itself, the internal delay (default 1ms) is applied instead of the transmission delay.
setapplication(self, application)
Attach the given Application to this node.
 
NOTE: This is called automatically by the Application as part of its initialization.

Data and other attributes defined here:
nextaddress = 1

 
class OutputFile
     Methods defined here:
__init__(self, filename)
exists(self)
lock(self)
locked(self)
release(self)
write(self, s)

 
class Scenario
    Store the parameters of a simulated scenario.
 
  Methods defined here:
__init__(self, name, log=None)
Initialize a scenario.
__str__(self)
Return a string representation of this scenario.
copy(self)
Return a new identical copy of the current scenario.
findmultiline(self)
Return the first line with several values in the current scenario.
 
Returns the (parameter, valuerange) of the first line with multiple values in this scenario or (None, None) if not found.
Such a line is in the format "[value1 value2 value3]" defining several values for different simulator runs.
get(self, param, default=None)
Return the value of a given scenario parameter.
getall(self)
Return the dictionary of all parameter values.
getfilename(self)
Return the file name by parsing the file parameter and inserting values of specified parameters.
getname(self)
Return the name of the scenario.
set(self, param, value)
Set the value of a given scenario parameter.
set_typechk(self, param, value)
Set the value of a given scenario parameter by converting a string to a suitable type.

 
class ScenarioManager
    Load and store the scenarios, and manage the queue of scenarios to run.
 
  Methods defined here:
__init__(self, log)
Initiate the ScenarioManager.
count(self)
Return the number of scenarios.
enqueue(self, scenarioname, runnumber)
Put a given scenario on the queue and mark it with the given runnumber.
getXX(self, param, default=None)
Return the value of a given parameter of the currently active scenario.
getactivescenario(self)
Return the currently active scenario.
getrunnumberXX(self)
Return the number of the currently active run.
getscenarios(self)
Return the names of all scenarios.
load(self, path, filename)
Load a scenario in the given file in the given path.
loadall(self, path)
Load all scenarios in the given path.
makemultiscenarios(self, scenario)
Generate several scenarios from the given scenario, if there are lines specifying several values.
pop(self)
Return the first enqueued scenario and remove it from the queue.
resetqueue(self)
Empty the queue.

 
class Scheduler
    Scheduler for storing simulated events and for managing simulated time.
 
  Methods defined here:
__init__(self, log=None, until=None)
Initialize the scheduler.
after(self, eventtime, function, parameters=None)
Schedule a given event after the given time.
at(self, eventtime, function, parameters=None)
Schedule a given event at a given time.
every(self, eventtime, function, parameters=None)
Schedule a given event to be run repeated at a given interval.
queuelength(self)
Return the current number of pending events.
reset(self)
Reset the scheduler for a new simulation.
run(self)
Run all scheduled events.
setlog(self, log)
Sets the Log to which warnings are written.
step(self)
Run a single scheduled event.
 
Returns True if the last event was run, otherwise returns False.
time(self)
Return the current simulated time.

 
class Simulation
     Methods defined here:
__init__(self)
Initialize the simulation
 
This function is called when the simulation is being initialized. 
Override this function to implement your simulator.
abort(self)
close(self)
Close the simulation.
 
This function is called when the simulation has been finished or stopped. It is a suitable place
to collect results from the simulation. 
Override this function to implement your simulator.
eachevent(self)
Perform actions after each event.
 
A common use of this function is to define when to stop (e.g. based on time).
Override this function to implement your simulator.
end(self)
init(self)
Initialize a simulation run.
 
This function is called when the simulation run is being initialized. 
Override this function to implement your simulator.
makeworld(self)
Return a World for the simulation.
 
Called before init(). This function CAN be overrided to define other types of Worlds
messagereport(self, simtime, sent, node1, node2, message)
Analyses a sent of received message.
output(self, s)
pause(self)
postprocess(self)
Perform postprocessing and analyzing data.
 
This function is called when the user clicks the postprocess button. It is a suitable place
to process the results from the simulation. 
Override this function to implement your simulator.

 
class Simulator
     Methods defined here:
__init__(self, simulation, logfilename, scenariodir=r'.\')
Initialize the Simulation.
 
Arguments:
scheduler - An instance of the Scheduler class.
master - The Tk root window.
scenariomanager - An instance of the ScenarioManager class.
button_postprocess(self)
Handle pressing of the postprocess button.
button_selectscenario(self, event)
Handle selecting scenario in the scenario listbox.
button_start(self)
Handle pressing of the start/pause/continue button.
button_step(self)
Handle pressing of the step button.
button_stop(self)
Handle pressing of the stop button.
clickleft(self, event)
Handle clicking the left mouse button in the world view.
clickright(self, event)
Handle clicking the right mouse button in the world view.
close(self)
Closes the simulator.
closeexceptionwin(self)
Close the error window.
closeinfowin(self, event=None)
Handle pressing the close window button of the info window.
draw(self, dummy=None)
Draw the World, the selected node, the status and the detail window.
enqueuescenarios(self)
Enqueue the scenarios selected in the listbox.
exception(self, where)
Show the stack dump on a program exception.
 
In interactive mode, the dump is shown in a window, otherwise as text. 
Argument where specifies a text describing where the exception happened.
The simulator is paused.
exit(self)
Handle pressing the exit button.
geteventspersecond(self)
Return the current number of simulated events per second.
getoutfile(self)
Return the name of the current output file.
getscenario(self)
Return the name (including run number) of the running scenario.
getsimulatedtime(self)
Return the current simulated time.
gettimescale(self)
Return the current number of simulated events per second.
infowinclosebutton(self, event=None)
initscreen(self)
Create the contents of the window and start periodical redrawing.
makestatusfield(self, frame)
pause_call(self)
redraw(self)
Redraw the screen and reshedule this function.
reset(self)
Reset the simulator and initialize a new scenario.
run(self)
Run the simulator.
runbatch(self, runtimes, scenarios)
Run the given scenarios in a batch mode without GUI.
runbatch_old(self, runtimes, scenarios)
Run the given scenarios in a batch mode without GUI.
runinteractive(self)
Run in an interactive mode with a GUI.
runsim(self, dummy)
Run the simulator.
 
Should be run in a separate thread. Controlled externally through the following variables:
self.stoprequest - Set True to stop the current simulation.
self.pauserequest - Set True to pause the current simulation and False to continue after pausing.
self.delay - Specify the delay to wait after each simulated event.
setdelay(self, event)
Handle moving the delay slider.
setredrawinterval(self, event)
Handle moving the redraw interval slider.
stop_call(self)

Data and other attributes defined here:
STATE_IDLE = 1
STATE_PAUSE = 3
STATE_RUNNING = 2

 
class Snapshot
    Statistics utility for making periodical snapshots of the current simulated state.
 
  Methods defined here:
__init__(self, scheduler, interval, callback, filename)
Initialize the Snapshot.
 
Arguments:
scheduler - Sheduler for scheduling the snapshot event.
interval - Interval in simulated sime for performing the snapshot.
callback - Callback function that is called for obtaining the snapshot value.
filename - File to which the snapshot is written.
 
The callback function is a function without arguments that returns any type of value.
close(self)
Closes the Snapshot and its related file.
event(self, dummy)
Handles a snapshot event (internal function).

 
class StatisticsCounter
    More heavy statistics utility for counting events of different type with analysis of the values.
 
Calculates sum, max, min, average and number of entries. Compatible with Counter.
 
  Methods defined here:
__init__(self, active=True, eventfile=None)
__str__(self)
Return a string representation of this Counter.
activate(self)
Activate the counter.
add(self, name, value=1)
Increase the named counter with the given value (default 1).
add_override(self, name, value=1)
Increase the named counter with the given value (default 1) even if result collection has not started.
average(self, name)
Return the value of the named counter, or None if it is not existing.
close(self)
Close this Counter and its related file.
counterlist(self)
Return the list of names of the counters.
deactivate(self)
Deactivate the counter.
delete(self, name)
Delete the named counter.
entrycount(self, name)
Return the value of the named counter, or None if it is not existing.
max(self, name)
Return the value of the named counter, or None if it is not existing.
min(self, name)
Return the value of the named counter, or None if it is not existing.
sum(self, name)
Return the value of the named counter, or None if it is not existing.

 
class StatusField
    User-extendable display of various status information about the simulation.
 
  Methods defined here:
__init__(self, frame)
Initialise the StatusField and attach it to the given frame.
__str__(self)
add(self, name, shortname, callback)
Add a field with a given name and a given callback function that returns the value to display.
draw(self)
Draw the StatusField.

 
class World
    Class representing the network.
 
Every Node belongs to a World. The simulator simulates a World
The concept of World is a bit outdated in the current version of the simulator, but is included
for compatibility. 
The missleading name (World instead of Network) is for backward compatibility.
 
  Methods defined here:
__init__(self, simulation, xsize=1000, ysize=800)
Initiate the World
 
The xsize and ysize arguments specify the graphical size of the world.
addnode(self, node)
Add a Node to the World.
 
NOTE: This function is called by the Node automatically.
clear(self)
Remove all nodes from the world.
closest(self, x, y)
Return the Node that is closest to the given x- and y-coordinates.
delete(self, node)
draw(self, canvas)
Draw the world on the given canvas.
getnodes(self)
Return a list of all nodes in the world.
nodecount(self)
Return the number of nodes in the world.
randomcoordinate(self)
Return random (x, y) coordinates within the graphical size of the world.
randomnode(self)
Returns a random Node.

 
Data
        ACTIVE = 'active'
ALL = 'all'
ANCHOR = 'anchor'
ARC = 'arc'
BASELINE = 'baseline'
BEVEL = 'bevel'
BOTH = 'both'
BOTTOM = 'bottom'
BROWSE = 'browse'
BUTT = 'butt'
CASCADE = 'cascade'
CENTER = 'center'
CHAR = 'char'
CHECKBUTTON = 'checkbutton'
CHORD = 'chord'
COMMAND = 'command'
CURRENT = 'current'
DEFAULTINTERNALDELAY = 1.0000000000000001e-05
DEFAULTTRANSMISSIONDELAY = 0.02
DISABLED = 'disabled'
DOTBOX = 'dotbox'
E = 'e'
END = 'end'
EW = 'ew'
EXCEPTION = 8
EXTENDED = 'extended'
FALSE = 0
FIRST = 'first'
FLAT = 'flat'
GROOVE = 'groove'
HIDDEN = 'hidden'
HORIZONTAL = 'horizontal'
INSERT = 'insert'
INSIDE = 'inside'
LAST = 'last'
LEFT = 'left'
MITER = 'miter'
MOVETO = 'moveto'
MULTIPLE = 'multiple'
N = 'n'
NE = 'ne'
NO = 0
NONE = 'none'
NORMAL = 'normal'
NS = 'ns'
NSEW = 'nsew'
NUMERIC = 'numeric'
NW = 'nw'
OFF = 0
ON = 1
OUTSIDE = 'outside'
PAGES = 'pages'
PIESLICE = 'pieslice'
PROJECTING = 'projecting'
RADIOBUTTON = 'radiobutton'
RAISED = 'raised'
READABLE = 2
RIDGE = 'ridge'
RIGHT = 'right'
ROUND = 'round'
S = 's'
SCROLL = 'scroll'
SE = 'se'
SEL = 'sel'
SEL_FIRST = 'sel.first'
SEL_LAST = 'sel.last'
SEPARATOR = 'separator'
SINGLE = 'single'
SOLID = 'solid'
SUNKEN = 'sunken'
SW = 'sw'
StringTypes = (<type 'str'>, <type 'unicode'>)
TOP = 'top'
TRUE = 1
TclVersion = 8.5
TkVersion = 8.5
UNDERLINE = 'underline'
UNITS = 'units'
VERTICAL = 'vertical'
W = 'w'
WORD = 'word'
WORLDSIZEX = 1000
WORLDSIZEY = 800
WRITABLE = 4
X = 'x'
Y = 'y'
YES = 1
wantobjects = 1