util.py 9.9 KB

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