Skip to main content
`Ctrl`+`K`

# aequilibrae.matrix.AequilibraeMatrix

class aequilibrae.matrix.AequilibraeMatrix

  Matrix class

  __init__()

    Creates a memory instance for a matrix, that can be used to load an existing matrix or to create an empty one

  Methods

  `__init__`() | Creates a memory instance for a matrix, that can be used to load an existing matrix or to create an empty one
  `close`() | Removes matrix from memory and flushes all data to disk, or closes the OMX file if that is the case
  `columns`() | Returns column vector for the matrix in the computational view
  `computational_view`([core_list]) | Creates a memory view for a list of matrices that is compatible with Cython memory buffers
  `copy`([output_name, cores, names, compress, ...]) | Copies a list of cores (or all cores) from one matrix file to another one
  `create_empty`([file_name, zones, ...]) | Creates an empty matrix in the AequilibraE format
  `create_from_omx`(omx_path[, file_path, ...]) | Creates an AequilibraeMatrix from an original OpenMatrix
  `create_from_trip_list`(path_to_file, ...) | Creates an AequilibraeMatrix from a trip list csv file The output is saved in the same folder as the trip list file
  `export`(output_name[, cores]) | Exports the matrix to other formats, rather than AEM.
  `get_matrix`(core[, copy]) | Returns the data for a matrix core
  `is_omx`() | Returns `True` if matrix data source is OMX, `False` otherwise
  `load`(file_path) | Loads matrix from disk.
  `nan_to_num`() | Converts all `NaN` values in all cores in the computational view to zeros
  `random_name`() | Returns a random name for a matrix with root in the temp directory of the user
  `rows`() | Returns row vector for the matrix in the computational view
  `save`([names, file_name]) | Saves matrix data back to file.
  `setDescription`(matrix_description) | Sets description for the matrix
  `setName`(matrix_name) | Sets the name for the matrix itself.
  `set_index`(index_to_set) | Sets the standard index to be the one the user wants to have be the one being used in all operations during run time.

  close()

    Removes matrix from memory and flushes all data to disk, or closes the OMX file if that is the case

  columns() → ndarray

    Returns column vector for the matrix in the computational view

    Computational view needs to be set to a single matrix core

    Returns:

      object (`np.ndarray`): the column totals for the matrix currently on the computational view

        >>> from aequilibrae.matrix import AequilibraeMatrix

        >>> project = create_example(project_path)

        >>> mat = AequilibraeMatrix()
        >>> mat.load(os.path.join(project_path, 'matrices/skims.omx'))
        >>> mat.computational_view(["distance_blended"])
        >>> mat.columns()
        array([357.54256811, 357.45109051, 310.88655449, 276.6783439 ,
               266.70388637, 270.62976319, 266.32888632, 279.6897402 ,
               285.89821842, 242.79743295, 252.34085912, 301.78116548,
               302.97058146, 270.61855294, 264.59944248, 257.83842251,
               276.63310578, 257.74513863, 281.15724257, 271.63886077,
               264.62215032, 252.79791125, 273.18139747, 282.7636574 ])

  computational_view(core_list: List[str] | None = None)

    Creates a memory view for a list of matrices that is compatible with Cython memory buffers

    It allows for AequilibraE matrices to be used in all parallelized algorithms within AequilibraE

    In case of OMX matrices, the computational view is held only in memory

    Arguments:

      core_list (`list`): List with the names of all matrices that need to be in the buffer

        >>> from aequilibrae.matrix import AequilibraeMatrix

        >>> zones_in_the_model = 3317
        >>> names_list = ['Car trips', 'pt trips', 'DRT trips', 'bike trips', 'walk trips']

        >>> mat = AequilibraeMatrix()
        >>> mat.create_empty(file_name=os.path.join(my_folder_path, 'my_matrix.aem'),
        ...                  zones=zones_in_the_model,
        ...                  matrix_names=names_list)
        >>> mat.computational_view(['bike trips', 'walk trips'])
        >>> mat.view_names
        ['bike trips', 'walk trips']

  copy(output_name: str | None = None, cores: List[str] | None = None, names: List[str] | None = None, compress: bool | None = None, memory_only: bool = True)

    Copies a list of cores (or all cores) from one matrix file to another one

    Arguments:

      output_name (`str`): Name of the new matrix file. If none is provided, returns a copy in memory only

      cores (`list`): List of the matrix cores to be copied

      names (`list`, Optional): List with the new names for the cores. Defaults to current names

      compress (`bool`, Optional): Whether you want to compress the matrix or not. Defaults to `False`. Not yet implemented

      memory_only (`bool`, Optional): Whether you want to keep the matrix copy in memory only. Defaults to `True`

        >>> from aequilibrae.matrix import AequilibraeMatrix

        >>> zones_in_the_model = 3317
        >>> names_list = ['Car trips', 'pt trips', 'DRT trips', 'bike trips', 'walk trips']

        >>> mat = AequilibraeMatrix()
        >>> mat.create_empty(file_name=os.path.join(my_folder_path, 'my_matrix.aem'),
        ...                  zones=zones_in_the_model,
        ...                  matrix_names=names_list)

        >>> mat.copy(os.path.join(my_folder_path, 'copy_of_my_matrix.aem'),
        ...          cores=['bike trips', 'walk trips'],
        ...          names=['bicycle', 'walking'],
        ...          memory_only=False)
        <aequilibrae.matrix.aequilibrae_matrix.AequilibraeMatrix object at 0x...>

        >>> mat2 = AequilibraeMatrix()
        >>> mat2.load(os.path.join(my_folder_path, 'copy_of_my_matrix.aem'))
        >>> mat2.cores
        2

  create_empty(file_name: str | None = None, zones: int | None = None, matrix_names: ~typing.List[str] | None = None, data_type: ~numpy.dtype = <class 'numpy.float64'>, index_names: ~typing.List[str] | None = None, compressed: bool = False, memory_only: bool = True)

    Creates an empty matrix in the AequilibraE format

    Arguments:

      file_name (`str`): Local path to the matrix file

      zones (`int`): Number of zones in the model (Integer). Maximum number of zones in a matrix is 4,294,967,296

      matrix_names (`list`): A regular Python list of names of the matrix. Limit is 50 characters each. Maximum number of cores per matrix is 256

      data_type (`np.dtype`, Optional): Data type of the matrix as NUMPY data types (`np.int32`, `np.int64`, `np.float32`, `np.float64`). Defaults to `np.float64`

      index_names (`list`, Optional): A regular Python list of names for indices. Limit is 20 characters each. Maximum number of indices per matrix is 256

      compressed (`bool`, Optional): Whether it is a flat matrix or a compressed one (Boolean - Not yet implemented)

      memory_only (`bool`, Optional): Whether you want to keep the matrix copy in memory only. Defaults to `True`

        >>> from aequilibrae.matrix import AequilibraeMatrix

        >>> zones_in_the_model = 3317
        >>> names_list = ['Car trips', 'pt trips', 'DRT trips', 'bike trips', 'walk trips']

        >>> mat = AequilibraeMatrix()
        >>> mat.create_empty(file_name=os.path.join(my_folder_path, 'my_matrix.aem'),
        ...                  zones=zones_in_the_model,
        ...                  matrix_names=names_list,
        ...                  memory_only=False)
        >>> mat.num_indices
        1
        >>> mat.zones
        3317

  create_from_omx(omx_path: str, file_path: str | None = None, cores: List[str] | None = None, mappings: List[str] | None = None, robust: bool = True, compressed: bool = False, memory_only: bool = True) → None

    Creates an AequilibraeMatrix from an original OpenMatrix

    Arguments:

      omx_path (`str`): Path to the OMX file one wants to import

      file_path (`str`, Optional): Path for the output AequilibraeMatrix

      cores (`list`, Optional): List of matrix cores to be imported

      mappings (`list`, Optional): List of the matrix mappings (i.e. indices, centroid numbers) to be imported

      robust (`bool`, Optional): Boolean for whether AequilibraE should try to adjust the names for cores and indices in case they are too long. Defaults to `True`

      compressed (`bool`, Optional): Boolean for whether we should compress the output matrix. Not yet implemented

      memory_only (`bool`, Optional): Whether you want to keep the matrix copy in memory only. Defaults to `True`

  create_from_trip_list(path_to_file: str, from_column: str, to_column: str, list_cores: List[str]) → str

    Creates an AequilibraeMatrix from a trip list csv file The output is saved in the same folder as the trip list file

    Arguments:

      path_to_file (`str`): Path for the trip list csv file

      from_column (`str`): trip list file column containing the origin zones numbers

      to_column (`str`): trip list file column containing the destination zones numbers

      list_cores (`list`): list of core columns in the trip list file

  export(output_name: str, cores: List[str] | None = None)

    Exports the matrix to other formats, rather than AEM. Formats currently supported: CSV, OMX

    When exporting to AEM or OMX, the user can chose to export only a set of cores, but all indices are exported

    When exporting to CSV, the active index will be used, and all cores will be exported as separate columns in the output file

    Arguments:

      output_name (`str`): Path to the output file

      cores (`list`): Names of the cores to be exported.

        >>> from aequilibrae.matrix import AequilibraeMatrix

        >>> zones_in_the_model = 3317
        >>> names_list = ['Car trips', 'pt trips', 'DRT trips', 'bike trips', 'walk trips']

        >>> mat = AequilibraeMatrix()
        >>> mat.create_empty(file_name=os.path.join(my_folder_path, 'my_matrix.aem'),
        ...                  zones=zones_in_the_model,
        ...                  matrix_names=names_list)

        >>> mat.export(os.path.join(my_folder_path, 'my_new_path.aem'), ['Car trips', 'bike trips'])

        >>> mat2 = AequilibraeMatrix()
        >>> mat2.load(os.path.join(my_folder_path, 'my_new_path.aem'))
        >>> mat2.cores
        2

  get_matrix(core: str, copy=False) → ndarray

    Returns the data for a matrix core

    Arguments:

      core (`str`): name of the matrix core to be returned

      copy (`bool`, Optional): return a copy of the data. Defaults to False

    Returns:

      object (`np.ndarray`): NumPy array

  is_omx()

    Returns `True` if matrix data source is OMX, `False` otherwise

  load(file_path: str)

    Loads matrix from disk. All cores and indices are load. First index is default.

    Arguments:

      file_path (`str`): Path to AEM or OMX file on disk

        >>> from aequilibrae.matrix import AequilibraeMatrix

        >>> project = create_example(project_path)

        >>> mat = AequilibraeMatrix()
        >>> mat.load(os.path.join(project_path, 'matrices/skims.omx'))
        >>> mat.computational_view()
        >>> mat.names
        ['distance_blended', 'time_final']

  nan_to_num()

    Converts all `NaN` values in all cores in the computational view to zeros

        >>> from aequilibrae.matrix import AequilibraeMatrix

        >>> nan_matrix = np.empty((3,3))
        >>> nan_matrix[:] = np.nan

        >>> index = np.arange(1, 4, dtype=np.int32)

        >>> mat = AequilibraeMatrix()
        >>> mat.create_empty(file_name=os.path.join(my_folder_path, "matrices/nan_matrix.aem"),
        ...                  zones=3,
        ...                  matrix_names=["only_nan"])
        >>> mat.index[:] = index[:]
        >>> mat.matrix["only_nan"][:, :] = nan_matrix[:, :]
        >>> mat.computational_view()
        >>> mat.nan_to_num()
        >>> mat.get_matrix("only_nan")
        array([[0., 0., 0.],
               [0., 0., 0.],
               [0., 0., 0.]])

  static random_name() → str

    Returns a random name for a matrix with root in the temp directory of the user

        >>> from aequilibrae.matrix import AequilibraeMatrix

        >>> mat = AequilibraeMatrix()
        >>> mat.random_name()
        '/tmp/Aequilibrae_matrix_...'

  rows() → ndarray

    Returns row vector for the matrix in the computational view

    Computational view needs to be set to a single matrix core

    Returns:

      object (`np.ndarray`): the row totals for the matrix currently on the computational view

        >>> from aequilibrae.matrix import AequilibraeMatrix

        >>> project = create_example(project_path)

        >>> mat = AequilibraeMatrix()
        >>> mat.load(os.path.join(project_path, 'matrices/skims.omx'))
        >>> mat.computational_view(["distance_blended"])
        >>> mat.rows()
        array([357.68202084, 358.68778868, 310.68285491, 275.87964738,
               265.91709918, 268.60184371, 267.32264726, 281.3793747 ,
               286.15085073, 242.60308705, 252.1776242 , 305.56774194,
               303.58100777, 270.48841269, 263.20417379, 253.92665702,
               277.1655432 , 258.84368258, 280.65697316, 272.7651157 ,
               264.06806038, 252.87533845, 273.45639965, 281.61102767])

  save(names=(), file_name=None) → None

    Saves matrix data back to file.

    If working with AEM file, it flushes data to disk. If working with OMX, requires new names.

    Arguments:

      names (`tuple(str)`, Optional): New names for the matrices. Required if working with OMX files

      file_name (`str`, Optional): Local path to the matrix file

  setDescription(matrix_description: str)

    Sets description for the matrix

    Arguments:

      matrix_description (`str`): Text with matrix description. Maximum length is 144 characters

        >>> from aequilibrae.matrix import AequilibraeMatrix

        >>> zones_in_the_model = 3317

        >>> mat = AequilibraeMatrix()
        >>> mat.create_empty(file_name=os.path.join(my_folder_path, 'my_matrix.aem'),
        ...                  zones=zones_in_the_model,
        ...                  memory_only=False)
        >>> mat.setDescription('This is a text')
        >>> mat.save()
        >>> mat.close()

        >>> mat = AequilibraeMatrix()
        >>> mat.load(os.path.join(my_folder_path, 'my_matrix.aem'))
        >>> mat.description.decode('utf-8')
        'This is a text'

  setName(matrix_name: str)

    Sets the name for the matrix itself. Only works for matrices in disk.

    Arguments:

      matrix_name (`str`): matrix name. Maximum length is 50 characters

        >>> from aequilibrae.matrix import AequilibraeMatrix

        >>> zones_in_the_model = 3317

        >>> mat = AequilibraeMatrix()
        >>> mat.create_empty(file_name=os.path.join(my_folder_path, 'my_matrix.aem'),
        ...                  zones=zones_in_the_model,
        ...                  memory_only=False)
        >>> mat.setName('This is my example')
        >>> mat.save()
        >>> mat.close()

        >>> mat = AequilibraeMatrix()
        >>> mat.load(os.path.join(my_folder_path, 'my_matrix.aem'))
        >>> mat.name.decode('utf-8')
        'This is my example'

  set_index(index_to_set: str) → None

    Sets the standard index to be the one the user wants to have be the one being used in all operations during run time. The first index is ALWAYS the default one every time the matrix is instantiated

    Arguments:

      index_to_set (`str`): Name of the index to be used. The default index name is ‘main_index’

        >>> from aequilibrae.matrix import AequilibraeMatrix

        >>> zones_in_the_model = 3317
        >>> names_list = ['Car trips', 'pt trips', 'DRT trips', 'bike trips', 'walk trips']
        >>> index_list = ['tazs', 'census']

        >>> mat = AequilibraeMatrix()
        >>> mat.create_empty(file_name=os.path.join(my_folder_path, 'my_matrix.aem'),
        ...                  zones=zones_in_the_model,
        ...                  matrix_names=names_list,
        ...                  index_names=index_list )
        >>> mat.num_indices
        2
        >>> mat.current_index
        'tazs'
        >>> mat.set_index('census')
        >>> mat.current_index
        'census'