You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

edit_costs.nums_sols.N.IPFP.py 4.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Wed Oct 20 11:48:02 2020
  5. @author: ljia
  6. """
  7. # This script tests the influence of the ratios between node costs and edge costs on the stability of the GED computation, where the base edit costs are [1, 1, 1, 1, 1, 1].
  8. import os
  9. import multiprocessing
  10. import pickle
  11. import logging
  12. from gklearn.ged.util import compute_geds
  13. import time
  14. import sys
  15. from group_results import group_trials
  16. def generate_graphs():
  17. from gklearn.utils.graph_synthesizer import GraphSynthesizer
  18. gsyzer = GraphSynthesizer()
  19. graphs = gsyzer.unified_graphs(num_graphs=100, num_nodes=20, num_edges=20, num_node_labels=0, num_edge_labels=0, seed=None, directed=False)
  20. return graphs
  21. def xp_compute_ged_matrix(graphs, N, num_solutions, ratio, trial):
  22. save_file_suffix = '.' + str(N) + '.num_sols_' + str(num_solutions) + '.ratio_' + "{:.2f}".format(ratio) + '.trial_' + str(trial)
  23. # Return if the file exists.
  24. if os.path.isfile(save_dir + 'ged_matrix' + save_file_suffix + '.pkl'):
  25. return None, None
  26. """**2. Set parameters.**"""
  27. # Parameters for GED computation.
  28. ged_options = {'method': 'IPFP', # use IPFP huristic.
  29. 'initialization_method': 'RANDOM', # or 'NODE', etc.
  30. # when bigger than 1, then the method is considered mIPFP.
  31. 'initial_solutions': int(num_solutions * 4),
  32. 'edit_cost': 'CONSTANT', # use CONSTANT cost.
  33. # the distance between non-symbolic node/edge labels is computed by euclidean distance.
  34. 'attr_distance': 'euclidean',
  35. 'ratio_runs_from_initial_solutions': 0.25,
  36. # parallel threads. Do not work if mpg_options['parallel'] = False.
  37. 'threads': multiprocessing.cpu_count(),
  38. 'init_option': 'EAGER_WITHOUT_SHUFFLED_COPIES'
  39. }
  40. edit_cost_constants = [i * ratio for i in [1, 1, 1]] + [1, 1, 1]
  41. # edit_cost_constants = [item * 0.01 for item in edit_cost_constants]
  42. # pickle.dump(edit_cost_constants, open(save_dir + "edit_costs" + save_file_suffix + ".pkl", "wb"))
  43. options = ged_options.copy()
  44. options['edit_cost_constants'] = edit_cost_constants
  45. options['node_labels'] = []
  46. options['edge_labels'] = []
  47. options['node_attrs'] = []
  48. options['edge_attrs'] = []
  49. parallel = True # if num_solutions == 1 else False
  50. """**5. Compute GED matrix.**"""
  51. ged_mat = 'error'
  52. runtime = 0
  53. try:
  54. time0 = time.time()
  55. ged_vec_init, ged_mat, n_edit_operations = compute_geds(graphs, options=options, repeats=1, parallel=parallel, verbose=True)
  56. runtime = time.time() - time0
  57. except Exception as exp:
  58. print('An exception occured when running this experiment:')
  59. LOG_FILENAME = save_dir + 'error.txt'
  60. logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)
  61. logging.exception(save_file_suffix)
  62. print(repr(exp))
  63. """**6. Get results.**"""
  64. with open(save_dir + 'ged_matrix' + save_file_suffix + '.pkl', 'wb') as f:
  65. pickle.dump(ged_mat, f)
  66. with open(save_dir + 'runtime' + save_file_suffix + '.pkl', 'wb') as f:
  67. pickle.dump(runtime, f)
  68. return ged_mat, runtime
  69. def save_trials_as_group(graphs, N, num_solutions, ratio):
  70. # Return if the group file exists.
  71. name_middle = '.' + str(N) + '.num_sols_' + str(num_solutions) + '.ratio_' + "{:.2f}".format(ratio) + '.'
  72. name_group = save_dir + 'groups/ged_mats' + name_middle + 'npy'
  73. if os.path.isfile(name_group):
  74. return
  75. ged_mats = []
  76. runtimes = []
  77. for trial in range(1, 101):
  78. print()
  79. print('Trial:', trial)
  80. ged_mat, runtime = xp_compute_ged_matrix(graphs, N, num_solutions, ratio, trial)
  81. ged_mats.append(ged_mat)
  82. runtimes.append(runtime)
  83. # Group trials and Remove single files.
  84. name_prefix = 'ged_matrix' + name_middle
  85. group_trials(save_dir, name_prefix, True, True, False)
  86. name_prefix = 'runtime' + name_middle
  87. group_trials(save_dir, name_prefix, True, True, False)
  88. def results_for_a_ratio(ratio):
  89. for N in N_list:
  90. print()
  91. print('# of graphs:', N)
  92. for num_solutions in [1, 20, 40, 60, 80, 100]:
  93. print()
  94. print('# of solutions:', num_solutions)
  95. save_trials_as_group(graphs[:N], N, num_solutions, ratio)
  96. if __name__ == '__main__':
  97. if len(sys.argv) > 1:
  98. N_list = [int(i) for i in sys.argv[1:]]
  99. else:
  100. N_list = [10, 50, 100]
  101. # Generate graphs.
  102. graphs = generate_graphs()
  103. save_dir = 'outputs/edit_costs.num_sols.N.IPFP/'
  104. os.makedirs(save_dir, exist_ok=True)
  105. os.makedirs(save_dir + 'groups/', exist_ok=True)
  106. for ratio in [10, 1, 0.1]:
  107. print()
  108. print('Ratio:', ratio)
  109. results_for_a_ratio(ratio)

A Python package for graph kernels, graph edit distances and graph pre-image problem.