Skip to content

Editing and Running a Script

Editing a Script

Scripts can be written within Aimsun Next, using an editor that provides syntax highlighting. Create a new script using the Project/New menu or the New option in the Project / Scripts folder.

Create a new script

A pop-up dialog will appear, in order to select the type of script to be created:

New script

Choose Empty Script for new scripts, Pre-Run or Post-Run Scripts for scripts that will be called automatically from experiments when executing, and Four-Step Model Experiment Script for scripts that will be used in a four-step model experiment diagram.

New script

Pre-Run and Post-Run Scripts predefined structure

There is a mandatory requirement that both these scripts must contain the following function to check any prerequisite the script might have. The rest of the script coding must be contained in this function. The filter function will return True if the experiment can be run or False if something is missing or invalid (the run will then be canceled). The signature of the function is:

def filter( experiment ):

    return True

External Editing

If preferred, it is possible to edit scripts with more familiar or sophisticated software, particularly if scripts will be stored outside the main ANG file. A list of external editors particularly suitable for Python can be found at As scripts are text files, they can be edited with the most basic text editors, such as Wordpad on Microsoft Windows, although in this case, the helpful highlighting functionality found in better editors won’t be available.

To move code between the python editor in Aimsun Next (which will save scripts within the ANG file), and the chosen external editor, simply use the normal select, copy [Ctrl-C] and paste [Ctrl-V] operations.

Imported Scripts

Use Import setting to add one or more existing scripts to be executed before the script. They will be executed in order using their identifiers.

Running a Script

A Python Script can be run either from its editor or from its context menu in the Project /Script Folder. Use the Execute button or Ctrl+E shortcut to run inside the editor.

The script can also be saved into an external file by checking the External File checkbox and typing the path. To save the modifications done while editing the script code into the external file use the Save button.

In the User Interface tab of the script editor, a script can also be assigned to an object type. The script will then appear in the context menu of any object of that type, under the item Scripts. The selected object can be accessed within the script using the variable target.

Use the Add Script to a Menu option to assign a script to an object type.

Assigning a script to Sections

For example, the script to print the ID of the selected object is:

print target.getId()

Before using the variable target, it is good practice to test that it exists:

if target != None:
    print target.getId()

If the check is passed, it means that the script is launched from the context menu of an object; if target is None, it means there is no specific object associated with this run of the script.

When running a script:

  • __name__ is set to __main__ for the executed script (this is the main script)
  • __name__ is set to the name of the script when running an imported script before the main script
  • __file__ is set to the external file path when the script is in a file

Execution Order

When running a script, the execution order is:

  1. The initial script (see Initialization bellow)
  2. Any imported script
  3. The script code

Search Paths for Modules

By default Aimsun Next will use the following paths to search for modules when doing an import call:

  1. When running a script from an external file, its folder
  2. The folder than contains the ANG file
  3. Paths defined in the System Preferences for Python using the Additional Python Path entry. Multiple paths separated by ; are allowed.
  4. Aimsun Next Plugins folder

If you need to add additional modules, for example pandas, do the following:

  1. Install a Python version compatible with Aimsun Next embedded version
  2. Use pip to install the new module
  3. Add the site-packages folder where the module has been installed to Aimsun Next using the entry in System Preferences


The scripting environment in Aimsun Next is initialized by executing the script located in the folder Program Files/Aimsun/Aimsun Next X.X/shared/scripts/model or equivalent.

This script imports the following Python modules, that contain the fundamental Aimsun classes required for model editing:

  • PyANGBasic: Qt classes.
  • PyANGKernel: Aimsun Kernel classes.
  • PyANGGui: Aimsun GUI classes.

In order to use the capabilities offered by the plug-ins, the related modules must be imported. For example, to calculate a static traversal matrix within a script, the PyMacroToolPlugin module must be imported

from PyMacroToolPlugin import *

The Table in the Architecture Section lists the modules to import in order to have access to a class.

The initialization script then redirects the standard output to Aimsun Log window and, finally, it pre-initializes the following variables:

  • model: contains the current network model.
  • target: contains the object from which the script is executed, if the script is linked to an object type.
  • selection: contains the objects currently selected.

Fast Access Script

To allow the faster execution of a specific Python script, in each Aimsun Next model, you can now set one of the available scripts in the Scripts folder as "Fast Access" script. By selecting one or various objects, the "Fast Access" script can be executed using the keyboard shortcut [Ctrl + J].

Note that only one script can be set as "Fast Access" script. To set a script as "Fast Access" script, right-click on it and select the option Set As Fast Access from the Context Menu. Once done, its icon will be colored in blue.

Setting a script as 'Fast Access'

