def test_reduce_node_quantity_custom_ex(): nodes_len = 2 column_names = ["№", "neighbors", "S"] data = [ ["1", "2,3,4", 2], ["2", "1,3,5", 4], ["3", "1,2,4,5", 6], ["4", "1,3,5", 8], ["5", "2,3,4,13,16", 10], ["6", "7,8,9", 1.01], ["7", "6,8,10", 1.02], ["8", "6,7,9,11", 1.03], ["9", "6,8,12", 1.04], ["10", "7,11,13", 1.05], ["11", "8,10,12,14", 1.06], ["12", "9,11,15", 1.07], ["13", "5,10,14,17", 1.08], ["14", "11,13,15", 1.09], ["15", "12,14", 1.10], ["16", "5,17", 50], ["17", "13,16", 50], ] dataframe = pd.DataFrame(data=data, columns=column_names) solver = Solver(data=dataframe, given_sum=20, number_of_clusters=4) solver._reduce_nodes_quantity(graph=solver.crop_map.graph, nodes_quantity=nodes_len) assert len( solver.crop_map.graph) == nodes_len, f"{len(solver.crop_map.graph)=}" test_cluster_connected = Cluster( serial_num=0, nodes_belong=[x for x in solver.crop_map.graph.values()]) assert solver._check_cluster_for_connectivity( graph=solver.crop_map.graph, cluster=test_cluster_connected)
def test_first_node_absorb_second(): column_names = ["№", "neighbors", "S"] data = [ ["1", "2,3", 1], ["2", "1", 2], ["3", "2", 5], ["4", "1", 3], ] dataframe = pd.DataFrame(data=data, columns=column_names) solver = Solver(data=dataframe, given_sum=20, number_of_clusters=4) first = "1" second = "2" solver._first_node_absorb_second(first=first, second=second, graph=solver.crop_map.graph) assert {x for x in solver.crop_map.graph.keys()} == { "1", "3", "4", }, f"{solver.crop_map.graph.keys()=}" adj_lists = [x.adjacent_list for x in solver.crop_map.graph.values()] for x in adj_lists: assert second not in x, f"{second=}, {x=}" assert ("1" in solver.crop_map.graph["3"].adjacent_list ), f'{solver.crop_map.graph["3"].adjacent_list=}' assert ("2" not in solver.crop_map.graph["1"].adjacent_list ), f'{solver.crop_map.graph["3"].adjacent_list=}'
def test_check_cluster_for_connectivity_basic_1(): column_names = ["№", "neighbors", "S"] data = [ ["1", "2,3", 1], ["2", "1,3", 2], ["3", "1,2, 10", 5], ["4", "5", 3], ["5", "4", 3], ] dataframe = pd.DataFrame(data=data, columns=column_names) solver = Solver(data=dataframe, given_sum=20, number_of_clusters=4) test_cluster_not_connected = Cluster( serial_num=0, nodes_belong=[ solver.crop_map.graph[x] for x in ["1", "2", "3", "4", "5"] ], ) assert not solver._check_cluster_for_connectivity( graph=solver.crop_map.graph, cluster=test_cluster_not_connected) test_cluster_connected = Cluster( serial_num=0, nodes_belong=[solver.crop_map.graph[x] for x in ["1", "2", "3"]], ) assert solver._check_cluster_for_connectivity( graph=solver.crop_map.graph, cluster=test_cluster_connected)
def test_find_pair_with_min_square(): column_names = ["№", "neighbors", "S"] data = [ ["1", "3", 1], ["2", "4", 2], ["3", "1", 5], ["4", "2", 3], ] dataframe = pd.DataFrame(data=data, columns=column_names) solver = Solver(data=dataframe, given_sum=20, number_of_clusters=4) res = Solver._find_pair_with_min_square(solver.crop_map.graph) assert set(res) == {"2", "4"}, f"{res=}"
def test_solve(): data = pd.read_excel(datapath) solver = Solver( data=data, given_sum=11, number_of_clusters=4, ) start = time.time() times, leaders, _ = solver.solve_new(cut_bound_max=3) print("time ", time.time() - start) print([(x.name, x.square) for x in leaders]) assert leaders, f"{leaders=}"
def test_reduce_node_quantity_basic(): """ придумать реальный кейс для проверки на связность :return: """ global data nodes_len = 20 data = pd.read_excel(datapath) solver = Solver(data=data, given_sum=20, number_of_clusters=4) solver._reduce_nodes_quantity(graph=solver.crop_map.graph, nodes_quantity=nodes_len) assert len( solver.crop_map.graph) == nodes_len, f"{len(solver.crop_map.graph)=}" test_cluster_connected = Cluster( serial_num=0, nodes_belong=[x for x in solver.crop_map.graph.values()]) assert solver._check_cluster_for_connectivity( graph=solver.crop_map.graph, cluster=test_cluster_connected)
def solve(): """ Скрипт для дополнения справочника Если указанные границы уже были проанализирваны, справочник останется без изменений Опции: -b граница отсечения -d количество точек -p """ datapath = Path(__file__).resolve().parents[1] / "data" argv = sys.argv[1:] try: opts, args = getopt.getopt(sys.argv[1:], "b:d:f:", ["border=", "dots=", "file="]) border = None dots = None for opt, arg in opts: if opt == "-b" or opt == "--border": border = arg elif opt == "-d" or opt == "--dots": dots = arg elif opt == "-f" or opt == "--file": datapath = datapath / arg # TODO как ошибки обрабатываем? if not border.isdigit(): raise if not dots.isdigit(): raise border = int(border) dots = int(dots) data = pd.read_excel(datapath) graph_constructor.construct_graph(data) print(data) # err_adj_list = validate(data) # TODO выбрасываем все это, так как учимся самостоятельно определять центры полей по координатам # и строить граф габриэля по центрам # if err_adj_list: # ic(err_adj_list) # return # # TODO научиться исправлять ошибку отсутствия антипараллельных ребер самостоятельно # err_double_adj = validate_double_edges(data) # if err_double_adj: # ic(err_double_adj) # return # # TODO научиться исправлять ошибку наличия имени ноды в своем же списке смежности(не критично) # err_node_in_adj = validate_node_name_not_in_adj_list(data) # if err_node_in_adj: # ic(err_node_in_adj) # return solver = Solver(data=data, given_sum=dots, number_of_clusters=4) cluster_for_checking_map_full_connecticity = Cluster( serial_num=-1, nodes_belong=list(solver.crop_map.graph.values())) if not Solver._check_cluster_for_connectivity( solver.crop_map.graph, cluster_for_checking_map_full_connecticity): ic("not_connected_initial_state") return res_new = solver.solve_new(cut_bound_max=border) ic(res_new) ic([x.square for x in res_new[1]]) ic(solver.crop_map.etalon_square) new_clusters = [] for index, cluster in enumerate(res_new[1]): names = [] for x in cluster.nodes_belong: names.append(x.name) names.extend(list(name for name in x.absorbed_names)) for name in names: new_clusters.append([name, index]) names.extend(list(name for name in x.absorbed_names)) for name in names: new_clusters.append([name, index]) new_сlusters_data = pd.DataFrame(data=new_clusters) new_сlusters_data.to_excel(excel_writer="kmn_21_1_new_clusters.xlsx", index=False) except getopt.GetoptError: logging( f"Запуск: script_refbook.py -b <bank> -l <lower num bound> -h <higher num bound>" ) sys.exit(-1)