timing.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. from collections import namedtuple
  2. from math import floor
  3. from typing import Callable
  4. TimeDisplay = namedtuple('TimeDisplay',
  5. 'round, sec_prec, min_prec, hour_prec, prefix, '
  6. 'round_sec_on_min, clear_sec_on_hour')
  7. RUN = TimeDisplay(0, .0, 2.0, 2.0, '', False, False)
  8. END = TimeDisplay(1, .1, 4.1, 4.1, '', False, False)
  9. ETA = RUN._replace(prefix='~', round_sec_on_min=True, clear_sec_on_hour=True)
  10. def time_display(seconds: float, conf: TimeDisplay) -> str:
  11. seconds = round(seconds, conf.round)
  12. if seconds < 60.:
  13. return '{}{:{}f}s'.format(conf.prefix, seconds, conf.sec_prec)
  14. minutes, seconds = divmod(seconds, 60.)
  15. if minutes < 60.:
  16. if conf.round_sec_on_min:
  17. seconds = floor(seconds / 10) * 10
  18. return '{}{:.0f}:{:0{}f}'.format(conf.prefix, minutes, seconds, conf.min_prec)
  19. hours, minutes = divmod(minutes, 60.)
  20. if conf.clear_sec_on_hour:
  21. seconds = 0
  22. return '{}{:.0f}:{:02.0f}:{:0{}f}'.format(conf.prefix, hours, minutes, seconds, conf.hour_prec)
  23. def eta_text(seconds: float) -> str:
  24. if seconds < 0.:
  25. return '?'
  26. return time_display(seconds, ETA)
  27. def fn_simple_eta(logic_total):
  28. def simple_eta(pos, rate):
  29. return (logic_total - pos) / rate
  30. return simple_eta
  31. def gen_simple_exponential_smoothing(alpha: float, fn: Callable[[float, float], float]):
  32. """Implements a generator with a simple exponential smoothing of some function.
  33. Given alpha and y_hat (t-1), we can calculate the next y_hat:
  34. y_hat = alpha * y + (1 - alpha) * y_hat
  35. y_hat = alpha * y + y_hat - alpha * y_hat
  36. y_hat = y_hat + alpha * (y - y_hat)
  37. Args:
  38. alpha: the smoothing coefficient
  39. fn: the function
  40. Returns:
  41. """
  42. p = (0.,)
  43. while any(x == 0. for x in p):
  44. p = yield 0.
  45. y_hat = fn(*p)
  46. while True:
  47. p = yield y_hat
  48. y = fn(*p)
  49. y_hat += alpha * (y - y_hat)