Skip to content

Aimsun Next Retrieve APA information

The Aimsun Next kernel plugin offers classes to iterate over all paths stored in an Path Assignment file (.apa). The idea is to create a class that derives from the class ForestCalculator and implements the doPath function. It's possible to filter the paths before iterating through them. This filter can be done by using the class AnalysisFilter and setting the corresponding filters. For example you can filter paths going through a set of sections or paths entering through a set of entrance sections or only paths related to a specified time interval.

The doPath function receives all the paths for a given pathKey: - mInterval -> time interval index - mVehicleIndex -> vehicle type index - mOriginIndex -> origin centroid index - mOriginCon -> origin connection index - mDestinationIndex -> destination centroid index - mDestinationCon -> destination connection index

And the path info inside the parameter NSPTreeData. This class holds the percentage of demand assigned to the path as well as the path info and other paths stats like the vehicles assigned, and function components.

Once the derived class from the ForestCalculator is implemented this is the code to iterate through all paths:

#Filter
customFilter=AnalysisFilter()
#PathReader
#baseForest is the apa file
pr=PathReader(baseForest, model, repIdName)
pr.init()
pr.calculate(customFilter)
pr.finishPaths()

Example: Retrieve path assignment information

import os.path

class PathReader(ForestCalculator):
    def __init__(self, forest, model, name):
        self.forest = forest
        self.model = model
        self.name = name
        self.geo = forest.getGeometry()
        self.nbLines = 1;
        super(ForestCalculator, self).__init__(forest, model, ForestCalculator.eOnlyAvailablePaths)

    def init(self):
        info= QFileInfo(self.model.getDocumentFileName())
        filename = os.path.join(info.absolutePath(),self.name+'_paths.csv')
        self.file = open(filename, 'w')
        if self.file!=None:
            self.file.write("interval;vehicle;origin;destination;type;path;probability;veh generated;veh arrived;cost;distance;travel time;speed;function component\n")
            self.file.flush()
        else:
            print("Could not open file %s"%filename)

    def doPath(self,pathKey, treeData, connections,aux):
        if self.file!=None:
            #print('entro')
            originId = self.geo.getOriginCentroid(pathKey.mOriginIndex)
            destId = self.geo.getDestinationCentroid(pathKey.mDestinationIndex)
            self.file.write("%d;%d;%d;%d;"%(pathKey.mInterval, pathKey.mVehicleIndex, originId, destId))
            typepath = treeData.pathType()
            typelist = ['None', 'RC', 'PAR', 'ODR', 'TRJ','P2P']
            self.file.write("%s;"%typelist[typepath])
            p = treeData.getPath(self.forest)
            sections = self.forest.getPathSections(self.geo.getSection(treeData.entrancePosition), p, pathKey.mVehicleIndex )
            s='-'.join(map(str, sections))
            self.file.write("%s"%s)
            comp = treeData.getComponents()
            self.file.write(";%f"%comp[1])
            self.file.write(";%f"%comp[0])
            self.file.write(";%f"%comp[2])

            costs =  self.geo.getPathCost( pathKey.mOriginIndex, pathKey.mDestinationIndex, connections, pathKey.mVehicleIndex, pathKey.mInterval )
            cost = costs.mCost
            self.file.write(";%f"%cost)

            distance = costs.mDistance
            self.file.write(";%f"%distance)

            if comp[2]==0.0:
                travel_time = 0.0
            else:
                travel_time = comp[3]/comp[2]

            self.file.write(";%f"%travel_time)

            if travel_time==0.0:
                speed = 0.0*3.6
            else:
                speed = distance*3.6/travel_time

            self.file.write(";%f"%speed)

            components = costs.mCostComponents
            if len(components)>0:
                for component in components:
                    self.file.write(";%f"%component)
            #c = ';'.join(map(str, comp))

            #self.file.write("%s"%c)
            self.file.write("\n")
            self.nbLines =self.nbLines+1
            if self.nbLines%1000==0:
                self.file.flush()

    def finishPaths(self):
        if self.file!=None:
            self.file.close()


