util.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. import collections
  2. import copy
  3. import datetime
  4. import gc
  5. import time
  6. # import torch
  7. import numpy as np
  8. from util.logconf import logging
  9. log = logging.getLogger(__name__)
  10. # log.setLevel(logging.WARN)
  11. # log.setLevel(logging.INFO)
  12. log.setLevel(logging.DEBUG)
  13. IrcTuple = collections.namedtuple('IrcTuple', ['index', 'row', 'col'])
  14. XyzTuple = collections.namedtuple('XyzTuple', ['x', 'y', 'z'])
  15. def xyz2irc(coord_xyz, origin_xyz, vxSize_xyz, direction_tup):
  16. # Note: _cri means Col,Row,Index
  17. if direction_tup == (1, 0, 0, 0, 1, 0, 0, 0, 1):
  18. direction_ary = np.ones((3,))
  19. elif direction_tup == (-1, 0, 0, 0, -1, 0, 0, 0, 1):
  20. direction_ary = np.array((-1, -1, 1))
  21. else:
  22. raise Exception("Unsupported direction_tup: {}".format(direction_tup))
  23. coord_cri = (np.array(coord_xyz) - np.array(origin_xyz)) / np.array(vxSize_xyz)
  24. coord_cri *= direction_ary
  25. return IrcTuple(*list(reversed(coord_cri.tolist())))
  26. def irc2xyz(coord_irc, origin_xyz, vxSize_xyz, direction_tup):
  27. # Note: _cri means Col,Row,Index
  28. coord_cri = np.array(list(reversed(coord_irc)))
  29. if direction_tup == (1, 0, 0, 0, 1, 0, 0, 0, 1):
  30. direction_ary = np.ones((3,))
  31. elif direction_tup == (-1, 0, 0, 0, -1, 0, 0, 0, 1):
  32. direction_ary = np.array((-1, -1, 1))
  33. else:
  34. raise Exception("Unsupported direction_tup: {}".format(direction_tup))
  35. coord_xyz = coord_cri * direction_ary * np.array(vxSize_xyz) + np.array(origin_xyz)
  36. return XyzTuple(*coord_xyz.tolist())
  37. def importstr(module_str, from_=None):
  38. """
  39. >>> importstr('os')
  40. <module 'os' from '.../os.pyc'>
  41. >>> importstr('math', 'fabs')
  42. <built-in function fabs>
  43. """
  44. if from_ is None and ':' in module_str:
  45. module_str, from_ = module_str.rsplit(':')
  46. module = __import__(module_str)
  47. for sub_str in module_str.split('.')[1:]:
  48. module = getattr(module, sub_str)
  49. if from_:
  50. try:
  51. return getattr(module, from_)
  52. except:
  53. raise ImportError('{}.{}'.format(module_str, from_))
  54. return module
  55. # class dotdict(dict):
  56. # '''dict where key can be access as attribute d.key -> d[key]'''
  57. # @classmethod
  58. # def deep(cls, dic_obj):
  59. # '''Initialize from dict with deep conversion'''
  60. # return cls(dic_obj).deepConvert()
  61. #
  62. # def __getattr__(self, attr):
  63. # if attr in self:
  64. # return self[attr]
  65. # log.error(sorted(self.keys()))
  66. # raise AttributeError(attr)
  67. # #return self.get(attr, None)
  68. # __setattr__= dict.__setitem__
  69. # __delattr__= dict.__delitem__
  70. #
  71. #
  72. # def __copy__(self):
  73. # return dotdict(self)
  74. #
  75. # def __deepcopy__(self, memo):
  76. # new_dict = dotdict()
  77. # for k, v in self.items():
  78. # new_dict[k] = copy.deepcopy(v, memo)
  79. # return new_dict
  80. #
  81. # # pylint: disable=multiple-statements
  82. # def __getstate__(self): return self.__dict__
  83. # def __setstate__(self, d): self.__dict__.update(d)
  84. #
  85. # def deepConvert(self):
  86. # '''Convert all dicts at all tree levels into dotdict'''
  87. # for k, v in self.items():
  88. # if type(v) is dict: # pylint: disable=unidiomatic-typecheck
  89. # self[k] = dotdict(v)
  90. # self[k].deepConvert()
  91. # try: # try enumerable types
  92. # for m, x in enumerate(v):
  93. # if type(x) is dict: # pylint: disable=unidiomatic-typecheck
  94. # x = dotdict(x)
  95. # x.deepConvert()
  96. # v[m] = x#
  97. # except TypeError:
  98. # pass
  99. # return self
  100. #
  101. # def copy(self):
  102. # # override dict.copy()
  103. # return dotdict(self)
  104. def prhist(ary, prefix_str=None, **kwargs):
  105. if prefix_str is None:
  106. prefix_str = ''
  107. else:
  108. prefix_str += ' '
  109. count_ary, bins_ary = np.histogram(ary, **kwargs)
  110. for i in range(count_ary.shape[0]):
  111. print("{}{:-8.2f}".format(prefix_str, bins_ary[i]), "{:-10}".format(count_ary[i]))
  112. print("{}{:-8.2f}".format(prefix_str, bins_ary[-1]))
  113. # def dumpCuda():
  114. # # small_count = 0
  115. # total_bytes = 0
  116. # size2count_dict = collections.defaultdict(int)
  117. # size2bytes_dict = {}
  118. # for obj in gc.get_objects():
  119. # if isinstance(obj, torch.cuda._CudaBase):
  120. # nbytes = 4
  121. # for n in obj.size():
  122. # nbytes *= n
  123. #
  124. # size2count_dict[tuple([obj.get_device()] + list(obj.size()))] += 1
  125. # size2bytes_dict[tuple([obj.get_device()] + list(obj.size()))] = nbytes
  126. #
  127. # total_bytes += nbytes
  128. #
  129. # # print(small_count, "tensors equal to or less than than 16 bytes")
  130. # for size, count in sorted(size2count_dict.items(), key=lambda sc: (size2bytes_dict[sc[0]] * sc[1], sc[1], sc[0])):
  131. # print('{:4}x'.format(count), '{:10,}'.format(size2bytes_dict[size]), size)
  132. # print('{:10,}'.format(total_bytes), "total bytes")
  133. def enumerateWithEstimate(iter, desc_str, start_ndx=0, print_ndx=4, backoff=2, iter_len=None):
  134. """
  135. In terms of behavior, `enumerateWithEstimate` is almost identical
  136. to the standard `enumerate` (the differences are things like how
  137. our function returns a generator, while `enumerate` returns a
  138. specialized `<enumerate object at 0x...>`).
  139. However, the side effects (logging, specifically) are what make the
  140. function interesting.
  141. :param iter: `iter` is the iterable that will be passed into
  142. `enumerate`. Required.
  143. :param desc_str: This is a human-readable string that describes
  144. what the loop is doing. The value is arbitrary, but should be
  145. kept reasonably short. Things like `"epoch 4 training"` or
  146. `"deleting temp files"` or similar would all make sense.
  147. :param start_ndx: This parameter defines how many iterations of the
  148. loop should be skipped before timing actually starts. Skipping
  149. a few iterations can be useful if there are startup costs like
  150. caching that are only paid early on, resulting in a skewed
  151. average when those early iterations dominate the average time
  152. per iteration.
  153. NOTE: Using `start_ndx` to skip some iterations makes the time
  154. spent performing those iterations not be included in the
  155. displayed duration. Please account for this if you use the
  156. displayed duration for anything formal.
  157. This parameter defaults to `0`.
  158. :param print_ndx: determines which loop interation that the timing
  159. logging will start on. The intent is that we don't start
  160. logging until we've given the loop a few iterations to let the
  161. average time-per-iteration a chance to stablize a bit. We
  162. require that `print_ndx` not be less than `start_ndx` times
  163. `backoff`, since `start_ndx` greater than `0` implies that the
  164. early N iterations are unstable from a timing perspective.
  165. `print_ndx` defaults to `4`.
  166. :param backoff: This is used to how many iterations to skip before
  167. logging again. Frequent logging is less interesting later on,
  168. so by default we double the gap between logging messages each
  169. time after the first.
  170. `backoff` defaults to `2`.
  171. :param iter_len: Since we need to know the number of items to
  172. estimate when the loop will finish, that can be provided by
  173. passing in a value for `iter_len`. If a value isn't provided,
  174. then it will be set by using the value of `len(iter)`.
  175. :return:
  176. """
  177. if iter_len is None:
  178. iter_len = len(iter)
  179. assert backoff >= 2
  180. while print_ndx < start_ndx * backoff:
  181. print_ndx *= backoff
  182. log.warning("{} ----/{}, starting".format(
  183. desc_str,
  184. iter_len,
  185. ))
  186. start_ts = time.time()
  187. for (current_ndx, item) in enumerate(iter):
  188. yield (current_ndx, item)
  189. if current_ndx == print_ndx:
  190. # ... <1>
  191. duration_sec = ((time.time() - start_ts)
  192. / (current_ndx - start_ndx + 1)
  193. * (iter_len-start_ndx)
  194. )
  195. done_dt = datetime.datetime.fromtimestamp(start_ts + duration_sec)
  196. done_td = datetime.timedelta(seconds=duration_sec)
  197. log.info("{} {:-4}/{}, done at {}, {}".format(
  198. desc_str,
  199. current_ndx,
  200. iter_len,
  201. str(done_dt).rsplit('.', 1)[0],
  202. str(done_td).rsplit('.', 1)[0],
  203. ))
  204. print_ndx *= backoff
  205. if current_ndx + 1 == start_ndx:
  206. start_ts = time.time()
  207. log.warning("{} ----/{}, done at {}".format(
  208. desc_str,
  209. iter_len,
  210. str(datetime.datetime.now()).rsplit('.', 1)[0],
  211. ))
  212. #
  213. # try:
  214. # import matplotlib
  215. # matplotlib.use('agg', warn=False)
  216. #
  217. # import matplotlib.pyplot as plt
  218. # # matplotlib color maps
  219. # cdict = {'red': ((0.0, 1.0, 1.0),
  220. # # (0.5, 1.0, 1.0),
  221. # (1.0, 1.0, 1.0)),
  222. #
  223. # 'green': ((0.0, 0.0, 0.0),
  224. # (0.5, 0.0, 0.0),
  225. # (1.0, 0.5, 0.5)),
  226. #
  227. # 'blue': ((0.0, 0.0, 0.0),
  228. # # (0.5, 0.5, 0.5),
  229. # # (0.75, 0.0, 0.0),
  230. # (1.0, 0.0, 0.0)),
  231. #
  232. # 'alpha': ((0.0, 0.0, 0.0),
  233. # (0.75, 0.5, 0.5),
  234. # (1.0, 0.5, 0.5))}
  235. #
  236. # plt.register_cmap(name='mask', data=cdict)
  237. #
  238. # cdict = {'red': ((0.0, 0.0, 0.0),
  239. # (0.25, 1.0, 1.0),
  240. # (1.0, 1.0, 1.0)),
  241. #
  242. # 'green': ((0.0, 1.0, 1.0),
  243. # (0.25, 1.0, 1.0),
  244. # (0.5, 0.0, 0.0),
  245. # (1.0, 0.0, 0.0)),
  246. #
  247. # 'blue': ((0.0, 0.0, 0.0),
  248. # # (0.5, 0.5, 0.5),
  249. # # (0.75, 0.0, 0.0),
  250. # (1.0, 0.0, 0.0)),
  251. #
  252. # 'alpha': ((0.0, 0.15, 0.15),
  253. # (0.5, 0.3, 0.3),
  254. # (0.8, 0.0, 0.0),
  255. # (1.0, 0.0, 0.0))}
  256. #
  257. # plt.register_cmap(name='maskinvert', data=cdict)
  258. # except ImportError:
  259. # pass