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.
 
 
 
 

213 lines
7.2 KiB

  1. #!/usr/bin/python
  2. # Sine wave fitting. This runs about 5x faster than realtime on raw data.
  3. import nilmtools.filter
  4. import nilmdb.client
  5. from numpy import *
  6. from scipy import *
  7. #import pylab as p
  8. import operator
  9. def main(argv = None):
  10. f = nilmtools.filter.Filter()
  11. parser = f.setup_parser("Sine wave fitting")
  12. group = parser.add_argument_group("Sine fit options")
  13. group.add_argument('-c', '--column', action='store', type=int,
  14. help='Column number (first data column is 1)')
  15. group.add_argument('-f', '--frequency', action='store', type=float,
  16. default=60.0,
  17. help='Approximate frequency (default: %(default)s)')
  18. group.add_argument('-m', '--min-freq', action='store', type=float,
  19. help='Minimum valid frequency '
  20. '(default: approximate frequency / 2))')
  21. group.add_argument('-M', '--max-freq', action='store', type=float,
  22. help='Maximum valid frequency '
  23. '(default: approximate frequency * 2))')
  24. group.add_argument('-a', '--min-amp', action='store', type=float,
  25. default=20.0,
  26. help='Minimum signal amplitude (default: %(default)s)')
  27. # Parse arguments
  28. try:
  29. args = f.parse_args(argv)
  30. except nilmtools.filter.MissingDestination as e:
  31. rec = "float32_3"
  32. print "Source is %s (%s)" % (e.src.path, e.src.layout)
  33. print "Destination %s doesn't exist" % (e.dest.path)
  34. print "You could make it with a command like:"
  35. print " nilmtool -u %s create %s %s" % (e.dest.url, e.dest.path, rec)
  36. raise SystemExit(1)
  37. if args.column is None or args.column < 1:
  38. parser.error("need a column number >= 1")
  39. if args.frequency < 0.1:
  40. parser.error("frequency must be >= 0.1")
  41. if args.min_freq is None:
  42. args.min_freq = args.frequency / 2
  43. if args.max_freq is None:
  44. args.max_freq = args.frequency * 2
  45. if (args.min_freq > args.max_freq or
  46. args.min_freq > args.frequency or
  47. args.max_freq < args.frequency):
  48. parser.error("invalid min or max frequency")
  49. if args.min_amp < 0:
  50. parser.error("min amplitude must be >= 0")
  51. f.check_dest_metadata({ "sinefit_source": f.src.path,
  52. "sinefit_column": args.column })
  53. f.process_numpy(process, args = (args.column, args.frequency, args.min_amp,
  54. args.min_freq, args.max_freq))
  55. def process(data, interval, args, insert_function, final):
  56. (column, f_expected, a_min, f_min, f_max) = args
  57. rows = data.shape[0]
  58. # Estimate sampling frequency from timestamps
  59. fs = 1e6 * (rows-1) / (data[-1][0] - data[0][0])
  60. # Pull out about 3.5 periods of data at once;
  61. # we'll expect to match 3 zero crossings in each window
  62. N = max(int(3.5 * fs / f_expected), 10)
  63. # If we don't have enough data, don't bother processing it
  64. if rows < N:
  65. return 0
  66. # Process overlapping windows
  67. start = 0
  68. num_zc = 0
  69. while start < (rows - N):
  70. this = data[start:start+N, column]
  71. t_min = data[start, 0]/1e6
  72. t_max = data[start+N-1, 0]/1e6
  73. # Do 4-parameter sine wave fit
  74. (A, f0, phi, C) = sfit4(this, fs)
  75. # Check bounds. If frequency is too crazy, ignore this window
  76. if f0 < f_min or f0 > f_max:
  77. print "frequency", f0, "outside valid range", f_min, "-", f_max
  78. start += N
  79. continue
  80. # If amplitude is too low, results are probably just noise
  81. if A < a_min:
  82. print "amplitude", A, "below minimum threshold", a_min
  83. start += N
  84. continue
  85. #p.plot(arange(N), this)
  86. #p.plot(arange(N), A * sin(f0/fs * 2 * pi * arange(N) + phi) + C, 'g')
  87. # Period starts when the argument of sine is 0 degrees,
  88. # so we're looking for sample number:
  89. # n = (0 - phi) / (f0/fs * 2 * pi)
  90. zc_n = (0 - phi) / (f0 / fs * 2 * pi)
  91. period_n = fs/f0
  92. # Add periods to make N positive
  93. while zc_n < 0:
  94. zc_n += period_n
  95. last_zc = None
  96. # Mark the zero crossings until we're a half period away
  97. # from the end of the window
  98. while zc_n < (N - period_n/2):
  99. #p.plot(zc_n, C, 'ro')
  100. t = t_min + zc_n / fs
  101. insert_function([[t * 1e6, f0, A, C]])
  102. num_zc += 1
  103. last_zc = zc_n
  104. zc_n += period_n
  105. # Advance the window one quarter period past the last marked
  106. # zero crossing, or advance the window by half its size if we
  107. # didn't mark any.
  108. if last_zc is not None:
  109. advance = min(last_zc + period_n/4, N)
  110. else:
  111. advance = N/2
  112. #p.plot(advance, C, 'go')
  113. #p.show()
  114. start = int(round(start + advance))
  115. # Return the number of rows we've processed
  116. print "Marked", num_zc, "zero-crossings in", start, "rows"
  117. return start
  118. def sfit4(data, fs):
  119. """(A, f0, phi, C) = sfit4(data, fs)
  120. Compute 4-parameter (unknown-frequency) least-squares fit to
  121. sine-wave data, according to IEEE Std 1241-2010 Annex B
  122. Input:
  123. data vector of input samples
  124. fs sampling rate (Hz)
  125. Output:
  126. Parameters [A, f0, phi, C] to fit the equation
  127. x[n] = A * sin(f0/fs * 2 * pi * n + phi) + C
  128. where n is sample number. Or, as a function of time:
  129. x(t) = A * sin(f0 * 2 * pi * t + phi) + C
  130. by Jim Paris
  131. (Verified to match sfit4.m)
  132. """
  133. N = len(data)
  134. t = linspace(0, (N-1) / float(fs), N)
  135. ## Estimate frequency using FFT (step b)
  136. Fc = fft(data)
  137. F = abs(Fc)
  138. F[0] = 0 # eliminate DC
  139. # Find pair of spectral lines with largest amplitude:
  140. # resulting values are in F(i) and F(i+1)
  141. i = argmax(F[0:int(N/2)] + F[1:int(N/2+1)])
  142. # Interpolate FFT to get a better result (from Markus [B37])
  143. U1 = real(Fc[i])
  144. U2 = real(Fc[i+1])
  145. V1 = imag(Fc[i])
  146. V2 = imag(Fc[i+1])
  147. n = 2 * pi / N
  148. ni1 = n * i
  149. ni2 = n * (i+1)
  150. K = ((V2-V1)*sin(ni1) + (U2-U1)*cos(ni1)) / (U2-U1)
  151. Z1 = V1 * (K - cos(ni1)) / sin(ni1) + U1
  152. Z2 = V2 * (K - cos(ni2)) / sin(ni2) + U2
  153. i = arccos((Z2*cos(ni2) - Z1*cos(ni1)) / (Z2-Z1)) / n
  154. # Convert to Hz
  155. f0 = i * float(fs) / N
  156. # Fit it. We'll catch exceptions here and just returns zeros
  157. # if something fails with the least squares fit, etc.
  158. try:
  159. # first guess for A0, B0 using 3-parameter fit (step c)
  160. s = zeros(3)
  161. w = 2*pi*f0
  162. # Now iterate 7 times (step b, plus 6 iterations of step i)
  163. for idx in range(7):
  164. D = c_[cos(w*t), sin(w*t), ones(N),
  165. -s[0] * t * sin(w*t) + s[1] * t * cos(w*t) ] # eqn B.16
  166. s = linalg.lstsq(D, data)[0] # eqn B.18
  167. w = w + s[3] # update frequency estimate
  168. ## Extract results
  169. A = sqrt(s[0]*s[0] + s[1]*s[1]) # eqn B.21
  170. f0 = w / (2*pi)
  171. phi = arctan2(s[0], s[1]) # eqn B.22 (flipped for sin instead of cos)
  172. C = s[2]
  173. return (A, f0, phi, C)
  174. except Exception as e:
  175. # something broke down, just return zeros
  176. return (0, 0, 0, 0)
  177. if __name__ == "__main__":
  178. main()