You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

sinefit.py 6.9 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. #!/usr/bin/python
  2. # Sine wave fitting.
  3. from nilmdb.utils.printf import *
  4. import nilmtools.filter
  5. import nilmtools.math
  6. import nilmdb.client
  7. from nilmdb.utils.time import (timestamp_to_human,
  8. timestamp_to_seconds,
  9. seconds_to_timestamp)
  10. from numpy import *
  11. from scipy import *
  12. #import pylab as p
  13. import sys
  14. def main(argv = None):
  15. f = nilmtools.filter.Filter()
  16. parser = f.setup_parser("Sine wave fitting")
  17. group = parser.add_argument_group("Sine fit options")
  18. group.add_argument('-c', '--column', action='store', type=int,
  19. help='Column number (first data column is 1)')
  20. group.add_argument('-f', '--frequency', action='store', type=float,
  21. default=60.0,
  22. help='Approximate frequency (default: %(default)s)')
  23. group.add_argument('-m', '--min-freq', action='store', type=float,
  24. help='Minimum valid frequency '
  25. '(default: approximate frequency / 2))')
  26. group.add_argument('-M', '--max-freq', action='store', type=float,
  27. help='Maximum valid frequency '
  28. '(default: approximate frequency * 2))')
  29. group.add_argument('-a', '--min-amp', action='store', type=float,
  30. default=20.0,
  31. help='Minimum signal amplitude (default: %(default)s)')
  32. # Parse arguments
  33. try:
  34. args = f.parse_args(argv)
  35. except nilmtools.filter.MissingDestination as e:
  36. rec = "float32_3"
  37. print("Source is %s (%s)" % (e.src.path, e.src.layout))
  38. print("Destination %s doesn't exist" % (e.dest.path))
  39. print("You could make it with a command like:")
  40. print(" nilmtool -u %s create %s %s" % (e.dest.url, e.dest.path, rec))
  41. raise SystemExit(1)
  42. if args.column is None or args.column < 1:
  43. parser.error("need a column number >= 1")
  44. if args.frequency < 0.1:
  45. parser.error("frequency must be >= 0.1")
  46. if args.min_freq is None:
  47. args.min_freq = args.frequency / 2
  48. if args.max_freq is None:
  49. args.max_freq = args.frequency * 2
  50. if (args.min_freq > args.max_freq or
  51. args.min_freq > args.frequency or
  52. args.max_freq < args.frequency):
  53. parser.error("invalid min or max frequency")
  54. if args.min_amp < 0:
  55. parser.error("min amplitude must be >= 0")
  56. f.check_dest_metadata({ "sinefit_source": f.src.path,
  57. "sinefit_column": args.column })
  58. f.process_numpy(process, args = (args.column, args.frequency, args.min_amp,
  59. args.min_freq, args.max_freq))
  60. class SuppressibleWarning(object):
  61. def __init__(self, maxcount = 10, maxsuppress = 100):
  62. self.maxcount = maxcount
  63. self.maxsuppress = maxsuppress
  64. self.count = 0
  65. self.last_msg = ""
  66. def _write(self, sec, msg):
  67. if sec:
  68. now = timestamp_to_human(seconds_to_timestamp(sec)) + ": "
  69. else:
  70. now = ""
  71. sys.stderr.write(now + msg)
  72. def warn(self, msg, seconds = None):
  73. self.count += 1
  74. if self.count <= self.maxcount:
  75. self._write(seconds, msg)
  76. if (self.count - self.maxcount) >= self.maxsuppress:
  77. self.reset(seconds)
  78. def reset(self, seconds = None):
  79. if self.count > self.maxcount:
  80. self._write(seconds, sprintf("(%d warnings suppressed)\n",
  81. self.count - self.maxcount))
  82. self.count = 0
  83. def process(data, interval, args, insert_function, final):
  84. (column, f_expected, a_min, f_min, f_max) = args
  85. rows = data.shape[0]
  86. # Estimate sampling frequency from timestamps
  87. ts_min = timestamp_to_seconds(data[0][0])
  88. ts_max = timestamp_to_seconds(data[-1][0])
  89. if ts_min >= ts_max:
  90. return 0
  91. fs = (rows-1) / (ts_max - ts_min)
  92. # Pull out about 3.5 periods of data at once;
  93. # we'll expect to match 3 zero crossings in each window
  94. N = max(int(3.5 * fs / f_expected), 10)
  95. # If we don't have enough data, don't bother processing it
  96. if rows < N:
  97. return 0
  98. warn = SuppressibleWarning(3, 1000)
  99. # Process overlapping windows
  100. start = 0
  101. num_zc = 0
  102. last_inserted_timestamp = None
  103. while start < (rows - N):
  104. this = data[start:start+N, column]
  105. t_min = timestamp_to_seconds(data[start, 0])
  106. t_max = timestamp_to_seconds(data[start+N-1, 0])
  107. # Do 4-parameter sine wave fit
  108. (A, f0, phi, C) = nilmtools.math.sfit4(this, fs)
  109. # Check bounds. If frequency is too crazy, ignore this window
  110. if f0 < f_min or f0 > f_max:
  111. warn.warn(sprintf("frequency %s outside valid range %s - %s\n",
  112. str(f0), str(f_min), str(f_max)), t_min)
  113. start += N
  114. continue
  115. # If amplitude is too low, results are probably just noise
  116. if A < a_min:
  117. warn.warn(sprintf("amplitude %s below minimum threshold %s\n",
  118. str(A), str(a_min)), t_min)
  119. start += N
  120. continue
  121. #p.plot(arange(N), this)
  122. #p.plot(arange(N), A * sin(f0/fs * 2 * pi * arange(N) + phi) + C, 'g')
  123. # Period starts when the argument of sine is 0 degrees,
  124. # so we're looking for sample number:
  125. # n = (0 - phi) / (f0/fs * 2 * pi)
  126. zc_n = (0 - phi) / (f0 / fs * 2 * pi)
  127. period_n = fs/f0
  128. # Add periods to make N positive
  129. while zc_n < 0:
  130. zc_n += period_n
  131. last_zc = None
  132. # Mark the zero crossings until we're a half period away
  133. # from the end of the window
  134. while zc_n < (N - period_n/2):
  135. #p.plot(zc_n, C, 'ro')
  136. t = t_min + zc_n / fs
  137. if (last_inserted_timestamp is None or
  138. t > last_inserted_timestamp):
  139. insert_function([[seconds_to_timestamp(t), f0, A, C]])
  140. last_inserted_timestamp = t
  141. warn.reset(t)
  142. else:
  143. warn.warn("timestamp overlap\n", t)
  144. num_zc += 1
  145. last_zc = zc_n
  146. zc_n += period_n
  147. # Advance the window one quarter period past the last marked
  148. # zero crossing, or advance the window by half its size if we
  149. # didn't mark any.
  150. if last_zc is not None:
  151. advance = min(last_zc + period_n/4, N)
  152. else:
  153. advance = N/2
  154. #p.plot(advance, C, 'go')
  155. #p.show()
  156. start = int(round(start + advance))
  157. # Return the number of rows we've processed
  158. warn.reset(last_inserted_timestamp)
  159. if last_inserted_timestamp:
  160. now = timestamp_to_human(seconds_to_timestamp(
  161. last_inserted_timestamp)) + ": "
  162. else:
  163. now = ""
  164. printf("%sMarked %d zero-crossings in %d rows\n", now, num_zc, start)
  165. return start
  166. if __name__ == "__main__":
  167. main()