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.

median_graph_estimator.py 39 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Mon Mar 16 18:04:55 2020
  5. @author: ljia
  6. """
  7. import numpy as np
  8. from gklearn.ged.env import AlgorithmState, NodeMap
  9. from gklearn.ged.util import misc
  10. from gklearn.utils import Timer
  11. import time
  12. from tqdm import tqdm
  13. import sys
  14. import networkx as nx
  15. class MedianGraphEstimator(object):
  16. def __init__(self, ged_env, constant_node_costs):
  17. """Constructor.
  18. Parameters
  19. ----------
  20. ged_env : gklearn.gedlib.gedlibpy.GEDEnv
  21. Initialized GED environment. The edit costs must be set by the user.
  22. constant_node_costs : Boolean
  23. Set to True if the node relabeling costs are constant.
  24. """
  25. self.__ged_env = ged_env
  26. self.__init_method = 'BRANCH_FAST'
  27. self.__init_options = ''
  28. self.__descent_method = 'BRANCH_FAST'
  29. self.__descent_options = ''
  30. self.__refine_method = 'IPFP'
  31. self.__refine_options = ''
  32. self.__constant_node_costs = constant_node_costs
  33. self.__labeled_nodes = (ged_env.get_num_node_labels() > 1)
  34. self.__node_del_cost = ged_env.get_node_del_cost(ged_env.get_node_label(1))
  35. self.__node_ins_cost = ged_env.get_node_ins_cost(ged_env.get_node_label(1))
  36. self.__labeled_edges = (ged_env.get_num_edge_labels() > 1)
  37. self.__edge_del_cost = ged_env.get_edge_del_cost(ged_env.get_edge_label(1))
  38. self.__edge_ins_cost = ged_env.get_edge_ins_cost(ged_env.get_edge_label(1))
  39. self.__init_type = 'RANDOM'
  40. self.__num_random_inits = 10
  41. self.__desired_num_random_inits = 10
  42. self.__use_real_randomness = True
  43. self.__seed = 0
  44. self.__update_order = True
  45. self.__refine = True
  46. self.__time_limit_in_sec = 0
  47. self.__epsilon = 0.0001
  48. self.__max_itrs = 100
  49. self.__max_itrs_without_update = 3
  50. self.__num_inits_increase_order = 10
  51. self.__init_type_increase_order = 'K-MEANS++'
  52. self.__max_itrs_increase_order = 10
  53. self.__print_to_stdout = 2
  54. self.__median_id = np.inf # @todo: check
  55. self.__median_node_id_prefix = '' # @todo: check
  56. self.__node_maps_from_median = {}
  57. self.__sum_of_distances = 0
  58. self.__best_init_sum_of_distances = np.inf
  59. self.__converged_sum_of_distances = np.inf
  60. self.__runtime = None
  61. self.__runtime_initialized = None
  62. self.__runtime_converged = None
  63. self.__itrs = [] # @todo: check: {} ?
  64. self.__num_decrease_order = 0
  65. self.__num_increase_order = 0
  66. self.__num_converged_descents = 0
  67. self.__state = AlgorithmState.TERMINATED
  68. self.__label_names = {}
  69. if ged_env is None:
  70. raise Exception('The GED environment pointer passed to the constructor of MedianGraphEstimator is null.')
  71. elif not ged_env.is_initialized():
  72. raise Exception('The GED environment is uninitialized. Call gedlibpy.GEDEnv.init() before passing it to the constructor of MedianGraphEstimator.')
  73. def set_options(self, options):
  74. """Sets the options of the estimator.
  75. Parameters
  76. ----------
  77. options : string
  78. String that specifies with which options to run the estimator.
  79. """
  80. self.__set_default_options()
  81. options_map = misc.options_string_to_options_map(options)
  82. for opt_name, opt_val in options_map.items():
  83. if opt_name == 'init-type':
  84. self.__init_type = opt_val
  85. if opt_val != 'MEDOID' and opt_val != 'RANDOM' and opt_val != 'MIN' and opt_val != 'MAX' and opt_val != 'MEAN':
  86. raise Exception('Invalid argument ' + opt_val + ' for option init-type. Usage: options = "[--init-type RANDOM|MEDOID|EMPTY|MIN|MAX|MEAN] [...]"')
  87. elif opt_name == 'random-inits':
  88. try:
  89. self.__num_random_inits = int(opt_val)
  90. self.__desired_num_random_inits = self.__num_random_inits
  91. except:
  92. raise Exception('Invalid argument "' + opt_val + '" for option random-inits. Usage: options = "[--random-inits <convertible to int greater 0>]"')
  93. if self.__num_random_inits <= 0:
  94. raise Exception('Invalid argument "' + opt_val + '" for option random-inits. Usage: options = "[--random-inits <convertible to int greater 0>]"')
  95. elif opt_name == 'randomness':
  96. if opt_val == 'PSEUDO':
  97. self.__use_real_randomness = False
  98. elif opt_val == 'REAL':
  99. self.__use_real_randomness = True
  100. else:
  101. raise Exception('Invalid argument "' + opt_val + '" for option randomness. Usage: options = "[--randomness REAL|PSEUDO] [...]"')
  102. elif opt_name == 'stdout':
  103. if opt_val == '0':
  104. self.__print_to_stdout = 0
  105. elif opt_val == '1':
  106. self.__print_to_stdout = 1
  107. elif opt_val == '2':
  108. self.__print_to_stdout = 2
  109. else:
  110. raise Exception('Invalid argument "' + opt_val + '" for option stdout. Usage: options = "[--stdout 0|1|2] [...]"')
  111. elif opt_name == 'update-order':
  112. if opt_val == 'TRUE':
  113. self.__update_order = True
  114. elif opt_val == 'FALSE':
  115. self.__update_order = False
  116. else:
  117. raise Exception('Invalid argument "' + opt_val + '" for option update-order. Usage: options = "[--update-order TRUE|FALSE] [...]"')
  118. elif opt_name == 'refine':
  119. if opt_val == 'TRUE':
  120. self.__refine = True
  121. elif opt_val == 'FALSE':
  122. self.__refine = False
  123. else:
  124. raise Exception('Invalid argument "' + opt_val + '" for option refine. Usage: options = "[--refine TRUE|FALSE] [...]"')
  125. elif opt_name == 'time-limit':
  126. try:
  127. self.__time_limit_in_sec = float(opt_val)
  128. except:
  129. raise Exception('Invalid argument "' + opt_val + '" for option time-limit. Usage: options = "[--time-limit <convertible to double>] [...]')
  130. elif opt_name == 'max-itrs':
  131. try:
  132. self.__max_itrs = int(opt_val)
  133. except:
  134. raise Exception('Invalid argument "' + opt_val + '" for option max-itrs. Usage: options = "[--max-itrs <convertible to int>] [...]')
  135. elif opt_name == 'max-itrs-without-update':
  136. try:
  137. self.__max_itrs_without_update = int(opt_val)
  138. except:
  139. raise Exception('Invalid argument "' + opt_val + '" for option max-itrs-without-update. Usage: options = "[--max-itrs-without-update <convertible to int>] [...]')
  140. elif opt_name == 'seed':
  141. try:
  142. self.__seed = int(opt_val)
  143. except:
  144. raise Exception('Invalid argument "' + opt_val + '" for option seed. Usage: options = "[--seed <convertible to int greater equal 0>] [...]')
  145. elif opt_name == 'epsilon':
  146. try:
  147. self.__epsilon = float(opt_val)
  148. except:
  149. raise Exception('Invalid argument "' + opt_val + '" for option epsilon. Usage: options = "[--epsilon <convertible to double greater 0>] [...]')
  150. if self.__epsilon <= 0:
  151. raise Exception('Invalid argument "' + opt_val + '" for option epsilon. Usage: options = "[--epsilon <convertible to double greater 0>] [...]')
  152. elif opt_name == 'inits-increase-order':
  153. try:
  154. self.__num_inits_increase_order = int(opt_val)
  155. except:
  156. raise Exception('Invalid argument "' + opt_val + '" for option inits-increase-order. Usage: options = "[--inits-increase-order <convertible to int greater 0>]"')
  157. if self.__num_inits_increase_order <= 0:
  158. raise Exception('Invalid argument "' + opt_val + '" for option inits-increase-order. Usage: options = "[--inits-increase-order <convertible to int greater 0>]"')
  159. elif opt_name == 'init-type-increase-order':
  160. self.__init_type_increase_order = opt_val
  161. if opt_val != 'CLUSTERS' and opt_val != 'K-MEANS++':
  162. raise Exception('Invalid argument ' + opt_val + ' for option init-type-increase-order. Usage: options = "[--init-type-increase-order CLUSTERS|K-MEANS++] [...]"')
  163. elif opt_name == 'max-itrs-increase-order':
  164. try:
  165. self.__max_itrs_increase_order = int(opt_val)
  166. except:
  167. raise Exception('Invalid argument "' + opt_val + '" for option max-itrs-increase-order. Usage: options = "[--max-itrs-increase-order <convertible to int>] [...]')
  168. else:
  169. valid_options = '[--init-type <arg>] [--random-inits <arg>] [--randomness <arg>] [--seed <arg>] [--stdout <arg>] '
  170. valid_options += '[--time-limit <arg>] [--max-itrs <arg>] [--epsilon <arg>] '
  171. valid_options += '[--inits-increase-order <arg>] [--init-type-increase-order <arg>] [--max-itrs-increase-order <arg>]'
  172. raise Exception('Invalid option "' + opt_name + '". Usage: options = "' + valid_options + '"')
  173. def set_init_method(self, init_method, init_options=''):
  174. """Selects method to be used for computing the initial medoid graph.
  175. Parameters
  176. ----------
  177. init_method : string
  178. The selected method. Default: ged::Options::GEDMethod::BRANCH_UNIFORM.
  179. init_options : string
  180. The options for the selected method. Default: "".
  181. Notes
  182. -----
  183. Has no effect unless "--init-type MEDOID" is passed to set_options().
  184. """
  185. self.__init_method = init_method;
  186. self.__init_options = init_options;
  187. def set_descent_method(self, descent_method, descent_options=''):
  188. """Selects method to be used for block gradient descent..
  189. Parameters
  190. ----------
  191. descent_method : string
  192. The selected method. Default: ged::Options::GEDMethod::BRANCH_FAST.
  193. descent_options : string
  194. The options for the selected method. Default: "".
  195. Notes
  196. -----
  197. Has no effect unless "--init-type MEDOID" is passed to set_options().
  198. """
  199. self.__descent_method = descent_method;
  200. self.__descent_options = descent_options;
  201. def set_refine_method(self, refine_method, refine_options):
  202. """Selects method to be used for improving the sum of distances and the node maps for the converged median.
  203. Parameters
  204. ----------
  205. refine_method : string
  206. The selected method. Default: "IPFP".
  207. refine_options : string
  208. The options for the selected method. Default: "".
  209. Notes
  210. -----
  211. Has no effect if "--refine FALSE" is passed to set_options().
  212. """
  213. self.__refine_method = refine_method
  214. self.__refine_options = refine_options
  215. def run(self, graph_ids, set_median_id, gen_median_id):
  216. """Computes a generalized median graph.
  217. Parameters
  218. ----------
  219. graph_ids : list[integer]
  220. The IDs of the graphs for which the median should be computed. Must have been added to the environment passed to the constructor.
  221. set_median_id : integer
  222. The ID of the computed set-median. A dummy graph with this ID must have been added to the environment passed to the constructor. Upon termination, the computed median can be obtained via gklearn.gedlib.gedlibpy.GEDEnv.get_graph().
  223. gen_median_id : integer
  224. The ID of the computed generalized median. Upon termination, the computed median can be obtained via gklearn.gedlib.gedlibpy.GEDEnv.get_graph().
  225. """
  226. # Sanity checks.
  227. if len(graph_ids) == 0:
  228. raise Exception('Empty vector of graph IDs, unable to compute median.')
  229. all_graphs_empty = True
  230. for graph_id in graph_ids:
  231. if self.__ged_env.get_graph_num_nodes(graph_id) > 0:
  232. self.__median_node_id_prefix = self.__ged_env.get_original_node_ids(graph_id)[0]
  233. all_graphs_empty = False
  234. break
  235. if all_graphs_empty:
  236. raise Exception('All graphs in the collection are empty.')
  237. # Start timer and record start time.
  238. start = time.time()
  239. timer = Timer(self.__time_limit_in_sec)
  240. self.__median_id = gen_median_id
  241. self.__state = AlgorithmState.TERMINATED
  242. # Get ExchangeGraph representations of the input graphs.
  243. graphs = {}
  244. for graph_id in graph_ids:
  245. # @todo: get_nx_graph() function may need to be modified according to the coming code.
  246. graphs[graph_id] = self.__ged_env.get_nx_graph(graph_id, True, True, False)
  247. # print(self.__ged_env.get_graph_internal_id(0))
  248. # print(graphs[0].graph)
  249. # print(graphs[0].nodes(data=True))
  250. # print(graphs[0].edges(data=True))
  251. # print(nx.adjacency_matrix(graphs[0]))
  252. # Construct initial medians.
  253. medians = []
  254. self.__construct_initial_medians(graph_ids, timer, medians)
  255. end_init = time.time()
  256. self.__runtime_initialized = end_init - start
  257. # print(medians[0].graph)
  258. # print(medians[0].nodes(data=True))
  259. # print(medians[0].edges(data=True))
  260. # print(nx.adjacency_matrix(medians[0]))
  261. # Reset information about iterations and number of times the median decreases and increases.
  262. self.__itrs = [0] * len(medians)
  263. self.__num_decrease_order = 0
  264. self.__num_increase_order = 0
  265. self.__num_converged_descents = 0
  266. # Initialize the best median.
  267. best_sum_of_distances = np.inf
  268. self.__best_init_sum_of_distances = np.inf
  269. node_maps_from_best_median = {}
  270. # Run block gradient descent from all initial medians.
  271. self.__ged_env.set_method(self.__descent_method, self.__descent_options)
  272. for median_pos in range(0, len(medians)):
  273. # Terminate if the timer has expired and at least one SOD has been computed.
  274. if timer.expired() and median_pos > 0:
  275. break
  276. # Print information about current iteration.
  277. if self.__print_to_stdout == 2:
  278. print('\n===========================================================')
  279. print('Block gradient descent for initial median', str(median_pos + 1), 'of', str(len(medians)), '.')
  280. print('-----------------------------------------------------------')
  281. # Get reference to the median.
  282. median = medians[median_pos]
  283. # Load initial median into the environment.
  284. self.__ged_env.load_nx_graph(median, gen_median_id)
  285. self.__ged_env.init(self.__ged_env.get_init_type())
  286. # Print information about current iteration.
  287. if self.__print_to_stdout == 2:
  288. progress = tqdm(desc='Computing initial node maps', total=len(graph_ids), file=sys.stdout)
  289. # Compute node maps and sum of distances for initial median.
  290. self.__sum_of_distances = 0
  291. self.__node_maps_from_median.clear()
  292. for graph_id in graph_ids:
  293. self.__ged_env.run_method(gen_median_id, graph_id)
  294. self.__node_maps_from_median[graph_id] = self.__ged_env.get_node_map(gen_median_id, graph_id)
  295. # print(self.__node_maps_from_median[graph_id])
  296. self.__sum_of_distances += self.__node_maps_from_median[graph_id].induced_cost()
  297. # print(self.__sum_of_distances)
  298. # Print information about current iteration.
  299. if self.__print_to_stdout == 2:
  300. progress.update(1)
  301. self.__best_init_sum_of_distances = min(self.__best_init_sum_of_distances, self.__sum_of_distances)
  302. self.__ged_env.load_nx_graph(median, set_median_id)
  303. print(self.__best_init_sum_of_distances)
  304. # Print information about current iteration.
  305. if self.__print_to_stdout == 2:
  306. print('\n')
  307. # Run block gradient descent from initial median.
  308. converged = False
  309. itrs_without_update = 0
  310. while not self.__termination_criterion_met(converged, timer, self.__itrs[median_pos], itrs_without_update):
  311. # Print information about current iteration.
  312. if self.__print_to_stdout == 2:
  313. print('\n===========================================================')
  314. print('Iteration', str(self.__itrs[median_pos] + 1), 'for initial median', str(median_pos + 1), 'of', str(len(medians)), '.')
  315. print('-----------------------------------------------------------')
  316. # Initialize flags that tell us what happened in the iteration.
  317. median_modified = False
  318. node_maps_modified = False
  319. decreased_order = False
  320. increased_order = False
  321. # Update the median. # @todo!!!!!!!!!!!!!!!!!!!!!!
  322. median_modified = self.__update_median(graphs, median)
  323. if self.__update_order:
  324. if not median_modified or self.__itrs[median_pos] == 0:
  325. decreased_order = self.__decrease_order(graphs, median)
  326. if not decreased_order or self.__itrs[median_pos] == 0:
  327. increased_order = False
  328. # Update the number of iterations without update of the median.
  329. if median_modified or decreased_order or increased_order:
  330. itrs_without_update = 0
  331. else:
  332. itrs_without_update += 1
  333. # Print information about current iteration.
  334. if self.__print_to_stdout == 2:
  335. print('Loading median to environment: ... ', end='')
  336. # Load the median into the environment.
  337. # @todo: should this function use the original node label?
  338. self.__ged_env.load_nx_graph(median, gen_median_id)
  339. self.__ged_env.init(self.__ged_env.get_init_type())
  340. # Print information about current iteration.
  341. if self.__print_to_stdout == 2:
  342. print('done.')
  343. # Print information about current iteration.
  344. if self.__print_to_stdout == 2:
  345. print('Updating induced costs: ... ', end='')
  346. # Compute induced costs of the old node maps w.r.t. the updated median.
  347. for graph_id in graph_ids:
  348. # print(self.__node_maps_from_median[graph_id].induced_cost())
  349. self.__ged_env.compute_induced_cost(gen_median_id, graph_id, self.__node_maps_from_median[graph_id])
  350. # print('---------------------------------------')
  351. # print(self.__node_maps_from_median[graph_id].induced_cost())
  352. # @todo:!!!!!!!!!!!!!!!!!!!!!!!!!!!!This value is a slight different from the c++ program, which might be a bug! Use it very carefully!
  353. # Print information about current iteration.
  354. if self.__print_to_stdout == 2:
  355. print('done.')
  356. # Update the node maps.
  357. node_maps_modified = self.__update_node_maps() # @todo
  358. # Update the order of the median if no improvement can be found with the current order.
  359. # Update the sum of distances.
  360. old_sum_of_distances = self.__sum_of_distances
  361. self.__sum_of_distances = 0
  362. for graph_id, node_map in self.__node_maps_from_median.items():
  363. self.__sum_of_distances += node_map.induced_cost()
  364. # print(self.__sum_of_distances)
  365. # Print information about current iteration.
  366. if self.__print_to_stdout == 2:
  367. print('Old local SOD: ', old_sum_of_distances)
  368. print('New local SOD: ', self.__sum_of_distances)
  369. print('Best converged SOD: ', best_sum_of_distances)
  370. print('Modified median: ', median_modified)
  371. print('Modified node maps: ', node_maps_modified)
  372. print('Decreased order: ', decreased_order)
  373. print('Increased order: ', increased_order)
  374. print('===========================================================\n')
  375. converged = not (median_modified or node_maps_modified or decreased_order or increased_order)
  376. self.__itrs[median_pos] += 1
  377. # Update the best median.
  378. if self.__sum_of_distances < best_sum_of_distances:
  379. best_sum_of_distances = self.__sum_of_distances
  380. node_maps_from_best_median = self.__node_maps_from_median.copy() # @todo: this is a shallow copy, not sure if it is enough.
  381. best_median = median
  382. # Update the number of converged descents.
  383. if converged:
  384. self.__num_converged_descents += 1
  385. # Store the best encountered median.
  386. self.__sum_of_distances = best_sum_of_distances
  387. self.__node_maps_from_median = node_maps_from_best_median
  388. self.__ged_env.load_nx_graph(best_median, gen_median_id)
  389. self.__ged_env.init(self.__ged_env.get_init_type())
  390. end_descent = time.time()
  391. self.__runtime_converged = end_descent - start
  392. # Refine the sum of distances and the node maps for the converged median.
  393. self.__converged_sum_of_distances = self.__sum_of_distances
  394. if self.__refine:
  395. self.__improve_sum_of_distances(timer) # @todo
  396. # Record end time, set runtime and reset the number of initial medians.
  397. end = time.time()
  398. self.__runtime = end - start
  399. self.__num_random_inits = self.__desired_num_random_inits
  400. # Print global information.
  401. if self.__print_to_stdout != 0:
  402. print('\n===========================================================')
  403. print('Finished computation of generalized median graph.')
  404. print('-----------------------------------------------------------')
  405. print('Best SOD after initialization: ', self.__best_init_sum_of_distances)
  406. print('Converged SOD: ', self.__converged_sum_of_distances)
  407. if self.__refine:
  408. print('Refined SOD: ', self.__sum_of_distances)
  409. print('Overall runtime: ', self.__runtime)
  410. print('Runtime of initialization: ', self.__runtime_initialized)
  411. print('Runtime of block gradient descent: ', self.__runtime_converged - self.__runtime_initialized)
  412. if self.__refine:
  413. print('Runtime of refinement: ', self.__runtime - self.__runtime_converged)
  414. print('Number of initial medians: ', len(medians))
  415. total_itr = 0
  416. num_started_descents = 0
  417. for itr in self.__itrs:
  418. total_itr += itr
  419. if itr > 0:
  420. num_started_descents += 1
  421. print('Size of graph collection: ', len(graph_ids))
  422. print('Number of started descents: ', num_started_descents)
  423. print('Number of converged descents: ', self.__num_converged_descents)
  424. print('Overall number of iterations: ', total_itr)
  425. print('Overall number of times the order decreased: ', self.__num_decrease_order)
  426. print('Overall number of times the order increased: ', self.__num_increase_order)
  427. print('===========================================================\n')
  428. def get_sum_of_distances(self, state=''):
  429. """Returns the sum of distances.
  430. Parameters
  431. ----------
  432. state : string
  433. The state of the estimator. Can be 'initialized' or 'converged'. Default: ""
  434. Returns
  435. -------
  436. float
  437. The sum of distances (SOD) of the median when the estimator was in the state `state` during the last call to run(). If `state` is not given, the converged SOD (without refinement) or refined SOD (with refinement) is returned.
  438. """
  439. if not self.__median_available():
  440. raise Exception('No median has been computed. Call run() before calling get_sum_of_distances().')
  441. if state == 'initialized':
  442. return self.__best_init_sum_of_distances
  443. if state == 'converged':
  444. return self.__converged_sum_of_distances
  445. return self.__sum_of_distances
  446. def __set_default_options(self):
  447. self.__init_type = 'RANDOM'
  448. self.__num_random_inits = 10
  449. self.__desired_num_random_inits = 10
  450. self.__use_real_randomness = True
  451. self.__seed = 0
  452. self.__update_order = True
  453. self.__refine = True
  454. self.__time_limit_in_sec = 0
  455. self.__epsilon = 0.0001
  456. self.__max_itrs = 100
  457. self.__max_itrs_without_update = 3
  458. self.__num_inits_increase_order = 10
  459. self.__init_type_increase_order = 'K-MEANS++'
  460. self.__max_itrs_increase_order = 10
  461. self.__print_to_stdout = 2
  462. self.__label_names = {}
  463. def __construct_initial_medians(self, graph_ids, timer, initial_medians):
  464. # Print information about current iteration.
  465. if self.__print_to_stdout == 2:
  466. print('\n===========================================================')
  467. print('Constructing initial median(s).')
  468. print('-----------------------------------------------------------')
  469. # Compute or sample the initial median(s).
  470. initial_medians.clear()
  471. if self.__init_type == 'MEDOID':
  472. self.__compute_medoid(graph_ids, timer, initial_medians)
  473. elif self.__init_type == 'MAX':
  474. pass # @todo
  475. # compute_max_order_graph_(graph_ids, initial_medians)
  476. elif self.__init_type == 'MIN':
  477. pass # @todo
  478. # compute_min_order_graph_(graph_ids, initial_medians)
  479. elif self.__init_type == 'MEAN':
  480. pass # @todo
  481. # compute_mean_order_graph_(graph_ids, initial_medians)
  482. else:
  483. pass # @todo
  484. # sample_initial_medians_(graph_ids, initial_medians)
  485. # Print information about current iteration.
  486. if self.__print_to_stdout == 2:
  487. print('===========================================================')
  488. def __compute_medoid(self, graph_ids, timer, initial_medians):
  489. # Use method selected for initialization phase.
  490. self.__ged_env.set_method(self.__init_method, self.__init_options)
  491. # Print information about current iteration.
  492. if self.__print_to_stdout == 2:
  493. progress = tqdm(desc='Computing medoid', total=len(graph_ids), file=sys.stdout)
  494. # Compute the medoid.
  495. medoid_id = graph_ids[0]
  496. best_sum_of_distances = np.inf
  497. for g_id in graph_ids:
  498. if timer.expired():
  499. self.__state = AlgorithmState.CALLED
  500. break
  501. sum_of_distances = 0
  502. for h_id in graph_ids:
  503. self.__ged_env.run_method(g_id, h_id)
  504. sum_of_distances += self.__ged_env.get_upper_bound(g_id, h_id)
  505. if sum_of_distances < best_sum_of_distances:
  506. best_sum_of_distances = sum_of_distances
  507. medoid_id = g_id
  508. # Print information about current iteration.
  509. if self.__print_to_stdout == 2:
  510. progress.update(1)
  511. initial_medians.append(self.__ged_env.get_nx_graph(medoid_id, True, True, False)) # @todo
  512. # Print information about current iteration.
  513. if self.__print_to_stdout == 2:
  514. print('\n')
  515. def __termination_criterion_met(self, converged, timer, itr, itrs_without_update):
  516. if timer.expired() or (itr >= self.__max_itrs if self.__max_itrs >= 0 else False):
  517. if self.__state == AlgorithmState.TERMINATED:
  518. self.__state = AlgorithmState.INITIALIZED
  519. return True
  520. return converged or (itrs_without_update > self.__max_itrs_without_update if self.__max_itrs_without_update >= 0 else False)
  521. def __update_median(self, graphs, median):
  522. # Print information about current iteration.
  523. if self.__print_to_stdout == 2:
  524. print('Updating median: ', end='')
  525. # Store copy of the old median.
  526. old_median = median.copy() # @todo: this is just a shallow copy.
  527. # Update the node labels.
  528. if self.__labeled_nodes:
  529. self.__update_node_labels(graphs, median)
  530. # Update the edges and their labels.
  531. self.__update_edges(graphs, median)
  532. # Print information about current iteration.
  533. if self.__print_to_stdout == 2:
  534. print('done.')
  535. return not self.__are_graphs_equal(median, old_median)
  536. def __update_node_labels(self, graphs, median):
  537. # Print information about current iteration.
  538. if self.__print_to_stdout == 2:
  539. print('nodes ... ', end='')
  540. # Iterate through all nodes of the median.
  541. for i in range(0, nx.number_of_nodes(median)):
  542. # print('i: ', i)
  543. # Collect the labels of the substituted nodes.
  544. node_labels = []
  545. for graph_id, graph in graphs.items():
  546. # print('graph_id: ', graph_id)
  547. # print(self.__node_maps_from_median[graph_id])
  548. k = self.__node_maps_from_median[graph_id].image(i)
  549. # print('k: ', k)
  550. if k != np.inf:
  551. node_labels.append(graph.nodes[k])
  552. # Compute the median label and update the median.
  553. if len(node_labels) > 0:
  554. # median_label = self.__ged_env.get_median_node_label(node_labels)
  555. median_label = self.__get_median_node_label(node_labels)
  556. if self.__ged_env.get_node_rel_cost(median.nodes[i], median_label) > self.__epsilon:
  557. nx.set_node_attributes(median, {i: median_label})
  558. def __update_edges(self, graphs, median):
  559. # Print information about current iteration.
  560. if self.__print_to_stdout == 2:
  561. print('edges ... ', end='')
  562. # # Clear the adjacency lists of the median and reset number of edges to 0.
  563. # median_edges = list(median.edges)
  564. # for (head, tail) in median_edges:
  565. # median.remove_edge(head, tail)
  566. # @todo: what if edge is not labeled?
  567. # Iterate through all possible edges (i,j) of the median.
  568. for i in range(0, nx.number_of_nodes(median)):
  569. for j in range(i + 1, nx.number_of_nodes(median)):
  570. # Collect the labels of the edges to which (i,j) is mapped by the node maps.
  571. edge_labels = []
  572. for graph_id, graph in graphs.items():
  573. k = self.__node_maps_from_median[graph_id].image(i)
  574. l = self.__node_maps_from_median[graph_id].image(j)
  575. if k != np.inf and l != np.inf:
  576. if graph.has_edge(k, l):
  577. edge_labels.append(graph.edges[(k, l)])
  578. # Compute the median edge label and the overall edge relabeling cost.
  579. rel_cost = 0
  580. median_label = self.__ged_env.get_edge_label(1)
  581. if median.has_edge(i, j):
  582. median_label = median.edges[(i, j)]
  583. if self.__labeled_edges and len(edge_labels) > 0:
  584. new_median_label = self.__get_median_edge_label(edge_labels)
  585. if self.__ged_env.get_edge_rel_cost(median_label, new_median_label) > self.__epsilon:
  586. median_label = new_median_label
  587. for edge_label in edge_labels:
  588. rel_cost += self.__ged_env.get_edge_rel_cost(median_label, edge_label)
  589. # Update the median.
  590. if median.has_edge(i, j):
  591. median.remove_edge(i, j)
  592. if rel_cost < (self.__edge_ins_cost + self.__edge_del_cost) * len(edge_labels) - self.__edge_del_cost * len(graphs):
  593. median.add_edge(i, j, **median_label)
  594. # else:
  595. # if median.has_edge(i, j):
  596. # median.remove_edge(i, j)
  597. def __update_node_maps(self):
  598. # Print information about current iteration.
  599. if self.__print_to_stdout == 2:
  600. progress = tqdm(desc='Updating node maps', total=len(self.__node_maps_from_median), file=sys.stdout)
  601. # Update the node maps.
  602. node_maps_were_modified = False
  603. for graph_id, node_map in self.__node_maps_from_median.items():
  604. self.__ged_env.run_method(self.__median_id, graph_id)
  605. if self.__ged_env.get_upper_bound(self.__median_id, graph_id) < node_map.induced_cost() - self.__epsilon:
  606. # xxx = self.__node_maps_from_median[graph_id]
  607. self.__node_maps_from_median[graph_id] = self.__ged_env.get_node_map(self.__median_id, graph_id)
  608. # yyy = self.__node_maps_from_median[graph_id]
  609. node_maps_were_modified = True
  610. # Print information about current iteration.
  611. if self.__print_to_stdout == 2:
  612. progress.update(1)
  613. # Print information about current iteration.
  614. if self.__print_to_stdout == 2:
  615. print('\n')
  616. # Return true if the node maps were modified.
  617. return node_maps_were_modified
  618. def __decrease_order(self, graphs, median):
  619. # Print information about current iteration
  620. if self.__print_to_stdout == 2:
  621. print('Trying to decrease order: ... ', end='')
  622. # Initialize ID of the node that is to be deleted.
  623. id_deleted_node = [None] # @todo: or np.inf
  624. decreased_order = False
  625. # Decrease the order as long as the best deletion delta is negative.
  626. while self.__compute_best_deletion_delta(graphs, median, id_deleted_node) > -self.__epsilon: # @todo
  627. decreased_order = True
  628. self.__delete_node_from_median(id_deleted_node[0], median)
  629. # Print information about current iteration.
  630. if self.__print_to_stdout == 2:
  631. print('done.')
  632. # Return true iff the order was decreased.
  633. return decreased_order
  634. def __compute_best_deletion_delta(self, graphs, median, id_deleted_node):
  635. best_delta = 0.0
  636. # Determine node that should be deleted (if any).
  637. for i in range(0, nx.number_of_nodes(median)):
  638. # Compute cost delta.
  639. delta = 0.0
  640. for graph_id, graph in graphs.items():
  641. k = self.__node_maps_from_median[graph_id].image(i)
  642. if k == np.inf:
  643. delta -= self.__node_del_cost
  644. else:
  645. delta += self.__node_ins_cost - self.__ged_env.get_node_rel_cost(median.nodes[i], graph.nodes[k])
  646. for j, j_label in median[i].items():
  647. l = self.__node_maps_from_median[graph_id].image(j)
  648. if k == np.inf or l == np.inf:
  649. delta -= self.__edge_del_cost
  650. elif not graph.has_edge(k, l):
  651. delta -= self.__edge_del_cost
  652. else:
  653. delta += self.__edge_ins_cost - self.__ged_env.get_edge_rel_cost(j_label, graph.edges[(k, l)])
  654. # Update best deletion delta.
  655. if delta < best_delta - self.__epsilon:
  656. best_delta = delta
  657. id_deleted_node[0] = i
  658. id_deleted_node[0] = i # @todo:
  659. return best_delta
  660. def __delete_node_from_median(self, id_deleted_node, median):
  661. # Update the median.
  662. median.remove_node(id_deleted_node)
  663. # Update the node maps.
  664. for key, node_map in self.__node_maps_from_median.items():
  665. new_node_map = NodeMap(nx.number_of_nodes(median), node_map.num_target_nodes())
  666. is_unassigned_target_node = [True] * node_map.num_target_nodes()
  667. for i in range(0, nx.number_of_nodes(median)):
  668. if i != id_deleted_node:
  669. new_i = (i if i < id_deleted_node else i - 1)
  670. k = node_map.image(i)
  671. new_node_map.add_assignment(new_i, k)
  672. if k != np.inf:
  673. is_unassigned_target_node[k] = False
  674. for k in range(0, node_map.num_target_nodes()):
  675. if is_unassigned_target_node[k]:
  676. new_node_map.add_assignment(np.inf, k)
  677. self.__node_maps_from_median[key] = new_node_map
  678. # Increase overall number of decreases.
  679. self.__num_decrease_order += 1
  680. def __improve_sum_of_distances(self, timer):
  681. pass
  682. def __median_available(self):
  683. return self.__median_id != np.inf
  684. # def __get_node_image_from_map(self, node_map, node):
  685. # """
  686. # Return ID of the node mapping of `node` in `node_map`.
  687. # Parameters
  688. # ----------
  689. # node_map : list[tuple(int, int)]
  690. # List of node maps where the mapping node is found.
  691. #
  692. # node : int
  693. # The mapping node of this node is returned
  694. # Raises
  695. # ------
  696. # Exception
  697. # If the node with ID `node` is not contained in the source nodes of the node map.
  698. # Returns
  699. # -------
  700. # int
  701. # ID of the mapping of `node`.
  702. #
  703. # Notes
  704. # -----
  705. # This function is not implemented in the `ged::MedianGraphEstimator` class of the `GEDLIB` library. Instead it is a Python implementation of the `ged::NodeMap::image` function.
  706. # """
  707. # if node < len(node_map):
  708. # return node_map[node][1] if node_map[node][1] < len(node_map) else np.inf
  709. # else:
  710. # raise Exception('The node with ID ', str(node), ' is not contained in the source nodes of the node map.')
  711. # return np.inf
  712. def __are_graphs_equal(self, g1, g2):
  713. """
  714. Check if the two graphs are equal.
  715. Parameters
  716. ----------
  717. g1 : NetworkX graph object
  718. Graph 1 to be compared.
  719. g2 : NetworkX graph object
  720. Graph 2 to be compared.
  721. Returns
  722. -------
  723. bool
  724. True if the two graph are equal.
  725. Notes
  726. -----
  727. This is not an identical check. Here the two graphs are equal if and only if their original_node_ids, nodes, all node labels, edges and all edge labels are equal. This function is specifically designed for class `MedianGraphEstimator` and should not be used elsewhere.
  728. """
  729. # check original node ids.
  730. if not g1.graph['original_node_ids'] == g2.graph['original_node_ids']:
  731. return False
  732. # check nodes.
  733. nlist1 = [n for n in g1.nodes(data=True)]
  734. nlist2 = [n for n in g2.nodes(data=True)]
  735. if not nlist1 == nlist2:
  736. return False
  737. # check edges.
  738. elist1 = [n for n in g1.edges(data=True)]
  739. elist2 = [n for n in g2.edges(data=True)]
  740. if not elist1 == elist2:
  741. return False
  742. return True
  743. def compute_my_cost(g, h, node_map):
  744. cost = 0.0
  745. for node in g.nodes:
  746. cost += 0
  747. def set_label_names(self, node_labels=[], edge_labels=[], node_attrs=[], edge_attrs=[]):
  748. self.__label_names = {'node_labels': node_labels, 'edge_labels': edge_labels,
  749. 'node_attrs': node_attrs, 'edge_attrs': edge_attrs}
  750. def __get_median_node_label(self, node_labels):
  751. if len(self.__label_names['node_labels']) > 0:
  752. return self.__get_median_label_symbolic(node_labels)
  753. elif len(self.__label_names['node_attrs']) > 0:
  754. return self.__get_median_label_nonsymbolic(node_labels)
  755. else:
  756. raise Exception('Node label names are not given.')
  757. def __get_median_edge_label(self, edge_labels):
  758. if len(self.__label_names['edge_labels']) > 0:
  759. return self.__get_median_label_symbolic(edge_labels)
  760. elif len(self.__label_names['edge_attrs']) > 0:
  761. return self.__get_median_label_nonsymbolic(edge_labels)
  762. else:
  763. raise Exception('Edge label names are not given.')
  764. def __get_median_label_symbolic(self, labels):
  765. # Construct histogram.
  766. hist = {}
  767. for label in labels:
  768. label = tuple([kv for kv in label.items()]) # @todo: this may be slow.
  769. if label not in hist:
  770. hist[label] = 1
  771. else:
  772. hist[label] += 1
  773. # Return the label that appears most frequently.
  774. best_count = 0
  775. median_label = {}
  776. for label, count in hist.items():
  777. if count > best_count:
  778. best_count = count
  779. median_label = {kv[0]: kv[1] for kv in label}
  780. return median_label
  781. def __get_median_label_nonsymbolic(self, labels):
  782. if len(labels) == 0:
  783. return {} # @todo
  784. else:
  785. # Transform the labels into coordinates and compute mean label as initial solution.
  786. labels_as_coords = []
  787. sums = {}
  788. for key, val in labels[0].items():
  789. sums[key] = 0
  790. for label in labels:
  791. coords = {}
  792. for key, val in label.items():
  793. label_f = float(val)
  794. sums[key] += label_f
  795. coords[key] = label_f
  796. labels_as_coords.append(coords)
  797. median = {}
  798. for key, val in sums.items():
  799. median[key] = val / len(labels)
  800. # Run main loop of Weiszfeld's Algorithm.
  801. epsilon = 0.0001
  802. delta = 1.0
  803. num_itrs = 0
  804. all_equal = False
  805. while ((delta > epsilon) and (num_itrs < 100) and (not all_equal)):
  806. numerator = {}
  807. for key, val in sums.items():
  808. numerator[key] = 0
  809. denominator = 0
  810. for label_as_coord in labels_as_coords:
  811. norm = 0
  812. for key, val in label_as_coord.items():
  813. norm += (val - median[key]) ** 2
  814. norm = np.sqrt(norm)
  815. if norm > 0:
  816. for key, val in label_as_coord.items():
  817. numerator[key] += val / norm
  818. denominator += 1.0 / norm
  819. if denominator == 0:
  820. all_equal = True
  821. else:
  822. new_median = {}
  823. delta = 0.0
  824. for key, val in numerator.items():
  825. this_median = val / denominator
  826. new_median[key] = this_median
  827. delta += np.abs(median[key] - this_median)
  828. median = new_median
  829. num_itrs += 1
  830. # Transform the solution to strings and return it.
  831. median_label = {}
  832. for key, val in median.items():
  833. median_label[key] = str(val)
  834. return median_label
  835. # def __get_median_edge_label_symbolic(self, edge_labels):
  836. # pass
  837. # def __get_median_edge_label_nonsymbolic(self, edge_labels):
  838. # if len(edge_labels) == 0:
  839. # return {}
  840. # else:
  841. # # Transform the labels into coordinates and compute mean label as initial solution.
  842. # edge_labels_as_coords = []
  843. # sums = {}
  844. # for key, val in edge_labels[0].items():
  845. # sums[key] = 0
  846. # for edge_label in edge_labels:
  847. # coords = {}
  848. # for key, val in edge_label.items():
  849. # label = float(val)
  850. # sums[key] += label
  851. # coords[key] = label
  852. # edge_labels_as_coords.append(coords)
  853. # median = {}
  854. # for key, val in sums.items():
  855. # median[key] = val / len(edge_labels)
  856. #
  857. # # Run main loop of Weiszfeld's Algorithm.
  858. # epsilon = 0.0001
  859. # delta = 1.0
  860. # num_itrs = 0
  861. # all_equal = False
  862. # while ((delta > epsilon) and (num_itrs < 100) and (not all_equal)):
  863. # numerator = {}
  864. # for key, val in sums.items():
  865. # numerator[key] = 0
  866. # denominator = 0
  867. # for edge_label_as_coord in edge_labels_as_coords:
  868. # norm = 0
  869. # for key, val in edge_label_as_coord.items():
  870. # norm += (val - median[key]) ** 2
  871. # norm += np.sqrt(norm)
  872. # if norm > 0:
  873. # for key, val in edge_label_as_coord.items():
  874. # numerator[key] += val / norm
  875. # denominator += 1.0 / norm
  876. # if denominator == 0:
  877. # all_equal = True
  878. # else:
  879. # new_median = {}
  880. # delta = 0.0
  881. # for key, val in numerator.items():
  882. # this_median = val / denominator
  883. # new_median[key] = this_median
  884. # delta += np.abs(median[key] - this_median)
  885. # median = new_median
  886. #
  887. # num_itrs += 1
  888. #
  889. # # Transform the solution to ged::GXLLabel and return it.
  890. # median_label = {}
  891. # for key, val in median.items():
  892. # median_label[key] = str(val)
  893. # return median_label

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