Migrating to the matrix API =========================== The matrix API replaces the previous ``AequilibraeMatrix`` workflow with two objects: ``AequilibraeMatrix`` for in-memory work and ``MatrixStore`` for interacting with an OMX file on disk. The import name for the in-memory class remains ``AequilibraeMatrix``. Both objects provide dictionary-style access to named matrices. Prefer ``AequilibraeMatrix`` for calculations. Use ``MatrixStore`` to inspect or update files and ``subset()`` to create an independent in-memory working set. Use the ``from_*`` functions to construct these objects from files, arrays or tabular data. For general usage, see :doc:`matrix`. Replace loading and computational views --------------------------------------- Previously, loading a file and selecting matrices for computation were separate operations: .. code-block:: python # Previous API from aequilibrae.matrix import AequilibraeMatrix demand = AequilibraeMatrix() demand.load("demand.omx") demand.set_index("zones") demand.computational_view(["car", "bus"]) Use ``from_file(..., store=True)`` to open a store and create a working set with ``subset()`` instead: .. code-block:: python # Matrix API from aequilibrae.matrix import from_file with from_file("demand.omx", index_name="zones", store=True) as store: demand = store.subset(["car", "bus"]) demand["car"] *= 1.1 demand["total"] = demand["car"] + demand["bus"] ``subset()`` returns an ``AequilibraeMatrix`` containing the selected named matrices, their zone index, file-level metadata and per-matrix attributes. It remains usable after the store closes, and changes to it do not change the source file. There is no ``computational_view()`` or ``matrix_view`` step. Work with each named matrix directly. Select only the matrices needed for the calculation rather than loading the whole file into memory. When the subset of matrices is known ahead of time, use ``from_file()`` with the ``subset`` argument directly: .. code-block:: python from aequilibrae.matrix import from_file demand = from_file( "demand.omx", index_name="zones", subset=["car", "bus"] ) ``from_file()`` returns an in-memory object by default. Providing ``store=True`` makes it return a store instead. For matrix files in a project, ``project.matrices.get_matrix()`` returns a ``MatrixStore`` by default. Supply ``subset`` to get an independent, in-memory ``AequilibraeMatrix`` for computation: .. code-block:: python with project.matrices.get_matrix("demand_mc.omx") as store: matrix_names = list(store) demand = project.matrices.get_matrix("demand_mc.omx", subset=["car", "trucks"]) When ``index_name`` is omitted, ``from_file()`` selects the only index in the OMX file when there is exactly one. If there are several indices, ``main_index`` is used when present, otherwise, specify ``index_name``. Project matrix loading uses the same ``from_file()`` index selection. .. _distribution_matrix_migration: Select matrices for distribution -------------------------------- ``Ipf``, ``GravityApplication`` and ``GravityCalibration`` take single-matrix collections for their seed, impedance or observed inputs. Replace ``computational_view()`` on a multi-matrix input with ``subset()`` and pass the returned collection to the procedure. For example, with ``vectors`` indexed in the same order as the seed matrix: .. code-block:: python from aequilibrae.distribution import Ipf ipf = Ipf( matrix=demand.subset(["car"]), vectors=vectors, row_field="productions", column_field="attractions", project=project, ) ipf.fit() ipf.save_to_project("balanced_demand.omx") For gravity, pass the selected skim as ``impedance=skims.subset(["time"])``. ``Ipf.fit()`` keeps its result in memory as ``ipf.output`` and no longer uses an ``output=`` filename. To save outside a project, call ``ipf.output.save_as_omx("balanced_demand.omx")``. Replace empty-matrix creation ----------------------------- The previous API created named matrices and then filled their index and values: .. code-block:: python # Previous API import numpy as np matrix = AequilibraeMatrix() matrix.create_empty(zones=3, matrix_names=["car", "bus"]) matrix.index[:] = [101, 205, 309] matrix.matrix["car"][:, :] = np.zeros((3, 3)) matrix.matrix["bus"][:, :] = np.zeros((3, 3)) Use ``AequilibraeMatrix`` with the zone index, then add named arrays: .. code-block:: python # Matrix API import numpy as np from aequilibrae.matrix import AequilibraeMatrix matrix = AequilibraeMatrix(index=[101, 205, 309], index_name="zones") matrix["car"] = np.zeros(matrix.shape) matrix["bus"] = np.zeros(matrix.shape) If the arrays are already available, use ``from_dict()`` instead: .. code-block:: python from aequilibrae.matrix import from_dict matrix = from_dict( {"car": np.zeros((3, 3)), "bus": np.zeros((3, 3))}, index=[101, 205, 309], index_name="zones", ) Replace matrix access and inspection ------------------------------------ Access matrices by name rather than through ``matrix``, ``get_matrix()`` or dynamically named attributes. Use ``.imat`` for zero-based positions or ``.mat`` for zone IDs, with the matrix name first, when changing values to ensure the underlying data is changed, rather than a copy. Matrix names must be non-empty strings, not paths. Slashes, backslashes, null characters, ``.`` and ``..`` are not allowed as matrix names. .. list-table:: :header-rows: 1 * - Previous workflow - Matrix API * - ``matrix.get_matrix("car")`` - ``matrix["car"]`` * - ``matrix.get_matrix("car", copy=True)`` - ``matrix["car"].copy()`` * - ``matrix.matrix["car"][0, 1]`` - ``matrix.imat["car", 0, 1]`` * - ``matrix.matrix["car"][:, 1] = values`` - ``matrix.imat["car", :, 1] = values`` * - ``matrix.names`` - ``list(matrix)`` * - ``matrix.cores`` - ``len(matrix)`` * - ``matrix.zones`` - ``len(matrix.index)`` * - ``matrix.copy(cores=["car"])`` - ``matrix.subset(["car"])`` For example: .. code-block:: python matrix.imat["car", 0, 1] = 42 matrix.imat["car", :, 2] = [1, 2, 3] selected = matrix.subset(["car"]) print(list(selected), selected.shape) Replace index changes --------------------- Choose an OMX mapping with ``index_name`` when opening the file rather than calling ``set_index()`` after loading. If the file has only one mapping, ``from_file()`` selects it automatically. If there are several mappings, it selects ``main_index`` when present, otherwise, specify ``index_name``. Each object has one selected zone index. To use another mapping, open the file again with that mapping's name. Index names follow the same rules as matrix names: they must be non-empty strings, and HDF5 paths are not accepted. The retrieved index is read-only. Replace slice assignment with assignment of the complete index: .. code-block:: python # Previous API matrix.index[:] = [1001, 1002, 1003] .. code-block:: python # Matrix API matrix.index = [1001, 1002, 1003] Index values must be unique, non-negative integers from ``0`` to ``2**64 - 1``. They are stored in memory as ``uint64``. Booleans and floating-point values are not accepted, even floats such as ``1.0``. The index length cannot change after construction. Relabelling the index does not reorder the matrix values. Create a new object when the number of zones changes. Replace saves and file edits ---------------------------- For in-memory results, replace ``export()`` and file-oriented ``save()`` calls with ``save_as_omx()``: .. code-block:: python # Previous API demand.export("adjusted_demand.omx", cores=["car", "bus"]) .. code-block:: python # Matrix API demand.save_as_omx("adjusted_demand.omx", subset=["car", "bus"]) The zone index and file-level metadata are saved with the selected matrices. The default ``mode="x"`` creates a new output file and raises ``FileExistsError`` if it already exists. Use ``mode="r+"`` to update an existing file, or ``mode="a"`` to update or create one. Selected matrices, the zone mapping and supplied metadata are always written: .. code-block:: python demand.save_as_omx( "adjusted_demand.omx", mode="r+", subset=["car", "bus"] ) Updating an existing files does not remove matrices or metadata that is not on the object. Use ``mode="w"`` to replace the whole file, removing all previous contents. For direct file edits, use ``from_file()`` to open a writable store. Stores open read-only by default. In ``from_file()``, the ``mode`` argument is only accepted with ``store=True``: .. code-block:: python with from_file( "demand.omx", index_name="zones", mode="r+", store=True ) as store: store.imat["car", 0, 1] = 42 store.imat["bus", :, 2] = [1, 2, 3] These assignments update the file without a separate save call. ``store["car"][:, 2] = ...`` only changes the returned array, so replace it with ``store.imat["car", :, 2] = ...``. The store provides file access through a similar interface to the in-memory object, but prefer ``subset()`` and an ``AequilibraeMatrix`` for calculations. Use a ``with`` block to close stores, or call ``store.close()`` explicitly. In-memory objects do not need ``close()``. Use ``store.omx`` for OMX-specific operations. Replace descriptive attributes ------------------------------ Use ``metadata`` for file-level information instead of the old ``name`` and ``description`` attributes: .. code-block:: python demand.metadata.update( {"name": "morning_demand", "description": "Adjusted morning demand"} ) OMX-managed file attributes are ignored when loading, copying, saving and comparing metadata. Use ``matrix_metadata(name)`` to read or change per-matrix attributes. These attributes can then be used with ``matrix.subset([{"mode": "car"}])`` to select an in-memory working set. Attribute queries work on both objects. Replace each metadata value as a whole, for example ``demand.metadata["periods"] = [1, 2, 3]``. Nested edits to a value are not supported. This also applies to values returned by ``matrix_metadata(name)``. Replace trip-list loading ------------------------- Replace ``create_from_trip_list()`` with a pandas read followed by ``from_df()``: .. code-block:: python import pandas as pd from aequilibrae.matrix import from_df trips = pd.read_csv("trips.csv") demand_from_trips = from_df( trips, row="origin", col="destination", subset=["car", "bus"], index_name="zones", ) demand_from_trips.save_as_omx("trip_demand.omx") Repeated origin-destination pairs are summed, and missing pairs default to zero. The index can be inferred from the sorted unique origin and destination IDs but you should pass ``index`` explicitly when a particular zone order or extra zones are required. Pass ``sparse=True`` to construct an ``AequilibraeSparseMatrix`` directly from the records without a dense intermediate, this requires ``fill_value=0``. Use sparse select-link results ------------------------------ Assignment select-link OD outputs are dictionaries of SciPy ``csr_array`` objects, indexed first by selection name and then by demand field name. Route-choice outputs map selection names to ``AequilibraeSparseMatrix`` objects, which retain the demand's zone index as well as its field names and order: .. code-block:: python selected = assignment.class_results["car"].select_link_od.matrices car = selected["screenline"]["car"] print(car[0, 1], car.sum()) selected_routes = route_choice.get_select_link_od_matrix_results() car_routes = selected_routes["screenline"]["car"] zone_ids = selected_routes["screenline"].index The old ``Sparse``, ``COO`` and ``GeneralisedCOODemand`` classes have been removed. Use ``RouteChoice.set_demand()`` to provide the complete ``AequilibraeMatrix`` or ``AequilibraeSparseMatrix``, and ``RouteChoice.prepare()`` for routing without demand. Only pairs with non-zero demand in at least one field will have a route set constructed. Use ``RouteChoice.prepare()`` to generate route sets for arbitrary OD pairs without a demand matrix. Move existing files to OMX -------------------------- The matrix objects support OMX only for file storage. Convert existing ``.aem`` files with the previous API before moving to the new objects: .. code-block:: python # Previous API, before upgrading legacy = AequilibraeMatrix() legacy.load("legacy.aem") legacy.export("converted.omx") legacy.close() For a project matrix, export the OMX file into the same scenario's ``matrices`` folder. In 1.x, retrieve the existing record with ``project.matrices.get_record(matrix_name)``, set its ``file_name`` to the new OMX filename and call ``record.save()`` to preserve the catalogue metadata. The 2.0 migration cannot migrate a catalogue entry that still points to an ``.aem`` file.