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.

parallel.py 2.8 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Tue Dec 11 11:39:46 2018
  5. Parallel aid functions.
  6. @author: ljia
  7. """
  8. import multiprocessing
  9. from multiprocessing import Pool
  10. from tqdm import tqdm
  11. import sys
  12. def parallel_me(func, func_assign, var_to_assign, itr, len_itr=None, init_worker=None,
  13. glbv=None, method=None, n_jobs=None, chunksize=None, itr_desc='',
  14. verbose=True):
  15. '''
  16. '''
  17. if method == 'imap_unordered':
  18. if glbv: # global varibles required.
  19. # def init_worker(v_share):
  20. # global G_var
  21. # G_var = v_share
  22. if n_jobs == None:
  23. n_jobs = multiprocessing.cpu_count()
  24. with Pool(processes=n_jobs, initializer=init_worker,
  25. initargs=glbv) as pool:
  26. if chunksize is None:
  27. if len_itr < 100 * n_jobs:
  28. chunksize = int(len_itr / n_jobs) + 1
  29. else:
  30. chunksize = 100
  31. for result in (tqdm(pool.imap_unordered(func, itr, chunksize),
  32. desc=itr_desc, file=sys.stdout) if verbose else
  33. pool.imap_unordered(func, itr, chunksize)):
  34. func_assign(result, var_to_assign)
  35. pool.close()
  36. pool.join()
  37. else:
  38. if n_jobs == None:
  39. n_jobs = multiprocessing.cpu_count()
  40. with Pool(processes=n_jobs) as pool:
  41. if chunksize is None:
  42. if len_itr < 100 * n_jobs:
  43. chunksize = int(len_itr / n_jobs) + 1
  44. else:
  45. chunksize = 100
  46. for result in (tqdm(pool.imap_unordered(func, itr, chunksize),
  47. desc=itr_desc, file=sys.stdout) if verbose else
  48. pool.imap_unordered(func, itr, chunksize)):
  49. func_assign(result, var_to_assign)
  50. pool.close()
  51. pool.join()
  52. def parallel_gm(func, Kmatrix, Gn, init_worker=None, glbv=None,
  53. method='imap_unordered', n_jobs=None, chunksize=None,
  54. verbose=True): # @todo: Gn seems not necessary.
  55. from itertools import combinations_with_replacement
  56. def func_assign(result, var_to_assign):
  57. var_to_assign[result[0]][result[1]] = result[2]
  58. var_to_assign[result[1]][result[0]] = result[2]
  59. itr = combinations_with_replacement(range(0, len(Gn)), 2)
  60. len_itr = int(len(Gn) * (len(Gn) + 1) / 2)
  61. parallel_me(func, func_assign, Kmatrix, itr, len_itr=len_itr,
  62. init_worker=init_worker, glbv=glbv, method=method, n_jobs=n_jobs,
  63. chunksize=chunksize, itr_desc='calculating kernels', verbose=verbose)

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