Last active
March 31, 2020 13:00
-
-
Save pedrocamargo/d565f545667fd473ea0590c7866965de to your computer and use it in GitHub Desktop.
Parsing Networks in the TNPM format for consumption in AequilibraE
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import aequilibrae | |
import os | |
import sys | |
import numpy as np | |
import pandas as pd | |
import openmatrix as omx | |
from aequilibrae.matrix import AequilibraeMatrix | |
data_folder = 'path/to/the/anaheim/folder' | |
matfile = os.path.join(data_folder, 'Anaheim_trips.tntp') | |
# Creating the matrix | |
f = open(matfile, 'r') | |
all_rows = f.read() | |
blocks = all_rows.split('Origin')[1:] | |
matrix = {} | |
for k in range(len(blocks)): | |
orig = blocks[k].split('\n') | |
dests = orig[1:] | |
orig=int(orig[0]) | |
d = [eval('{'+a.replace(';',',').replace(' ','') +'}') for a in dests] | |
destinations = {} | |
for i in d: | |
destinations = {**destinations, **i} | |
matrix[orig] = destinations | |
zones = max(matrix.keys()) | |
mat = np.zeros((zones, zones)) | |
for i in range(zones): | |
for j in range(zones): | |
mat[i, j] = matrix[i+1].get(j+1,0) | |
# Saving the matrix to an OMX container | |
omxfile = matfile.replace('tntp', 'omx') | |
index = np.arange(zones) + 1 | |
myfile = omx.open_file(omxfile,'w') | |
myfile['matrix'] = mat | |
myfile.create_mapping('taz', index) | |
myfile.close() | |
# Or if you prefer an AequilibraE matrix | |
aemfile = matfile.replace('tntp', 'aem') | |
aem = AequilibraeMatrix() | |
kwargs = {'file_name': aemfile, | |
'zones': zones, | |
'matrix_names': ['matrix']} | |
aem.create_empty(**kwargs) | |
aem.matrix['matrix'][:,:] = mat[:,:] | |
aem.index[:] = index[:] | |
# Now let's parse the network | |
net = os.path.join(data_folder, 'Anaheim_net.tntp') | |
net = pd.read_csv(net, skiprows=7, sep='\t') | |
# If you want to create an AequilibraE matrix for computation, then it follows | |
from aequilibrae.paths import Graph | |
g = Graph() | |
g.cost = net['Free Flow Time (min)'].values | |
g.capacity = net['Capacity (veh/h)'].values | |
g.free_flow_time = net['Free Flow Time (min)'].values | |
network = net[['Tail', 'Head', 'Free Flow Time (min)', 'Capacity (veh/h)' ]] | |
network.columns = ['a_node', 'b_node', 'time', 'capacity'] | |
network = network.assign(direction=1) | |
g.network = network.to_records(index=False) | |
g.network_ok = True | |
g.status = 'OK' | |
g.prepare_graph(index) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is what AequilibraE has been designed to do, but it still has a long way to go if compared to the commercial platforms you mentioned.