aequilibrae.matrix#
Functions
|
Create dense or sparse in-memory matrices from an origin-destination DataFrame. |
|
Create named square matrices from a mapping of names to array-like values. |
|
Load an OMX file as an in-memory matrix or an on-disk store. |
Classes
|
A dictionary-like collection of square matrices held in memory. |
|
A dictionary-like collection of square SciPy sparse arrays held in memory. |
|
A dictionary-like collection of square matrices backed by an OMX file. |
- class aequilibrae.matrix.AequilibraeMatrix(index: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str], index_name: str = 'main_index')[source]#
A dictionary-like collection of square matrices held in memory.
All matrices use the same zone index for rows and columns.
Assigning a whole matrix copies the values and keeps their dtype. Reading a matrix or taking a basic slice returns a view of its data. Use
.copy()when you need an independent array. You can also use dictionary operations such askeys(),items()andupdate().Matrix and index names must be non-empty strings, not paths. They cannot be
"."or"..", or contain a slash, backslash or null character.>>> demand = AequilibraeMatrix(index=[101, 205], index_name="zones") >>> demand["car"] = [[0, 12], [10, 0]] >>> demand["bus"] = [[0, 2], [2, 0]] >>> demand["total"] = demand["car"] + demand["bus"] >>> list(demand) ['car', 'bus', 'total'] >>> demand["total"].tolist() [[0, 14], [12, 0]] >>> del demand["total"] >>> len(demand), demand.shape (2, (2, 2))
- classmethod from_omx(path: str | PathLike, index_name: str = 'main_index', subset: Sequence[str | dict[str, Any]] | None = None, **kwargs) Self[source]#
Load matrices from an OMX file into memory.
The file must contain the mapping named by
index_name. By default, all matrices are loaded. Passsubsetto choose matrices by name or by their attributes. A query matches matrices with all the given attributes, and each matching matrix is loaded once.Matrix values, the zone index and metadata are copied. Changing the loaded object does not change the file.
- Arguments:
- path (
stroros.PathLike): Existing OMX file to load.
- index_name (
str, Optional): Existing zone mapping to read. Defaults to
"main_index".- subset (sequence of
strordict, Optional): Matrix names or attribute queries to load. Defaults to all matrices.
- kwargs: Additional keyword arguments passed to the matrix
constructor.
- path (
>>> from pathlib import Path >>> from tempfile import TemporaryDirectory >>> demand = from_dict({"car": [[12]], "bus": [[2]]}, index=[101]) >>> demand.matrix_metadata("car")["mode"] = "car" >>> with TemporaryDirectory() as directory: ... path = Path(directory) / "demand.omx" ... demand.save_as_omx(path) ... working = AequilibraeMatrix.from_omx(path, subset=[{"mode": "car"}]) >>> list(working) ['car'] >>> working["car"].tolist() [[12]]
- clear() None#
Remove all named matrices and their attributes.
The zone index and file-level metadata are kept.
>>> demand = from_dict({"car": [[0]]}, index=[101]) >>> demand.metadata["year"] = 2030 >>> demand.clear() >>> list(demand), demand.index.tolist(), demand.metadata["year"] ([], [101], 2030)
- get(k[, d]) D[k] if k in D, else d. d defaults to None.#
- items() a set-like object providing a view on D's items#
- keys() a set-like object providing a view on D's keys#
- matrix_metadata(name: str) MutableMapping[str, Any][source]#
Return the mutable attribute dictionary for an existing named matrix.
Assign a new value to an attribute to update it. Attributes are kept when you replace a matrix and can be used to select matrices with
subset().- Arguments:
name (
str): Name of an existing matrix.
>>> demand = from_dict({"car": [[12]]}, index=[101]) >>> demand.matrix_metadata("car")["mode"] = "car" >>> demand["car"] = [[15.0]] >>> demand.matrix_metadata("car")["mode"] 'car'
- pop(k[, d]) v, remove specified key and return the corresponding value.#
If key is not found, d is returned if given, otherwise KeyError is raised.
- popitem() (k, v), remove and return some (key, value) pair#
as a 2-tuple; but raise KeyError if D is empty.
- save_as_omx(path: str | PathLike, mode: Literal['w', 'a', 'r+', 'w-', 'x'] = 'x', *, subset: Sequence[str | dict[str, Any]] | None = None, **kwargs) None#
Save named matrices, their attributes, the zone index and file metadata to OMX.
By default, this saves all matrices to a new file and raises an error if the file already exists. Pass
subsetto select matrices by name or by their attributes. A query matches matrices with all the given attributes. Each matrix is saved once, even if it matches several entries.When updating a file, matrices outside the subset are left unchanged. Attributes provided here replace matching attributes in the file. Other attributes are kept. The zone mapping and file metadata are always written, apart from attributes managed by OMX.
- Arguments:
path (
stroros.PathLike): Destination OMX file.- mode (
str, Optional): Use"x"or"w-"to create a new file,
"w"to replace or create a file,"r+"to update an existing file, or"a"to update or create a file. Defaults to"x".- subset (sequence of
strordict, Optional): Matrix names or attribute queries to save. Defaults to all matrices. If nothing matches, only the zone mapping and file metadata are written.
- kwargs: Additional keyword arguments passed to
openmatrix.open_file.
- mode (
>>> from pathlib import Path >>> from tempfile import TemporaryDirectory >>> demand = from_dict({"car": [[0, 12], [10, 0]]}, index=[101, 205]) >>> demand.matrix_metadata("car")["mode"] = "car" >>> with TemporaryDirectory() as directory: ... path = Path(directory) / "demand.omx" ... demand.save_as_omx(path, subset=[{"mode": "car"}]) ... loaded = from_file(path) >>> loaded == demand True
- setdefault(key: str, default: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str] | bsr_array | coo_array | csc_array | csr_array | dok_array | lil_array | None = None) _ArrayT#
Return a named matrix, adding it from
defaultif it is missing.An existing matrix is returned unchanged. If the name is missing,
defaultmust contain a full square matrix.Nonecannot be used to create a matrix.As with a normal lookup, the result is a view for a dense in-memory matrix, the stored array for a sparse matrix and a copy for a store.
- Arguments:
key (
str): Matrix name to look up or insert.- default (array-like, Optional): Full square matrix to insert
if the name is missing. Defaults to
None, which is only valid when the matrix already exists.
>>> demand = AequilibraeMatrix(index=[101]) >>> demand.setdefault("car", [[12]]).tolist() [[12]] >>> demand.setdefault("car", [[99]]).tolist() [[12]]
- subset(subset: Sequence[str | dict[str, Any]]) Self[source]#
Copy selected matrices into a new in-memory matrix object.
Select matrices by name or by their attributes. A query matches matrices with all the given attributes. Each matrix is included once, even if it matches more than one entry.
The arrays, zone index and metadata are copied. Changes to the result do not affect the original object.
- Arguments:
- subset (sequence of
strordict): Matrix names or attribute queries to copy.
- subset (sequence of
>>> demand = from_dict({"car": [[12]], "bus": [[2]]}, index=[101]) >>> demand.matrix_metadata("car")["mode"] = "car" >>> working = demand.subset([{"mode": "car"}, "car"]) >>> list(working) ['car'] >>> working["car"] *= 2 >>> demand["car"].tolist(), working["car"].tolist() ([[12]], [[24]])
- totals() dict[str, Any]#
Return each named matrix’s total.
- update([E, ]**F) None. Update D from mapping/iterable E and F.#
If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v
- values() an object providing a view on D's values#
- property imat: _MatrixIndexer[_ArrayT]#
Read or change matrix values using zero-based positions.
Use
imat[name]for a whole matrix,imat[name, row]for rows, orimat[name, row, column]to select both rows and columns. Slices exclude the stop position.Zone IDs are converted to positions before indexing. In-memory, dense matrices use NumPy selections while sparse matrices use SciPy selections. Stored dense matrices support the selections allowed by h5py. Stored sparse matrices only support whole-matrix access. Writing to a selection keeps the matrix’s dtype. Values are broadcast and converted according to the array or dataset’s rules.
>>> demand = from_dict({"car": [[0, 12], [10, 0]]}, index=[101, 205]) >>> demand.imat["car", :, 1].tolist() [12, 0] >>> demand.imat["car", 0, :] = [1, 2] >>> demand.imat["car", :1].tolist() [[1, 2]]
- property index: ndarray#
Zone IDs in row and column order, returned as a read-only uint64 array.
IDs must be unique integers between
0and2**64 - 1. To relabel zones, assign a new index of the same length. This does not move any matrix values.Changing a store’s index requires write access. The mapping keeps its existing dtype and attributes.
>>> demand = from_dict({"car": [[0, 12], [10, 0]]}, index=[101, 205]) >>> demand.index.tolist() [101, 205] >>> demand.index.flags.writeable False >>> demand.index = [1001, 1002] >>> int(demand.mat["car", 1001, 1002]) 12
- property index_name: str#
Name of the zone mapping used when reading and writing OMX files.
>>> AequilibraeMatrix(index=[101, 205]).index_name 'main_index' >>> AequilibraeMatrix(index=[101, 205], index_name="zones").index_name 'zones'
- property mat: _MatrixIndexer[_ArrayT]#
Read or change matrix values using zone IDs.
Use
mat[name]for a whole matrix,mat[name, row]for rows, ormat[name, row, column]to select both rows and columns. Slices follow the stored zone order and include the stop ID. An unknown zone ID raisesKeyError.Zone IDs are converted to positions before indexing. In-memory, dense matrices use NumPy selections while sparse matrices use SciPy selections. Stored dense matrices support the selections allowed by h5py. Stored sparse matrices only support whole-matrix access. Writing to a selection keeps the matrix’s dtype. Values are broadcast and converted according to the array or dataset’s rules.
>>> demand = from_dict({"car": [[0, 12], [10, 0]]}, index=[101, 205]) >>> demand.mat["car", 101:205].tolist() [[0, 12], [10, 0]] >>> demand.mat["car", 101, 205] = 42 >>> int(demand.mat["car", 101, 205]) 42
- property metadata: MutableMapping[str, Any]#
File-level attributes that can be read and updated by name.
These are stored in a dictionary for in-memory matrices and in h5py attributes for stores. Assign a new value to an attribute to update it.
Attributes managed by OMX are visible on a store but are ignored when loading, copying, saving or comparing file metadata.
>>> demand = AequilibraeMatrix(index=[101, 205]) >>> demand.metadata["description"] = "Morning demand" >>> demand.metadata["description"] 'Morning demand'
- property shape: tuple[int, int]#
Shape of each matrix, determined by the number of zone IDs.
>>> demand = AequilibraeMatrix(index=[101, 205, 309]) >>> demand.shape (3, 3) >>> len(demand) 0
- class aequilibrae.matrix.AequilibraeSparseMatrix(index: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str], index_name: str = 'main_index')[source]#
A dictionary-like collection of square SciPy sparse arrays held in memory.
All matrices use the same zone index for rows and columns. Assigning a matrix copies the array and keeps its sparse format and dtype. Reading a whole matrix returns the stored array, so changes to it change the matrix. Use
.copy()when you need an independent array. Selections throughmatandimatfollow the sparse format’s own SciPy indexing rules.Saving writes each array in the CSR format. This extends the OMX format with a
/sparse/<name>group for each matrix. The group has arow_index(CSR row pointers),col_index(column positions) anddatadatasets. The group attributeFORMATis set to"csr". Zone mappings, file metadata, and shape use the standard OMX attributes.When reading, only
/sparseis read from, dense matrices in/dataare ignored. UseMatrixStoreor :method:`AequilibraeMatrix.from_omx()` instead.Matrix and index names follow the same rules as
AequilibraeMatrix.>>> from scipy.sparse import coo_array >>> demand = AequilibraeSparseMatrix(index=[101, 205]) >>> demand["car"] = coo_array([[0, 12], [10, 0]]) >>> demand["car"].format 'coo' >>> demand["car"].toarray().tolist() [[0, 12], [10, 0]]
- classmethod from_omx(path: str | PathLike, index_name: str = 'main_index', subset: Sequence[str | dict[str, Any]] | None = None, **kwargs) Self[source]#
Load CSR arrays from the OMX extension group
/sparseinto memory.Dense matrices in
/dataare ignored. Values, the zone index and metadata are copied. Changes to the result do not change the file.- Arguments:
path (
stroros.PathLike): Existing OMX file.- index_name (
str, Optional): Existing zone mapping to read. Defaults to
"main_index".- subset (sequence of
strordict, Optional): Matrix names or attribute queries. Defaults to all sparse matrices. Each matching matrix is loaded once.
kwargs: Additional keyword arguments passed to the constructor.
- index_name (
- clear() None#
Remove all named matrices and their attributes.
The zone index and file-level metadata are kept.
>>> demand = from_dict({"car": [[0]]}, index=[101]) >>> demand.metadata["year"] = 2030 >>> demand.clear() >>> list(demand), demand.index.tolist(), demand.metadata["year"] ([], [101], 2030)
- get(k[, d]) D[k] if k in D, else d. d defaults to None.#
- items() a set-like object providing a view on D's items#
- keys() a set-like object providing a view on D's keys#
- matrix_metadata(name: str) MutableMapping[str, Any][source]#
Return mutable attributes for an existing named sparse matrix.
- pop(k[, d]) v, remove specified key and return the corresponding value.#
If key is not found, d is returned if given, otherwise KeyError is raised.
- popitem() (k, v), remove and return some (key, value) pair#
as a 2-tuple; but raise KeyError if D is empty.
- save_as_omx(path: str | PathLike, mode: Literal['w', 'a', 'r+', 'w-', 'x'] = 'x', *, subset: Sequence[str | dict[str, Any]] | None = None, **kwargs) None#
Save named matrices, their attributes, the zone index and file metadata to OMX.
By default, this saves all matrices to a new file and raises an error if the file already exists. Pass
subsetto select matrices by name or by their attributes. A query matches matrices with all the given attributes. Each matrix is saved once, even if it matches several entries.When updating a file, matrices outside the subset are left unchanged. Attributes provided here replace matching attributes in the file. Other attributes are kept. The zone mapping and file metadata are always written, apart from attributes managed by OMX.
- Arguments:
path (
stroros.PathLike): Destination OMX file.- mode (
str, Optional): Use"x"or"w-"to create a new file,
"w"to replace or create a file,"r+"to update an existing file, or"a"to update or create a file. Defaults to"x".- subset (sequence of
strordict, Optional): Matrix names or attribute queries to save. Defaults to all matrices. If nothing matches, only the zone mapping and file metadata are written.
- kwargs: Additional keyword arguments passed to
openmatrix.open_file.
- mode (
>>> from pathlib import Path >>> from tempfile import TemporaryDirectory >>> demand = from_dict({"car": [[0, 12], [10, 0]]}, index=[101, 205]) >>> demand.matrix_metadata("car")["mode"] = "car" >>> with TemporaryDirectory() as directory: ... path = Path(directory) / "demand.omx" ... demand.save_as_omx(path, subset=[{"mode": "car"}]) ... loaded = from_file(path) >>> loaded == demand True
- setdefault(key: str, default: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str] | bsr_array | coo_array | csc_array | csr_array | dok_array | lil_array | None = None) _ArrayT#
Return a named matrix, adding it from
defaultif it is missing.An existing matrix is returned unchanged. If the name is missing,
defaultmust contain a full square matrix.Nonecannot be used to create a matrix.As with a normal lookup, the result is a view for a dense in-memory matrix, the stored array for a sparse matrix and a copy for a store.
- Arguments:
key (
str): Matrix name to look up or insert.- default (array-like, Optional): Full square matrix to insert
if the name is missing. Defaults to
None, which is only valid when the matrix already exists.
>>> demand = AequilibraeMatrix(index=[101]) >>> demand.setdefault("car", [[12]]).tolist() [[12]] >>> demand.setdefault("car", [[99]]).tolist() [[12]]
- subset(subset: Sequence[str | dict[str, Any]]) Self[source]#
Copy selected sparse matrices, their zone index and metadata.
Select by matrix name or attribute query. Each matching matrix is included once. Changes to the result do not change the original. Sparse formats and dtypes are kept.
- totals() dict[str, Any]#
Return each named matrix’s total.
- update([E, ]**F) None. Update D from mapping/iterable E and F.#
If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v
- values() an object providing a view on D's values#
- property imat: _MatrixIndexer[_ArrayT]#
Read or change matrix values using zero-based positions.
Use
imat[name]for a whole matrix,imat[name, row]for rows, orimat[name, row, column]to select both rows and columns. Slices exclude the stop position.Zone IDs are converted to positions before indexing. In-memory, dense matrices use NumPy selections while sparse matrices use SciPy selections. Stored dense matrices support the selections allowed by h5py. Stored sparse matrices only support whole-matrix access. Writing to a selection keeps the matrix’s dtype. Values are broadcast and converted according to the array or dataset’s rules.
>>> demand = from_dict({"car": [[0, 12], [10, 0]]}, index=[101, 205]) >>> demand.imat["car", :, 1].tolist() [12, 0] >>> demand.imat["car", 0, :] = [1, 2] >>> demand.imat["car", :1].tolist() [[1, 2]]
- property index: ndarray#
Zone IDs in row and column order, returned as a read-only uint64 array.
IDs must be unique integers between
0and2**64 - 1. To relabel zones, assign a new index of the same length. This does not move any matrix values.Changing a store’s index requires write access. The mapping keeps its existing dtype and attributes.
>>> demand = from_dict({"car": [[0, 12], [10, 0]]}, index=[101, 205]) >>> demand.index.tolist() [101, 205] >>> demand.index.flags.writeable False >>> demand.index = [1001, 1002] >>> int(demand.mat["car", 1001, 1002]) 12
- property index_name: str#
Name of the zone mapping used when reading and writing OMX files.
>>> AequilibraeMatrix(index=[101, 205]).index_name 'main_index' >>> AequilibraeMatrix(index=[101, 205], index_name="zones").index_name 'zones'
- property mat: _MatrixIndexer[_ArrayT]#
Read or change matrix values using zone IDs.
Use
mat[name]for a whole matrix,mat[name, row]for rows, ormat[name, row, column]to select both rows and columns. Slices follow the stored zone order and include the stop ID. An unknown zone ID raisesKeyError.Zone IDs are converted to positions before indexing. In-memory, dense matrices use NumPy selections while sparse matrices use SciPy selections. Stored dense matrices support the selections allowed by h5py. Stored sparse matrices only support whole-matrix access. Writing to a selection keeps the matrix’s dtype. Values are broadcast and converted according to the array or dataset’s rules.
>>> demand = from_dict({"car": [[0, 12], [10, 0]]}, index=[101, 205]) >>> demand.mat["car", 101:205].tolist() [[0, 12], [10, 0]] >>> demand.mat["car", 101, 205] = 42 >>> int(demand.mat["car", 101, 205]) 42
- property metadata: MutableMapping[str, Any]#
File-level attributes that can be read and updated by name.
These are stored in a dictionary for in-memory matrices and in h5py attributes for stores. Assign a new value to an attribute to update it.
Attributes managed by OMX are visible on a store but are ignored when loading, copying, saving or comparing file metadata.
>>> demand = AequilibraeMatrix(index=[101, 205]) >>> demand.metadata["description"] = "Morning demand" >>> demand.metadata["description"] 'Morning demand'
- property shape: tuple[int, int]#
Shape of each matrix, determined by the number of zone IDs.
>>> demand = AequilibraeMatrix(index=[101, 205, 309]) >>> demand.shape (3, 3) >>> len(demand) 0
- class aequilibrae.matrix.MatrixStore(path: str | PathLike, index: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str] | None = None, index_name: str = 'main_index', mode: Literal['r', 'w', 'a', 'r+', 'w-', 'x'] = 'r', **kwargs)[source]#
A dictionary-like collection of square matrices backed by an OMX file.
Open an existing file by choosing a zone mapping with
index_name. To create a file or relabel its zones, supplyindexand a writable mode. Stores are read-only by default.Each read loads values from disk into a new array. Changing that array does not update the file. To write changes, assign a whole matrix by name or use
matorimatto update part of a dense matrix.Sparse matrices use the CSR extension in
/sparseand share the selected zone mapping with dense matrices in/data. Each sparse read returns an independent CSR array. Partial reads and writes throughmatorimatare not supported, even for selections covering all values. Whole-matrix access throughmat[name]andimat[name]is supported.Use
subset()to copy selected matrices of one type into memory for calculations. Keep the store open while using it. Using awithblock is recommended. Delete a matrix before changing its storage type.>>> from pathlib import Path >>> from tempfile import TemporaryDirectory >>> with TemporaryDirectory() as directory: ... path = Path(directory) / "demand.omx" ... with MatrixStore(path, index=[101, 205], mode="x") as store: ... store["car"] = [[0, 12], [10, 0]] ... values = store["car"] ... values[0, 1] = 99 ... print(int(store.imat["car", 0, 1])) ... store.mat["car", 101, 205] = 42 ... working = store.subset(["car"]) 12 >>> working["car"].tolist() [[0, 42], [10, 0]]
- clear() None#
Remove all named matrices and their attributes.
The zone index and file-level metadata are kept.
>>> demand = from_dict({"car": [[0]]}, index=[101]) >>> demand.metadata["year"] = 2030 >>> demand.clear() >>> list(demand), demand.index.tolist(), demand.metadata["year"] ([], [101], 2030)
- close() None[source]#
Close the OMX file.
This is called automatically when leaving a
withblock.>>> from pathlib import Path >>> from tempfile import TemporaryDirectory >>> with TemporaryDirectory() as directory: ... store = MatrixStore(Path(directory) / "demand.omx", index=[101], mode="x") ... store["car"] = [[12]] ... working = store.subset(["car"]) ... store.close() >>> working["car"].tolist() [[12]]
- get(k[, d]) D[k] if k in D, else d. d defaults to None.#
- items() a set-like object providing a view on D's items#
- keys() a set-like object providing a view on D's keys#
- matrix_metadata(name: str) AttributeManager[source]#
Return h5py attributes for an existing matrix dataset or sparse group.
Use a writable store to change attributes, and assign each new value as a whole. Replacing a matrix with a different dtype creates a new dataset. Replacing a sparse matrix creates a new storage group. Call this method again afterwards to get its attributes. The sparse storage attribute
FORMATis ignored when writing.- Arguments:
name (
str): Name of an existing matrix dataset or sparse group.
>>> from pathlib import Path >>> from tempfile import TemporaryDirectory >>> with TemporaryDirectory() as directory: ... with MatrixStore(Path(directory) / "demand.omx", index=[101], mode="x") as store: ... store["car"] = [[12]] ... store.matrix_metadata("car")["mode"] = "car" ... print(store.matrix_metadata("car")["mode"]) car
- pop(k[, d]) v, remove specified key and return the corresponding value.#
If key is not found, d is returned if given, otherwise KeyError is raised.
- popitem() (k, v), remove and return some (key, value) pair#
as a 2-tuple; but raise KeyError if D is empty.
- save_as_omx(path: str | PathLike, mode: Literal['w', 'a', 'r+', 'w-', 'x'] = 'x', *, subset: Sequence[str | dict[str, Any]] | None = None, **kwargs) None#
Save named matrices, their attributes, the zone index and file metadata to OMX.
By default, this saves all matrices to a new file and raises an error if the file already exists. Pass
subsetto select matrices by name or by their attributes. A query matches matrices with all the given attributes. Each matrix is saved once, even if it matches several entries.When updating a file, matrices outside the subset are left unchanged. Attributes provided here replace matching attributes in the file. Other attributes are kept. The zone mapping and file metadata are always written, apart from attributes managed by OMX.
- Arguments:
path (
stroros.PathLike): Destination OMX file.- mode (
str, Optional): Use"x"or"w-"to create a new file,
"w"to replace or create a file,"r+"to update an existing file, or"a"to update or create a file. Defaults to"x".- subset (sequence of
strordict, Optional): Matrix names or attribute queries to save. Defaults to all matrices. If nothing matches, only the zone mapping and file metadata are written.
- kwargs: Additional keyword arguments passed to
openmatrix.open_file.
- mode (
>>> from pathlib import Path >>> from tempfile import TemporaryDirectory >>> demand = from_dict({"car": [[0, 12], [10, 0]]}, index=[101, 205]) >>> demand.matrix_metadata("car")["mode"] = "car" >>> with TemporaryDirectory() as directory: ... path = Path(directory) / "demand.omx" ... demand.save_as_omx(path, subset=[{"mode": "car"}]) ... loaded = from_file(path) >>> loaded == demand True
- setdefault(key: str, default: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str] | bsr_array | coo_array | csc_array | csr_array | dok_array | lil_array | None = None) _ArrayT#
Return a named matrix, adding it from
defaultif it is missing.An existing matrix is returned unchanged. If the name is missing,
defaultmust contain a full square matrix.Nonecannot be used to create a matrix.As with a normal lookup, the result is a view for a dense in-memory matrix, the stored array for a sparse matrix and a copy for a store.
- Arguments:
key (
str): Matrix name to look up or insert.- default (array-like, Optional): Full square matrix to insert
if the name is missing. Defaults to
None, which is only valid when the matrix already exists.
>>> demand = AequilibraeMatrix(index=[101]) >>> demand.setdefault("car", [[12]]).tolist() [[12]] >>> demand.setdefault("car", [[99]]).tolist() [[12]]
- subset(subset: Sequence[str | dict[str, Any]], *, sparse: bool | None = None) AequilibraeMatrix | AequilibraeSparseMatrix[source]#
Copy selected matrices from the file into memory.
Select matrices by name or by their attributes. A query matches matrices with all the given attributes. Each matrix is included once, even if it matches more than one entry.
The zone index and metadata are also copied. You can keep using the result after the store closes, and changes to it do not affect the file. All selected matrices must have the same storage type.
- Arguments:
- subset (sequence of
strordict): Matrix names or attribute queries to load.
- sparse (
bool, Optional): Expected storage type. Defaults to
None, which infers the type from the first selected matrix.
- subset (sequence of
>>> from pathlib import Path >>> from tempfile import TemporaryDirectory >>> with TemporaryDirectory() as directory: ... with MatrixStore(Path(directory) / "demand.omx", index=[101], mode="x") as store: ... store["car"] = [[12]] ... store["bus"] = [[2]] ... store.matrix_metadata("car")["mode"] = "car" ... working = store.subset([{"mode": "car"}]) >>> list(working), working["car"].tolist() (['car'], [[12]])
- totals() dict[str, Any]#
Return each named matrix’s total.
- update([E, ]**F) None. Update D from mapping/iterable E and F.#
If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v
- values() an object providing a view on D's values#
- property imat: _MatrixIndexer[_ArrayT]#
Read or change matrix values using zero-based positions.
Use
imat[name]for a whole matrix,imat[name, row]for rows, orimat[name, row, column]to select both rows and columns. Slices exclude the stop position.Zone IDs are converted to positions before indexing. In-memory, dense matrices use NumPy selections while sparse matrices use SciPy selections. Stored dense matrices support the selections allowed by h5py. Stored sparse matrices only support whole-matrix access. Writing to a selection keeps the matrix’s dtype. Values are broadcast and converted according to the array or dataset’s rules.
>>> demand = from_dict({"car": [[0, 12], [10, 0]]}, index=[101, 205]) >>> demand.imat["car", :, 1].tolist() [12, 0] >>> demand.imat["car", 0, :] = [1, 2] >>> demand.imat["car", :1].tolist() [[1, 2]]
- property index: ndarray#
Zone IDs in row and column order, returned as a read-only uint64 array.
IDs must be unique integers between
0and2**64 - 1. To relabel zones, assign a new index of the same length. This does not move any matrix values.Changing a store’s index requires write access. The mapping keeps its existing dtype and attributes.
>>> demand = from_dict({"car": [[0, 12], [10, 0]]}, index=[101, 205]) >>> demand.index.tolist() [101, 205] >>> demand.index.flags.writeable False >>> demand.index = [1001, 1002] >>> int(demand.mat["car", 1001, 1002]) 12
- property index_name: str#
Name of the zone mapping used when reading and writing OMX files.
>>> AequilibraeMatrix(index=[101, 205]).index_name 'main_index' >>> AequilibraeMatrix(index=[101, 205], index_name="zones").index_name 'zones'
- property mat: _MatrixIndexer[_ArrayT]#
Read or change matrix values using zone IDs.
Use
mat[name]for a whole matrix,mat[name, row]for rows, ormat[name, row, column]to select both rows and columns. Slices follow the stored zone order and include the stop ID. An unknown zone ID raisesKeyError.Zone IDs are converted to positions before indexing. In-memory, dense matrices use NumPy selections while sparse matrices use SciPy selections. Stored dense matrices support the selections allowed by h5py. Stored sparse matrices only support whole-matrix access. Writing to a selection keeps the matrix’s dtype. Values are broadcast and converted according to the array or dataset’s rules.
>>> demand = from_dict({"car": [[0, 12], [10, 0]]}, index=[101, 205]) >>> demand.mat["car", 101:205].tolist() [[0, 12], [10, 0]] >>> demand.mat["car", 101, 205] = 42 >>> int(demand.mat["car", 101, 205]) 42
- property metadata: MutableMapping[str, Any]#
File-level attributes that can be read and updated by name.
These are stored in a dictionary for in-memory matrices and in h5py attributes for stores. Assign a new value to an attribute to update it.
Attributes managed by OMX are visible on a store but are ignored when loading, copying, saving or comparing file metadata.
>>> demand = AequilibraeMatrix(index=[101, 205]) >>> demand.metadata["description"] = "Morning demand" >>> demand.metadata["description"] 'Morning demand'
- property omx: File#
Underlying open OMX file for advanced operations.
Changes to matrix storage groups through this handle are visible to the store without reopening it.
>>> from pathlib import Path >>> from tempfile import TemporaryDirectory >>> with TemporaryDirectory() as directory: ... with MatrixStore(Path(directory) / "demand.omx", index=[101], mode="x") as store: ... store["car"] = [[12]] ... print(store.omx.list_matrices()) ['car']
- property shape: tuple[int, int]#
Shape of each matrix, determined by the number of zone IDs.
>>> demand = AequilibraeMatrix(index=[101, 205, 309]) >>> demand.shape (3, 3) >>> len(demand) 0
- aequilibrae.matrix.from_df(df: DataFrame, row: str, col: str, subset: Sequence[str] | None = None, *, index: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str] | None = None, index_name: str = 'main_index', fill_value: float = 0, dtype: type[Any] | dtype[Any] | _HasDType[dtype[Any]] | _HasNumPyDType[dtype[Any]] | tuple[Any, Any] | list[Any] | _DTypeDict | str = float, sparse: Literal[False] = False) AequilibraeMatrix[source]#
- aequilibrae.matrix.from_df(df: DataFrame, row: str, col: str, subset: Sequence[str] | None = None, *, index: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str] | None = None, index_name: str = 'main_index', fill_value: float = 0, dtype: type[Any] | dtype[Any] | _HasDType[dtype[Any]] | _HasNumPyDType[dtype[Any]] | tuple[Any, Any] | list[Any] | _DTypeDict | str = float, sparse: Literal[True]) AequilibraeSparseMatrix
Create dense or sparse in-memory matrices from an origin-destination DataFrame.
Choose the origin and destination columns with
rowandcol. All other columns become a named matrix, or you can choose columns withsubset. Values for repeated origin-destination pairs are summed. Missing pairs are filled withfill_value.Pass
indexto set the zone order and include zones with no trips. If omitted, the index contains the sorted unique origin and destination IDs. All IDs must be valid integer zone IDs and appear in the index. Passsparse=Trueto construct CSR arrays directly from the records without allocating dense matrices. Sparse matrices requirefill_value=0.- Arguments:
- df (
pandas.DataFrame): Origin-destination records with zone IDs and matrix value columns.
row (
str): Column containing origin zone IDs.col (
str): Column containing destination zone IDs.- subset (sequence of
str, Optional): Value columns to convert to named matrices. Defaults to all columns except
rowandcol.- index (array-like, Optional): Unique integer zone IDs shared by
rows and columns. Must include all origin and destination IDs. Defaults to their sorted union.
- index_name (
str, Optional): Zone mapping name. Defaults to "main_index".- fill_value (
float, Optional): Value for pairs without records. Defaults to
0.- dtype (NumPy dtype-like, Optional): Dtype used for all output
matrices. Defaults to
float.- sparse (
bool, Optional): Return an AequilibraeSparseMatrixinstead of anAequilibraeMatrix. Defaults toFalse. Requiresfill_value=0.
- df (
>>> trips = pd.DataFrame({"origin": [101, 101, 309], "destination": [205, 205, 101], "car": [2, 3, 7]}) >>> demand = from_df( ... trips, row="origin", col="destination", subset=["car"], ... index=[101, 205, 309], index_name="zones", fill_value=-1, ... ) >>> demand["car"].tolist() [[-1.0, 5.0, -1.0], [-1.0, -1.0, -1.0], [7.0, -1.0, -1.0]] >>> from_df(trips, row="origin", col="destination").index.tolist() [101, 205, 309]
- aequilibrae.matrix.from_dict(data: Mapping[str, _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str]], index: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str], *, index_name: str = 'main_index') AequilibraeMatrix[source]#
- aequilibrae.matrix.from_dict(data: Mapping[str, bsr_array | coo_array | csc_array | csr_array | dok_array | lil_array], index: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str], *, index_name: str = 'main_index') AequilibraeSparseMatrix
Create named square matrices from a mapping of names to array-like values.
The result is an in-memory
AequilibraeMatrixorAequilibraeSparseMatrix, inferred from the first value. All values must have the same storage type. Mixed dense and sparse inputs will raise aValueError. The mapping must contain at least one matrix.Arrays are copied with their original dtypes. Each sparse array keeps its format. Its shape must match the number of zones in
index, which sets the row and column order.- Arguments:
- data (mapping of
strto array-like or SciPy sparse arrays): Non-empty collection of named square matrices matching the index length. Values must all be dense or all be sparse, with integer, float, boolean or complex dtypes.
- index (array-like): One-dimensional sequence of unique integer zone
IDs from
0to2**64 - 1in row and column order.- index_name (
str, Optional): Zone mapping name. Defaults to "main_index".
- data (mapping of
>>> demand = from_dict( ... {"car": [[0, 12], [10, 0]], "bus": [[0, 2], [2, 0]]}, ... index=[101, 205], index_name="zones", ... ) >>> demand["car"].tolist() [[0, 12], [10, 0]] >>> from scipy.sparse import csr_array >>> demand = from_dict( ... {"car": csr_array([[0, 12], [10, 0]])}, ... index=[101, 205], index_name="zones", ... ) >>> demand["car"].toarray().tolist() [[0, 12], [10, 0]] >>> demand.index.tolist() [101, 205]
- aequilibrae.matrix.from_file(path: str | PathLike, mode: None = None, *, index_name: str | None = None, subset: Sequence[str | dict[str, Any]] | None = None, store: Literal[False] = False, sparse: Literal[False]) AequilibraeMatrix[source]#
- aequilibrae.matrix.from_file(path: str | PathLike, mode: Literal['r', 'r+'] | None = None, *, index_name: str | None = None, subset: None = None, store: Literal[True], sparse: bool | None = None) MatrixStore
- aequilibrae.matrix.from_file(path: str | PathLike, mode: None = None, *, index_name: str | None = None, subset: Sequence[str | dict[str, Any]] | None = None, store: Literal[False] = False, sparse: bool | None = None) AequilibraeMatrix | AequilibraeSparseMatrix
Load an OMX file as an in-memory matrix or an on-disk store.
By default, this copies all matrices and metadata into an in-memory
AequilibraeMatrixorAequilibraeSparseMatrix, inferred from the first selected matrix. Passsubsetto load only the matrices you need. Mixed storage types raiseValueError.Use
store=Trueto work with the file through aMatrixStoreinstead. The store opens read-only unless you passmode="r+". Stores do not acceptsubset. Use theirsubset()method to copy selected matrices into memory.Pass
sparse=TrueorFalseto require sparse or dense matrices, respectively. This validates the selection without filtering or converting matrices. An empty selection returns an AequilibraeMatrix. The option is ignored whenstore=True; stores expose both storage types.If the file has only one zone mapping, it is selected automatically. If there are several,
main_indexis used when available. Otherwise, choose a mapping withindex_name.- Arguments:
path (
stroros.PathLike): Existing OMX file to open.- mode (
str, Optional): Store access mode,"r"or "r+". Defaults toNone, which opens stores read-only. Must be omitted for in-memory loading.- index_name (
str, Optional): Zone mapping to read. Defaults to automatic selection of the only mapping, or
"main_index"when several exist. Required if neither choice is available.- subset (sequence of
strordict, Optional): Matrix names or attribute queries to load into memory. Defaults to all matrices. Cannot be combined with
store=True.- store (
bool, Optional): Return an open MatrixStoreinstead of an in-memoryAequilibraeMatrix. Defaults toFalse.- sparse (
bool, Optional): Expected in-memory storage type. Defaults to
None, which infers it from the first selected matrix. Ignored whenstore=True.
- mode (
>>> from pathlib import Path >>> from tempfile import TemporaryDirectory >>> demand = from_dict({"car": [[0, 12], [10, 0]]}, index=[101, 205], index_name="zones") >>> with TemporaryDirectory() as directory: ... path = Path(directory) / "demand.omx" ... demand.save_as_omx(path) ... loaded = from_file(path, subset=["car"]) ... with from_file(path, store=True, mode="r+") as store: ... store.mat["car", 101, 205] = 42 ... working = store.subset(["car"]) >>> loaded["car"].tolist() [[0, 12], [10, 0]] >>> working["car"].tolist() [[0, 42], [10, 0]]