The "Fast Access" scripts do not work with the target object, but only using a selection of objects. Since these objects will not be filtered by type, to avoid possible issues with different types of objects, you must use the following filter structure:

for object in selection:
    if object.isA("GKSection"):

To execute the "Fast Access" script from the Context Menu for that selection of objects (right-click on any object from the selection), select the specific object type in Settings > Add Script to a Menu.

Setting a script as 'Fast Access'

Setting a script as 'Fast Access'

Startup Scripts

Aimsun Next GUI

Aimsun Next provides the option of running a script held in an external file when Aimsun Next is started using the command line with the –script option. The syntax is:

"Aimsun Next.exe" –script

Aimsun Next will start as usual but, instead of waiting for the user to open or create a network, it will execute the script. At that moment, therefore, only the GUI is available.

Usually the first thing that the script will do is to load a network. The steps are to get the GUI object and execute the loadNetwork method:

gui = GKGUISystem.getGUISystem().getActiveGui()
# Load a network
gui.loadNetwork( "vitex.ang" )

The network can contain the full path (i.e. c:/my nets/vitex.ang). Note that the folder separator uses the slash (/) and not the backslash (\). If no path is specified, the current folder will be used.

It is also possible to read the path of the network to be loaded from the command line arguments sys.argv.

import sys

from PyANGBasic import *
from PyANGKernel import *
from PyANGGui import *

def main(argv):
    if len(argv) < 4:
        print "Usage: "Aimsun Next.exe" -script %s ANG_FILE " % argv[2]
        return -1
    # Get the GUI
    gui = GKGUISystem.getGUISystem().getActiveGui()
    # Load a network
    if gui.loadNetwork(argv[3]):
        # Here you can do things with the model
        # Save and close the network
        # Quit the GUI
        gui.showMessage( GGui.eCritical, "Open error", "Cannot load the network" )


Then, to call the script as Aimsun Next is started, use the -script command line option.

"Aimsun Next.exe" –script my_network.ang

Note that argv contains all the command line arguments,i.e.

  • argv[0] will be "Aimsun Next.exe",
  • argv[1] will be -script,
  • argv[2] will be the file containing the script
  • argv[3] will be the network.

Once the network is loaded, the model can be accessed using the GGui::getActiveModel method as follows:

model =gui.getActiveModel()

Aimsun Next Console

It is possible to run a script held in an external file to control the Aimsun Next Console application, a version of Aimsun Next without the graphical user interface and thus particularly suitable to quickly simulate a lot of replications for an already calibrated model. The syntax is:

aconsole.exe –script

The console neither opens a graphical window nor provides for any user interaction with the application, it just executes the supplied script and then quits. The main advantage is speed as any graphical code in Aimsun Next is not executed (animation during the simulation, creation of the main window, creation of an initial view…).

The Aimsun Next Console is available in Aimsun Next Pro, Advanced, or Expert Editions annual subscriptions.

To allow interaction the console adds a new class called ANGConsole. This class offers methods to load a network and get the GKModel created, to save the network and to close it.

The following example loads a network, accesses a matrix in it, then closes the network.

import sys

from PyANGBasic import *
from PyANGKernel import *
from PyANGConsole import *

def main( argv ):
    if len( argv ) < 3:
        print str("Usage: aconsole -script %s ANG_FILE MATRIX_ID"%(argv[0]))
        return -1
    # Start a Console
    console = ANGConsole()
    # Load a network
    if argv[1] ):
        model = console.getModel()  
        print "load network"
        matrix = model.getCatalog().find( int(argv[2]) )
        if matrix != None:
            print "matrix accessed"
        console.getLog().addError( "Cannot load the network" )
        print "cannot load network"

if __name__ == "__main__":

This example uses the variable argv to access the network name to be loaded. This variable, which is automatically set by the system, holds the parameters used when invoking the script from the command line. When using aconsole, the first argument (indexed from zero) is the name of the script and then the rest of the arguments are numbered from 1 to N.

For example:

aconsole.exe –script my_network.ang 100

  • argv[0] will be,
  • argv[1] will be my_network.ang
  • argv[2] will be 100.

The script checks all the required arguments are provided before continuing; otherwise it exits giving the information on the correct usage

if len( argv ) < 3:
    print "Usage: aimsun -script %s ANG_FILE MATRIX_ID" % argv[0]
    return -1

If everything is good, the script uses the Console to load the network. Once the network is loaded, the model is acquired using the ANGConsole::getModel() method.

The main body of the script is enclosed into a function, main, called by these lines of code

if __name__ == "__main__":

This means that if the script is executed, it’s function main is automatically executed, while if it is imported into another script


it does nothing unless it’s function main is called.