replicacion1626=model.getCatalog().find( 1626 )
if (replicacion1626.getSimulationStatus() == GKGenericExperiment.eLoaded ):

    #Forest
    baseForest=replicacion1626.getPathsForest()

    #Filter
    customFilter=AnalysisFilter()
    #Filter could no applied iif it is passing to the reader without conditions. so this part could be skipped.
    intervals=[0]
    customFilter.setIntervals(intervals)
    userClass=0
    customFilter.setUserClass(userClass)
    originCentroids=[1586]
    customFilter.setOriginCentroids(originCentroids)
    destinationCentroids=[1589]
    customFilter.setDestinationCentroids(destinationCentroids)

    #Name
    repIdName='Replication'+str(replicacion1626.getId())
    #PathReader
    pr=PathReader(baseForest, model, repIdName)
    pr.init()
    pr.calculate(customFilter)
    pr.finishPaths()
else:   
    print( 'Replication %s is not simulated yet.' %repIdName)

print( 'info in file: %s_paths.csv.' %repIdName)

% Aimsun Next Retrieve Static Transit APA information

Analogously to the Aimsun Next kernel, the Macro PT plugin offers classes to iterate over all paths stored in an Path Assignment file generated from a Transit Assignment. The idea is to create a class that derives from the class PTForestCalculator and implements the doPTODPair function. It's possible to filter the paths before iterating through them. This filter can be done by using the class PTForestFilter and setting the corresponding filters. For example you can filter paths going through a set of sections or lines or only paths related to a specified user class.

The doPTODPair function receives a PTODPair instance containing all the information related to the demand, the paths and its percentages.

Once the derived class from the ForestCalculator is implemented this is the code to iterate through all paths:

#Filter
filter=PTForestFilter()
#PathReader
#forest is the apa file
pr=PathReader(forest, filter, model, repIdName)
pr.visit(forest)

Example: Retrieve path assignment costs information

import os.path

class PTPathReader(PTForestCalculator):

def __init__(self, forest, filter, model, name ):
    self.file = None
    self.model = model
    self.name = name
    self.forest = forest
    super(PTForestCalculator, self).__init__(forest, filter, model, False)

def init(self):
    info= QFileInfo(self.model.getDocumentFileName())
    filename = os.path.join(info.absolutePath(),self.name+'_paths.csv')
    self.file = open(filename, 'w')
    if self.file!=None:
        self.file.write("user;origin;destination;volume;cost;time;distance;\n")
        self.file.flush()
    else:
        print("Could not open file %s"%filename)

def doPTODPair(self,ptODpair):

    if self.file!=None:

        userId = self.forest.getUsers()[ ptODpair.user() ]
        originId = self.forest.getOriginCentroidId( ptODpair.origin() )
        destinationId = self.forest.getDestinationCentroidId( ptODpair.destination() )

        for strategy in ptODpair.strategies():

            for path in strategy.paths():

                self.file.write("%d;"% userId )
                self.file.write("%d;"% originId )
                self.file.write("%d;"% destinationId )
                self.file.write("%f;"%( path.factor()*ptODpair.volume() ) )
                self.file.write("%f;"%path.cost())
                self.file.write("%f;"%path.inVehicleTime())
                self.file.write("%f;"%path.inVehicleDistance())
                self.file.write("\n")

        self.file.flush()

def postProcess(self):
    if self.file!=None:
        self.file.close()

EXAMPLE OF USE

experiment=model.getCatalog().findByName("Transit Assignment Experiment") # SET THE REPLICATION ID HERE forest=experiment.getForest()

Filter

filter = PTForestFilter() filter.setUserClass( model.getCatalog().findByName("Transit Users - Work").getId() ) destinationCentroids=[model.getCatalog().findByName("Mall West").getId()] # SET THE DESTINATION CENTROIDS HERE filter.setDestinationCentroids(destinationCentroids)

PTPathReader

pr=PTPathReader(forest, filter, model, experiment.getName()) pr.visit(forest)

print("Done")