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.
A pop-up dialog will appear, in order to select the type of script to be created:
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 Experiment Script for scripts that will be used in a four-step model experiment diagram.
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 http://wiki.python.org/moin/PythonEditors. 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.
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.
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.
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.
For example, the script to print the ID of the selected object is:
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.
The scripting environment in Aimsun Next is initialized by executing the script initial.py located in the folder "Program Files/Aimsun/Aimsun Next X.X/shared/scripts/model". Its content is shown below
import sys from PyANGBasic import * from PyANGKernel import * from PyANGGui import * def GKAlreadyInPath( path, str ): res = False for i in path: if i == str: res = True return res class GKPrintHook: def __init__( self ): sys.stdout = self #override write of stdout def write(self,text): model = GKSystem.getSystem().getActiveModel() if model != None: model.getLog().addInfo( text ) else: GKSystem.getSystem().getLog().addInfo( text ) #pass all other methods to __stdout__ so that we don't have to override them def __getattr__(self, name): return self.origOut.__getattr__(name) phOut = GKPrintHook() model = GKSystem.getSystem().getActiveModel() target = GKSystem.getSystem().getActiveTarget() selection = GKSystem.getSystem().getActiveSelection()
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.
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 python_script.py
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 return -1 # Get the GUI gui = GKGUISystem.getGUISystem().getActiveGui() # Load a network if gui.loadNetwork(argv): model=gui.getActiveModel() # Here you can do things with the model # Save and close the network gui.save() gui.closeDocument(model) # Quit the GUI gui.forceQuit() else: gui.showMessage( GGui.eCritical, "Open error", "Cannot load the network" ) main(sys.argv)
Then, to call the script as Aimsun Next is started, use the -script command line option.
"Aimsun Next.exe" –script python_script.py my_network.ang
Note that argv contains all the command line arguments,i.e.
- argv will be "Aimsun Next.exe",
- argv will be -script,
- argv will be the file containing the script
- argv will be the network.
Once the network is loaded, the model can be accessed using the GGui::getActiveModel method as follows:
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 python_script.py
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 all editions.
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)) return -1 # Start a Console console = ANGConsole() # Load a network if console.open( argv ): model = console.getModel() print "load network" matrix = model.getCatalog().find( int(argv) ) if matrix != None: print "matrix accessed" console.close() else: console.getLog().addError( "Cannot load the network" ) print "cannot load network" if __name__ == "__main__": sys.exit(main(sys.argv))
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.
aconsole.exe –script python_script.py my_network.ang 100
- argv will be python_script.py,
- argv will be my_network.ang
- argv 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 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__": sys.exit(main(sys.argv))
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.