def test_set_pce(self): mat_name = AequilibraeMatrix().random_name() g = Graph() g.load_from_disk(test_graph) g.set_graph(cost_field="distance") # Creates the matrix for assignment args = { "file_name": os.path.join(gettempdir(), mat_name), "zones": g.num_zones, "matrix_names": ["cars", "trucks"], "index_names": ["my indices"], } matrix = AequilibraeMatrix() matrix.create_empty(**args) matrix.index[:] = g.centroids[:] matrix.cars.fill(1.1) matrix.trucks.fill(2.2) matrix.computational_view() tc = TrafficClass(graph=g, matrix=matrix) self.assertIsInstance(tc.results, AssignmentResults, 'Results have the wrong type') self.assertIsInstance(tc._aon_results, AssignmentResults, 'Results have the wrong type') with self.assertRaises(ValueError): tc.set_pce('not a number') tc.set_pce(1) tc.set_pce(3.9)
def test_save(self): a = AequilibraeMatrix() a.load(self.sf_skims) a.computational_view(['distance']) new_mat = np.random.rand(a.zones, a.zones) a.matrix_view *= new_mat res = a.matrix_view.sum() a.save('new_name_for_matrix') self.assertEqual(res, a.matrix_view.sum(), 'Saved wrong result') a.save(['new_name_for_matrix2']) self.assertEqual(a.view_names[0], 'new_name_for_matrix2', 'Did not update computational view') self.assertEqual(len(a.view_names), 1, 'computational view with the wrong number of matrices') a.computational_view(['distance', 'new_name_for_matrix']) with self.assertRaises(ValueError): a.save(['just_one_name']) a.save(['one_name', 'two_names']) with self.assertRaises(ValueError): a.save('distance') b = AequilibraeMatrix() b.load(self.name_test) b.computational_view("seed") b.save() b.computational_view(["mat", "seed", "dist"]) b.save()
def __redim(self): self.compact_link_loads = np.zeros( (self.compact_links + 1, self.classes["number"]), self.__float_type) self.compact_total_link_loads = np.zeros(self.compact_links, self.__float_type) self.link_loads = np.zeros((self.links, self.classes["number"]), self.__float_type) self.total_link_loads = np.zeros(self.links, self.__float_type) self.no_path = np.zeros((self.zones, self.zones), dtype=self.__integer_type) if self.num_skims > 0: self.skims = AequilibraeMatrix() self.skims.create_empty(file_name=self.skims.random_name(), zones=self.zones, matrix_names=self.skim_names) self.skims.index[:] = self.centroids[:] self.skims.computational_view() if len(self.skims.matrix_view.shape[:]) == 2: self.skims.matrix_view = self.skims.matrix_view.reshape( (self.zones, self.zones, 1)) else: self.skims = AequilibraeMatrix() self.skims.matrix_view = np.array((1, 1, 1)) self.reset()
def test_copy_from_omx_long_name(self): temp_file = AequilibraeMatrix().random_name() a = AequilibraeMatrix() with self.assertRaises(ValueError): a.create_from_omx(temp_file, omx_example, robust=False)
def test_save(self): a = AequilibraeMatrix() a.load(self.sf_skims) a.computational_view(["distance"]) new_mat = np.random.rand(a.zones, a.zones) a.matrix_view *= new_mat res = a.matrix_view.sum() a.save("new_name_for_matrix") self.assertEqual(res, a.matrix_view.sum(), "Saved wrong result") a.save(["new_name_for_matrix2"]) self.assertEqual(a.view_names[0], "new_name_for_matrix2", "Did not update computational view") self.assertEqual(len(a.view_names), 1, "computational view with the wrong number of matrices") a.computational_view(["distance", "new_name_for_matrix"]) with self.assertRaises(ValueError): a.save(["just_one_name"]) a.save(["one_name", "two_names"]) with self.assertRaises(ValueError): a.save("distance") b = AequilibraeMatrix() b.load(self.name_test) b.computational_view("seed") b.save() b.computational_view(["mat", "seed", "dist"]) b.save()
def test_load(self): self.new_matrix = AequilibraeMatrix() # Cannot load OMX file with no indices with self.assertRaises(LookupError): self.new_matrix.load(no_index_omx) self.new_matrix = AequilibraeMatrix() self.new_matrix.load(name_test)
def new_record(self, name: str, file_name: str, matrix=AequilibraeMatrix()) -> MatrixRecord: """Creates a new record for a matrix in disk, but does not save it If the matrix file is not already on disk, it will fail Args: *name* (:obj:`str`): Name of the matrix *file_name* (:obj:`str`): Name of the file on disk Return: *matrix_record* (:obj:`MatrixRecord`): A matrix record that can be manipulated in memory before saving """ if name in self.__items: raise ValueError( f"There is already a matrix of name ({name}). It must be unique." ) for mat in self.__items.values(): if mat.file_name == file_name: raise ValueError( f"There is already a matrix record for file name ({file_name}). It must be unique." ) if matrix.cores > 0: if isfile(join(self.fldr, file_name)): raise FileExistsError( f"{file_name} already exists. Choose a different name or matrix format" ) mat_format = file_name.split(".")[-1].lower() if mat_format not in ["omx", "aem"]: raise ValueError( "Matrix needs to be either OMX or native AequilibraE") matrix.export(join(self.fldr, file_name)) cores = matrix.cores else: if not isfile(join(self.fldr, file_name)): raise FileExistsError( f"{file_name} does not exist. Cannot create this matrix record" ) mat = AequilibraeMatrix() mat.load(join(self.fldr, file_name)) cores = mat.cores mat.close() del mat tp = {key: None for key in self.__fields} tp["name"] = name tp["file_name"] = file_name tp["cores"] = cores mr = MatrixRecord(tp) mr.save() self.__items[name.lower()] = mr logger.warning("Matrix Record has been saved to the database") return mr
def __init__(self, **kwargs): """ Instantiates the Ipf problem Args: matrix (:obj:`AequilibraeMatrix`): Seed Matrix rows (:obj:`AequilibraeData`): Vector object with data for row totals row_field (:obj:`str`): Field name that contains the data for the row totals columns (:obj:`AequilibraeData`): Vector object with data for column totals column_field (:obj:`str`): Field name that contains the data for the column totals parameters (:obj:`str`, optional): Convergence parameters. Defaults to those in the parameter file nan_as_zero (:obj:`bool`, optional): If Nan values should be treated as zero. Defaults to True Results: output (:obj:`AequilibraeMatrix`): Result Matrix report (:obj:`list`): Iteration and convergence report error (:obj:`str`): Error description """ self.parameters = kwargs.get("parameters", self.__get_parameters("ipf")) # Seed matrix self.matrix = kwargs.get("matrix", None) # NaN as zero self.nan_as_zero = kwargs.get("nan_as_zero", True) # row vector self.rows = kwargs.get("rows", None) self.row_field = kwargs.get("row_field", None) self.output_name = kwargs.get("output", AequilibraeMatrix().random_name()) # Column vector self.columns = kwargs.get("columns", None) self.column_field = kwargs.get("column_field", None) self.output = AequilibraeMatrix() self.error = None self.__required_parameters = [ "convergence level", "max iterations", "balancing tolerance" ] self.error_free = True self.report = [" ##### IPF computation ##### ", ""] self.gap = None self.procedure_date = '' self.procedure_id = ''
def test_copy_omx_wrong_content(self): # Check if we get a result if we try to copy non-existing cores temp_file = AequilibraeMatrix().random_name() a = AequilibraeMatrix() with self.assertRaises(ValueError): a.create_from_omx(temp_file, omx_example, cores=["m1", "m2", "m3", "m4"]) with self.assertRaises(ValueError): a.create_from_omx(temp_file, omx_example, mappings=["wrong index"]) del a
def __init__(self, parentThread, **kwargs): WorkerThread.__init__(self, parentThread) self.matrix = AequilibraeMatrix() self.matrices = kwargs.get('matrices') self.sparse = kwargs.get('sparse', False) self.file_name = kwargs.get('file_name', AequilibraeMatrix().random_name()) self.num_matrices = len(self.matrices.keys()) self.matrix_hash = {} self.titles = [] self.report = []
def test_get_matrix(self): self.test_load() a = AequilibraeMatrix() a.load(siouxfalls_skims) with self.assertRaises(AttributeError): a.get_matrix('does not exist') q = a.get_matrix('distance') self.assertEqual(q.shape[0], 24) a = AequilibraeMatrix() a.load(name_test) print(np.array_equal(a.get_matrix("seed"), a.matrix["seed"]))
def test_get_matrix(self): a = AequilibraeMatrix() a.load(self.sf_skims) with self.assertRaises(AttributeError): a.get_matrix("does not exist") q = a.get_matrix("distance") self.assertEqual(q.shape[0], 24) a = AequilibraeMatrix() a.load(self.name_test) print(np.array_equal(a.get_matrix("seed"), a.matrix["seed"])) del a
def __setCriticalLinks(self, save=False, queries={}, crit_res_result=None): a = AequilibraeMatrix() if save: if crit_res_result is None: warnings.warn( "Critical Link analysis not set properly. Need to specify output file too" ) else: if crit_res_result[-3:].lower() != "aem": crit_res_result += ".aes" if self.nodes > 0 and self.zones > 0: if ["elements", "labels", "type"] in queries.keys(): if len(queries["labels"]) == len( queries["elements"]) == len(queries["type"]): a.create_empty(file_name=crit_res_result, zones=self.zones, matrix_names=queries["labels"]) else: raise ValueError( "Queries are inconsistent. 'Labels', 'elements' and 'type' need to have same dimensions" ) else: raise ValueError( "Queries are inconsistent. It needs to contain the following elements: 'Labels', 'elements' and 'type'" ) else: a.create_empty(file_name=a.random_name(), zones=self.zones, matrix_names=["empty", "nothing"]) a.computational_view() if len(a.matrix_view.shape[:]) == 2: a.matrix_view = a.matrix_view.reshape((self.zones, self.zones, 1)) self.critical_links = {"save": save, "queries": queries, "results": a}
def test_skimming_on_assignment(self): matrix = AequilibraeMatrix() matrix.load(os.path.join(gettempdir(), self.mat_name)) matrix.computational_view(["cars"]) res = AssignmentResults() res.prepare(self.g, matrix) self.g.set_skimming([]) self.g.set_blocked_centroid_flows(True) assig = allOrNothing(matrix, self.g, res) assig.execute() if res.skims.distance.sum() > 0: self.fail( "skimming for nothing during assignment returned something different than zero" ) self.g.set_skimming("distance") res.prepare(self.g, matrix) assig = allOrNothing(matrix, self.g, res) assig.execute() if res.skims.distance.sum() != 2914644.0: self.fail("skimming during assignment returned the wrong value") matrix.close()
def setUp(self) -> None: self.sf_skims = f"/Aequilibrae_matrix_{uuid.uuid4()}.omx" copyfile(siouxfalls_skims, self.sf_skims) temp_folder = gettempdir() self.name_test = temp_folder + f"/Aequilibrae_matrix_{uuid.uuid4()}.aem" self.copy_matrix_name = temp_folder + f"/Aequilibrae_matrix_{uuid.uuid4()}.aem" self.csv_export_name = temp_folder + f"/Aequilibrae_matrix_{uuid.uuid4()}.csv" self.omx_export_name = temp_folder + f"/Aequilibrae_matrix_{uuid.uuid4()}.omx" if self.matrix is not None: return args = { "file_name": self.name_test, "zones": zones, "matrix_names": ["mat", "seed", "dist"], "index_names": ["my indices"], } self.matrix = AequilibraeMatrix() self.matrix.create_empty(**args) self.matrix.index[:] = np.arange(self.matrix.zones) + 100 self.matrix.mat[:, :] = np.random.rand(self.matrix.zones, self.matrix.zones)[:, :] self.matrix.mat[:, :] = self.matrix.mat[:, :] * (1000 / np.sum(self.matrix.mat[:, :])) self.matrix.setName("Test matrix - " + str(random.randint(1, 10))) self.matrix.setDescription("Generated at " + datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")) self.new_matrix = self.matrix
def __init__(self): self.compact_link_loads = np.array([]) # Results for assignment on simplified graph self.compact_total_link_loads = np.array([]) # Results for all user classes summed on simplified graph self.link_loads = np.array([]) # The actual results for assignment self.total_link_loads = np.array([]) # The result of the assignment for all user classes summed self.crosswalk = np.array([]) # crosswalk between compact graph link IDs and actual link IDs self.skims = AequilibraeMatrix() # The array of skims self.no_path = None # The list os paths self.num_skims = 0 # number of skims that will be computed. Depends on the setting of the graph provided p = Parameters().parameters["system"]["cpus"] if not isinstance(p, int): p = 0 self.set_cores(p) self.classes = {"number": 1, "names": ["flow"]} self.nodes = -1 self.zones = -1 self.links = -1 self.compact_links = -1 self.compact_nodes = -1 self.__graph_id__ = None self.__float_type = None self.__integer_type = None self.lids = None self.direcs = None
def prepare_assignable_matrices(self): table = self.table_matrices_to_assign idx = self.graph.centroids mat_names = [] if table.rowCount() > 1: for row in range(table.rowCount() - 1): mat = table.cellWidget(row, 0).currentText() core = table.cellWidget(row, 1).currentText() mat_index = self.matrices[mat].index if not np.array_equal(idx, mat_index): no_zones = [item for item in mat_index if item not in idx] # We only return an error if the matrix has too many centroids if no_zones: self.error = 'Assignable matrix has centroids that do not exist in the network: {}'.format( ','.join([str(x) for x in no_zones])) return False if core in mat_names: self.error = 'Assignable matrices cannot have same names' return False mat_names.append(only_str(core)) self.matrix = AequilibraeMatrix() self.matrix.create_empty(file_name=self.matrix.random_name(), zones=idx.shape[0], matrix_names=mat_names) self.matrix.index[:] = idx[:] for row in range(table.rowCount() - 1): mat = table.cellWidget(row, 0).currentText() core = table.cellWidget(row, 1).currentText() src_mat = self.matrices[mat].matrix[core] dest_mat = self.matrix.matrix[core] rows = src_mat.shape[0] cols = src_mat.shape[1] dest_mat[:rows, :cols] = src_mat[:, :] # Inserts cols and rows that don;t exist if rows != self.matrix.zones: src_index = list(self.matrices[mat].index[:]) for i, row in enumerate(idx): if row not in src_index: dest_mat[i + 1:, :] = dest_mat[i:-1, :] dest_mat[i, :] = 0 if cols != self.matrix.zones: for j, col in enumerate(idx): if col not in src_index: dest_mat[:, j + 1:] = dest_mat[:, j:-1] dest_mat[:, j] = 0 self.matrix.computational_view() else: self.error = 'You need to have at least one matrix to assign' return False return True
def test_copy_from_omx(self): temp_file = AequilibraeMatrix().random_name() a = AequilibraeMatrix() a.create_from_omx(temp_file, omx_example) omxfile = omx.open_file(omx_example, "r") # Check if matrices values are compatible for m in ["m1", "m2", "m3"]: sm = a.matrix[m].sum() sm2 = np.array(omxfile[m]).sum() if sm != sm2: self.fail( "Matrix {} was copied with the wrong value".format(m)) if np.any(a.index[:] != np.array(list(omxfile.mapping("taz").keys()))): self.fail("Index was not created properly") a.close()
def test_execute(self): # Loads and prepares the graph car_loads = [] two_class_loads = [] for extension in ["omx", "aem"]: matrix = AequilibraeMatrix() if extension == 'omx': mat_name = os.path.join(gettempdir(), "my_matrix." + extension) else: mat_name = self.mat_name matrix.load(mat_name) matrix.computational_view(["cars"]) # Performs assignment res = AssignmentResults() res.prepare(self.g, matrix) assig = allOrNothing(matrix, self.g, res) assig.execute() car_loads.append(res.link_loads) res.save_to_disk( os.path.join(gettempdir(), "link_loads_{}.aed".format(extension))) res.save_to_disk( os.path.join(gettempdir(), "link_loads_{}.csv".format(extension))) matrix.computational_view() # Performs assignment res = AssignmentResults() res.prepare(self.g, matrix) assig = allOrNothing(matrix, self.g, res) assig.execute() two_class_loads.append(res.link_loads) res.save_to_disk( os.path.join(gettempdir(), "link_loads_2_classes_{}.aed".format(extension))) res.save_to_disk( os.path.join(gettempdir(), "link_loads_2_classes_{}.csv".format(extension))) matrix.close() load_diff = two_class_loads[0] - two_class_loads[1] if load_diff.max() > 0.0000000001 or load_diff.max() < -0.0000000001: self.fail( "Loads for two classes differ for OMX and AEM matrix types") load_diff = car_loads[0] - car_loads[1] if load_diff.max() > 0.0000000001 or load_diff.max() < -0.0000000001: self.fail( "Loads for a single class differ for OMX and AEM matrix types")
def test_calibrate_with_omx(self): imped = AequilibraeMatrix() imped.load(siouxfalls_skims) imped.computational_view(['free_flow_time']) mat = AequilibraeMatrix() mat.load(siouxfalls_demand) mat.computational_view() args = {"impedance": imped, "matrix": mat, "function": "power", "nan_to_zero": False} distributed_matrix = GravityCalibration(**args) distributed_matrix.calibrate() if distributed_matrix.gap > 0.0001: self.fail("Calibration did not converge") args = {"impedance": imped, "matrix": mat, "function": "power", "nan_to_zero": True} distributed_matrix = GravityCalibration(**args) distributed_matrix.calibrate() if distributed_matrix.gap > 0.0001: self.fail("Calibration did not converge")
def setUp(self) -> None: self.matrix = AequilibraeMatrix() self.matrix.load(siouxfalls_demand) self.matrix.computational_view() self.project = Project(siouxfalls_project) self.project.network.build_graphs() self.car_graph = self.project.network.graphs['c'] # type: Graph self.car_graph.set_graph('free_flow_time') self.car_graph.set_blocked_centroid_flows(False) self.assignment = TrafficAssignment() self.assigclass = TrafficClass(self.car_graph, self.matrix)
def setUp(self) -> None: self.mat_name = AequilibraeMatrix().random_name() self.g = Graph() self.g.load_from_disk(test_graph) self.g.set_graph(cost_field="distance") # Creates the matrix for assignment args = { "file_name": os.path.join(gettempdir(), self.mat_name), "zones": self.g.num_zones, "matrix_names": ["cars", "trucks"], "index_names": ["my indices"], } matrix = AequilibraeMatrix() matrix.create_empty(**args) matrix.index[:] = self.g.centroids[:] matrix.cars.fill(1.1) matrix.trucks.fill(2.2) # Exports matrix to OMX in order to have two matrices to work with matrix.export(os.path.join(gettempdir(), "my_matrix.omx")) matrix.close()
def load_the_matrix(self): self.error = None self.worker_thread = None if self.radio_layer_matrix.isChecked(): if self.field_from.currentIndex() < 0 or self.field_from.currentIndex() < 0 or self.field_cells.currentIndex() < 0: self.error = 'Invalid field chosen' if self.error is None: self.compressed.setVisible(False) self.progress_label.setVisible(True) self.__current_name = self.field_cells.currentText().lower().replace(' ', '_') idx1 = self.layer.dataProvider().fieldNameIndex(self.field_from.currentText()) idx2 = self.layer.dataProvider().fieldNameIndex(self.field_to.currentText()) idx3 = self.layer.dataProvider().fieldNameIndex(self.field_cells.currentText()) idx = [idx1, idx2, idx3] self.worker_thread = LoadMatrix(qgis.utils.iface.mainWindow(), type='layer', layer=self.layer, idx=idx, sparse=self.sparse) if self.radio_npy_matrix.isChecked(): file_types = ["NumPY array(*.npy)"] default_type = '.npy' box_name = 'Matrix Loader' new_name, type = GetOutputFileName(self, box_name, file_types, default_type, self.path) self.__current_name = os.path.split(new_name)[1].split('.')[0] self.worker_thread = LoadMatrix(qgis.utils.iface.mainWindow(), type='numpy', file_path=new_name) if self.radio_aeq_matrix.isChecked(): file_types = ["AequilibraE Matrix(*.aem)"] default_type = '.aem' box_name = 'AequilibraE Matrix' new_name, type = GetOutputFileName(self, box_name, file_types, default_type, self.path) if new_name is not None: self.matrix = AequilibraeMatrix() self.matrix.load(new_name) self.exit_procedure() if self.radio_omx_matrix.isChecked(): pass # Still not implemented if self.worker_thread is not None: self.run_thread() if self.error is not None: qgis.utils.iface.messageBar().pushMessage("Error:", self.error, level=1)
def test___init__(self): os.remove(name_test) if os.path.exists(name_test) else None args = {'file_name': name_test, 'zones': zones, 'matrix_names': ['mat', 'seed', 'dist'], 'index_names': ['my indices']} matrix = AequilibraeMatrix() matrix.create_empty(**args) matrix.index[:] = np.arange(matrix.zones) + 100 matrix.mat[:, :] = np.random.rand(matrix.zones, matrix.zones)[:, :] matrix.mat[:, :] = matrix.mat[:, :] * (1000 / np.sum(matrix.mat[:, :])) matrix.setName('Test matrix - ' + str(random.randint(1, 10))) matrix.setDescription('Generated at ' + datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")) matrix.close(True) del (matrix)
def test_execute(self): # Loads and prepares the graph g = Graph() g.load_from_disk(test_graph) g.set_graph(cost_field='distance', skim_fields=None) # None implies that only the cost field will be skimmed # Prepares the matrix for assignment args = { 'file_name': '/tmp/my_matrix.aem', 'zones': g.num_zones, 'matrix_names': ['cars', 'trucks'], 'index_names': ['my indices'] } matrix = AequilibraeMatrix() matrix.create_empty(**args) matrix.index[:] = g.centroids[:] matrix.cars.fill(1) matrix.trucks.fill(2) matrix.computational_view(['cars']) # Performs assignment res = AssignmentResults() res.prepare(g, matrix) assig = allOrNothing(matrix, g, res) assig.execute() res.save_to_disk('/tmp/link_loads.aed') res.save_to_disk('/tmp/link_loads.csv') matrix.computational_view() # Performs assignment res = AssignmentResults() res.prepare(g, matrix) assig = allOrNothing(matrix, g, res) assig.execute() res.save_to_disk('/tmp/link_loads_2_classes.aed') res.save_to_disk('/tmp/link_loads_2_classes.csv')
def test_execute(self): # Loads and prepares the graph g = Graph() g.load_from_disk(test_graph) g.set_graph(cost_field="distance", skim_fields=None) # None implies that only the cost field will be skimmed # Prepares the matrix for assignment args = { "file_name": os.path.join(gettempdir(), "my_matrix.aem"), "zones": g.num_zones, "matrix_names": ["cars", "trucks"], "index_names": ["my indices"], } matrix = AequilibraeMatrix() matrix.create_empty(**args) matrix.index[:] = g.centroids[:] matrix.cars.fill(1) matrix.trucks.fill(2) matrix.computational_view(["cars"]) # Performs assignment res = AssignmentResults() res.prepare(g, matrix) assig = allOrNothing(matrix, g, res) assig.execute() res.save_to_disk(os.path.join(gettempdir(), "link_loads.aed")) res.save_to_disk(os.path.join(gettempdir(), "link_loads.csv")) matrix.computational_view() # Performs assignment res = AssignmentResults() res.prepare(g, matrix) assig = allOrNothing(matrix, g, res) assig.execute() res.save_to_disk(os.path.join(gettempdir(), "link_loads_2_classes.aed")) res.save_to_disk(os.path.join(gettempdir(), "link_loads_2_classes.csv"))
def test___init__(self): os.remove(name_test) if os.path.exists(name_test) else None args = { "file_name": name_test, "zones": zones, "matrix_names": ["mat", "seed", "dist"], "index_names": ["my indices"], } matrix = AequilibraeMatrix() matrix.create_empty(**args) matrix.index[:] = np.arange(matrix.zones) + 100 matrix.mat[:, :] = np.random.rand(matrix.zones, matrix.zones)[:, :] matrix.mat[:, :] = matrix.mat[:, :] * (1000 / np.sum(matrix.mat[:, :])) matrix.setName("Test matrix - " + str(random.randint(1, 10))) matrix.setDescription( "Generated at " + datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")) matrix.close() del matrix
def test_computational_view_with_omx(self): self.new_matrix = AequilibraeMatrix() self.new_matrix.load(omx_example) arrays = ["m1", "m2"] self.new_matrix.computational_view(arrays) total_mats = np.sum(self.new_matrix.matrix_view) self.new_matrix.computational_view([arrays[0]]) total_m1 = np.sum(self.new_matrix.matrix_view) self.new_matrix.close() omx_file = omx.open_file(omx_example, "r") m1 = np.array(omx_file["m1"]).sum() m2 = np.array(omx_file["m2"]).sum() self.assertEqual(m1 + m2, total_mats) self.assertEqual(m1, total_m1) omx_file.close()
def setUp(self) -> None: if self.matrix is not None: return args = { "file_name": name_test, "zones": zones, "matrix_names": ["mat", "seed", "dist"], "index_names": ["my indices"], } self.matrix = AequilibraeMatrix() self.matrix.create_empty(**args) self.matrix.index[:] = np.arange(self.matrix.zones) + 100 self.matrix.mat[:, :] = np.random.rand(self.matrix.zones, self.matrix.zones)[:, :] self.matrix.mat[:, :] = self.matrix.mat[:, :] * ( 1000 / np.sum(self.matrix.mat[:, :])) self.matrix.setName("Test matrix - " + str(random.randint(1, 10))) self.matrix.setDescription( "Generated at " + datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")) self.new_matrix = self.matrix
def update_database(self) -> None: """Adds records to the matrices database for matrix files found on disk""" existing_files = os.listdir(self.fldr) paths_for_existing = [mat.file_name for mat in self.__items.values()] new_files = [x for x in existing_files if x not in paths_for_existing] new_files = [ x for x in new_files if os.path.splitext(x.lower())[1] in [".omx", ".aem"] ] if new_files: logger.warning( f'New matrix found on disk. Added to the database: {",".join(new_files)}' ) for fl in new_files: mat = AequilibraeMatrix() mat.load(join(self.fldr, fl)) name = None if not mat.is_omx(): name = str(mat.name).lower() if not name: name = fl.lower() name = name.replace(".", "_").replace(" ", "_") if name in self.__items: i = 0 while f"{name}_{i}" in self.__items: i += 1 name = f"{name}_{i}" rec = self.new_record(name, fl) rec.save()