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.
 
 
 
 

188 lines
5.8 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. # Parse arguments
  19. try:
  20. args = f.parse_args(argv)
  21. except nilmtools.filter.MissingDestination as e:
  22. rec = "float32_4"
  23. print "Source is %s (%s)" % (e.src.path, e.src.layout)
  24. print "Destination %s doesn't exist" % (e.dest.path)
  25. print "You could make it with a command like:"
  26. print " nilmtool -u %s create %s %s" % (e.dest.url, e.dest.path, rec)
  27. raise SystemExit(1)
  28. if args.column is None or args.column < 1:
  29. parser.error("need a column number >= 1")
  30. if args.frequency < 0.1:
  31. parser.error("frequency must be >= 0.1")
  32. f.check_dest_metadata({ "sinefit_source": f.src.path,
  33. "sinefit_column": args.column })
  34. f.process_numpy(process, args = (args.column, args.frequency))
  35. def process(data, interval, args, insert_function, final):
  36. (column, f_expected) = args
  37. rows = data.shape[0]
  38. # Estimate sampling frequency from timestamps
  39. fs = 1e6 * (rows-1) / (data[-1][0] - data[0][0])
  40. # Pull out about 3.5 periods of data at once;
  41. # we'll expect to match 3 zero crossings in each window
  42. N = max(int(3.5 * fs / f_expected), 10)
  43. # If we don't have enough data, don't bother processing it
  44. if rows < N:
  45. return 0
  46. # Process overlapping windows
  47. start = 0
  48. num_zc = 0
  49. while start < (rows - N):
  50. this = data[start:start+N, column]
  51. t_min = data[start, 0]/1e6
  52. t_max = data[start+N-1, 0]/1e6
  53. # Do 4-parameter sine wave fit
  54. (A, f0, phi, C) = sfit4(this, fs)
  55. # Check bounds. If frequency is too crazy, ignore this window
  56. if f0 < (f_expected/2) or f0 > (f_expected*2):
  57. print "frequency", f0, "too far from expected value", f_expected
  58. start += N
  59. continue
  60. #p.plot(arange(N), this)
  61. #p.plot(arange(N), A * cos(f0/fs * 2 * pi * arange(N) + phi) + C, 'g')
  62. # Period starts when the argument of cosine is 3*pi/2 degrees,
  63. # so we're looking for sample number:
  64. # n = (3 * pi / 2 - phi) / (f0/fs * 2 * pi)
  65. zc_n = (3 * pi / 2 - phi) / (f0 / fs * 2 * pi)
  66. period_n = fs/f0
  67. # Add periods to make N positive
  68. while zc_n < 0:
  69. zc_n += period_n
  70. last_zc = None
  71. # Mark the zero crossings until we're a half period away
  72. # from the end of the window
  73. while zc_n < (N - period_n/2):
  74. #p.plot(zc_n, C, 'ro')
  75. t = t_min + zc_n / fs
  76. insert_function([[t * 1e6, f0, A, C]])
  77. num_zc += 1
  78. last_zc = zc_n
  79. zc_n += period_n
  80. # Advance the window one quarter period past the last marked
  81. # zero crossing, or advance the window by half its size if we
  82. # didn't mark any.
  83. if last_zc is not None:
  84. advance = min(last_zc + period_n/4, N)
  85. else:
  86. advance = N/2
  87. #p.plot(advance, C, 'go')
  88. #p.show()
  89. start = int(round(start + advance))
  90. # Return the number of rows we've processed
  91. print "Marked", num_zc, "zero-crossings in", start, "rows"
  92. return start
  93. def sfit4(data, fs):
  94. """(A, f0, phi, C) = sfit4(data, fs)
  95. Compute 4-parameter (unknown-frequency) least-squares fit to
  96. sine-wave data, according to IEEE Std 1241-2010 Annex B
  97. Input:
  98. data vector of input samples
  99. fs sampling rate (Hz)
  100. Output:
  101. Parameters [A, f0, phi, C] to fit the equation
  102. x[n] = A * cos(f0/fs * 2 * pi * n + phi) + C
  103. where n is sample number. Or, as a function of time:
  104. x(t) = A * cos(f0 * 2 * pi * t + phi) + C
  105. by Jim Paris
  106. (Verified to match sfit4.m)
  107. """
  108. N = len(data)
  109. t = linspace(0, (N-1) / fs, N)
  110. ## Estimate frequency using FFT (step b)
  111. Fc = fft(data)
  112. F = abs(Fc)
  113. F[0] = 0 # eliminate DC
  114. # Find pair of spectral lines with largest amplitude:
  115. # resulting values are in F(i) and F(i+1)
  116. i = argmax(F[0:int(N/2)] + F[1:int(N/2+1)])
  117. # Interpolate FFT to get a better result (from Markus [B37])
  118. U1 = real(Fc[i])
  119. U2 = real(Fc[i+1])
  120. V1 = imag(Fc[i])
  121. V2 = imag(Fc[i+1])
  122. n = 2 * pi / N
  123. ni1 = n * i
  124. ni2 = n * (i+1)
  125. K = ((V2-V1)*sin(ni1) + (U2-U1)*cos(ni1)) / (U2-U1)
  126. Z1 = V1 * (K - cos(ni1)) / sin(ni1) + U1
  127. Z2 = V2 * (K - cos(ni2)) / sin(ni2) + U2
  128. i = arccos((Z2*cos(ni2) - Z1*cos(ni1)) / (Z2-Z1)) / n
  129. # Convert to Hz
  130. f0 = i * fs / N
  131. ## Fit it
  132. # first guess for A0, B0 using 3-parameter fit (step c)
  133. w = 2*pi*f0
  134. D = c_[cos(w*t), sin(w*t), ones(N)]
  135. s = linalg.lstsq(D, data)[0]
  136. # Now iterate 6 times (step i)
  137. for idx in range(6):
  138. D = c_[cos(w*t), sin(w*t), ones(N),
  139. -s[0] * t * sin(w*t) + s[1] * t * cos(w*t) ] # eqn B.16
  140. s = linalg.lstsq(D, data)[0] # eqn B.18
  141. w = w + s[3] # update frequency estimate
  142. ## Extract results
  143. A = sqrt(s[0]*s[0] + s[1]*s[1]) # eqn B.21
  144. f0 = w / (2*pi)
  145. try:
  146. phi = -arctan2(s[1], s[0]) # eqn B.22
  147. except TypeError:
  148. # something broke down, just return zeros
  149. return (0, 0, 0, 0)
  150. C = s[2]
  151. return (A, f0, phi, C)
  152. if __name__ == "__main__":
  153. main()