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.
 
 
 
 

186 lines
5.7 KiB

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