Friday, November 2, 2018

fft - Piano pitch detection



I'm working on a piano tuning program and part of it requires real-time pitch detection. Here is the scheme I have so far which works to some degree but could probably use some refinement.


I'm capturing mono, 44.1kHz, 16-bit PCM audio in chunks of 2^14 samples. I combine the last 4 samples into a 2^16 length buffer, apply a Hann window to the buffer and run a FFT on it. Then, I bucketize the results of the FFT in two resolutions. First, I bucketize into 200 buckets and then run the HPS pitch detection algorithm at this granularity. I don't need to get an exact frequency here, I just want to get close. Then, I bucketize into 12000 buckets which gives me 1 cent resolution from 10Hz to 10kHz. Once I know an approximate frequency from the 200 bin HPS algorithm, I search that range of the 12000 bin case for a peak to get a more exact frequency.


This seems to work okay for the notes in the middle of the keyboard. What happens with the low notes is about 1.5s of mis-identification of the note as usually the 2nd or 3rd partial of the real note and then a correct identification of the note.


In all of the spectral plots I created to see what is going on, there is more width to the peaks that I would expect. This width is visually somewhat consistent from the 200 bin to 12000 bin case. I would have expected the peaks to be narrower in the 200 bin case.


So, signal processing is new to me so there may be things that are problems that I wouldn't think to ask about but in terms of specific questions, are the sample sizes sufficient for this task? Is Hann the right choice of window? Should I smooth the data as well before FFT? How sensitive is HPS to the number of bins? I was thinking that if I used a lot of bins then inharmonicity might not make partials overlap their fundamentals with the HPS algorithm's simple approach of dividing by 2, 3, 4, etc.




havdalah - Pre existing flame for Havdala after Yom Kippur


Doe anyone know the reasoning for the requirement to use a flame that was lit over Yom Kippur for Havdala?



Answer



Based on Shulchan Aruch Harav, Section 624:4 - 624:5.


Just like on Shabbos, after Yom Kippur we make a Bracha on fire since we were not permitted to use fire before, and it is like a new entity to us.


After Shabbos we may use new fire because this is how fire was initially brought into the world after Shabbos Adam took two stones and made fire and made the bracha.


But this does not apply after Yom Kippur, so we must make a bracha only on fire the rested throughout the day of Yom Kippur.




4. However, a blessing must be recited over fire even when [Yom Kippur] falls on a weekday, [thereby indicating that] it is a new entity from which we did not benefit on Yom Kippur, for it is forbidden to light fire [on that day]. Therefore [the night after Yom Kippur] is different from the night after any other festival, when a blessing is not recited over [fire].


[The rationale is that] a blessing is recited over fire only at the time when it was brought into being, i.e., on the night after Shabbos, when fire was first created, or on the night after Yom Kippur, when fire is like a new entity for us, as was explained above.


5. On the night after Yom Kippur, the blessing is not recited over fire that was produced [that night] from flint or wood, nor over fire that was kindled from such fire, but only over fire that "rested" from work, such as a lamp that has been alight since the eve of Yom Kippur.


On the night after [any] Shabbos, a blessing may be recited over fire that was produced from flint or wood, because it was in this manner that fire was originally created on the night after [the first] Shabbos. As [our Sages relate, on the night after the first Shabbos of creation] Adam took two stones, struck them together, brought forth fire, and recited the blessing borei meorei ha'esh, [praising G-d as "the Creator of the lights of fire"]. Hence on the night following [any] Shabbos, the blessing may be recited over any fire (unless it was used for forbidden labor on Shabbos, as stated in sec. 298[:7]) - even over fire produced at that time from flint, for this resembles the way it was originally brought into being.


On the night after Yom Kippur, by contrast, the reason for this blessing is that one was unable to benefit [from fire] on that day, and now this is permitted. Hence, the blessing should be recited only over fire that actually "rested," i.e., that was kindled on the day before Yom Kippur and "rested" throughout the day of Yom Kippur. Even when Yom Kippur falls on Shabbos, the blessing should be recited - at night, at the close of the holy day - only over fire that was kindled on the day before Yom Kippur and "rested" throughout the day of Yom Kippur, to show that this day was sanctified in that fire was not kindled during that time.



Kalman filter for position and velocity: introducing speed estimates


Thanks to everyone who posted comments/answers to my query yesterday (Implementing a Kalman filter for position, velocity, acceleration ). I've been looking at what was recommended, and in particular at both (a) the wikipedia example on one dimensional position and velocity and also another website that considers a similar thing.



Update 26-Apr-2013: the original question here contained some errors, related to the fact that I hadn't properly understood the the wikipedia example on one dimensional position and velocity. With my improved understanding of what's going on, I've now redrafted the question and focused it more tightly.


Both examples that I refer to in the introductory paragraph above assume that it's only position that's measured. However, neither example has any kind of calculation $(x_k-x_{k-1})/dt$ for speed. For example, the Wikipedia example specifies the ${\bf H}$ matrix as ${\bf H} = [1\ \ \ 0]$, which means that only position is input. Focussing on the Wikipedia example, the state vector ${\bf x}_k$ of the Kalman filter contains position $x_k$and speed $\dot{x}_{k}$, i.e.


$$ \begin{align*} \mathbf{x}_{k} & =\left(\begin{array}[c]{c}x_{k}\\ \dot{x}_{k}\end{array} \right) \end{align*} $$


Suppose the measurement of position at time $k$ is $\hat{x}_k$. Then if the position and speed at time $k-1$ were $x_{k-1}$ and $\dot{x}_{k-1}$, and if $a$ is a constant acceleration that applies in the time interval $k-1$ to $k$, from the measurement of $\hat{x}$ it's possible to deduce a value for $a$ using the formula


$$ \hat{x}_k = x_{k-1} + \dot{x}_{k-1} dt + \frac{1}{2} a dt^2 $$


This implies that at time $k$, a measurement $\hat{\dot{x}}_k$ of the speed is given by


$$ \hat{\dot{x}}_k = \dot{x}_{k-1} + a dt = 2 \frac{\hat{x}_k - {x}_{k-1}}{dt} - \dot{x}_{k-1} $$


All the quantities on the right hand side of that equation (i.e. $\hat{x}_k$, $x_{k-1}$ and $\dot{x}_{k-1}$) are normally distributed random variables with known means and standard deviations, so the $\bf R$ matrix for the measurement vector


$$ \begin{align*} \mathbf{\hat{x}}_{k} & =\left(\begin{array}[c]{c}\hat{x}_{k}\\ \hat{\dot{x}}_{k}\end{array} \right) \end{align*} $$


can be calculated. Is this a valid way of introducing speed estimates into the process?




Answer




Is this a valid way of introducing speed estimates into the process?



If you choose your state appropriately, then the speed estimates come "for free". See the derivation of the signal model below (for the simple 1-D case we've been looking at).


Signal Model, Take 2


So, we really need to agree on a signal model before we can move this forward. From your edit, it looks like your model of the position, $x_k$, is:


$$ \begin{array} xx_{k+1} &=& x_{k} + \dot{x}_{k} \Delta t + \frac{1}{2} a (\Delta t)^2\\ \dot{x}_{k+1} &=& \dot{x}_{k} + a \Delta t \end{array} $$


If our state is as before: $$ \begin{align*} \mathbf{x}_{k} & =\left(\begin{array}[c]{c}x_{k}\\ \dot{x}_{k}\end{array} \right) \end{align*} $$ then the state update equation is just: $$ \mathbf{x}_{k+1} = \left(\begin{array}[c]{c} 1\ \ \Delta t\\ 0\ \ 1\end{array} \right) \mathbf{x}_{k} + \left(\begin{array}[c]{c} \frac{(\Delta t)^2}{2} \\ \Delta t \end{array} \right) a_k $$ where now our $a_k$ is the normally distributed acceleration.


That gives different $\mathbf{G}$ matrix from the previous version, but the $\mathbf{F}$ and $\mathbf{H}$ matrices should be the same.





If I implement this in scilab (sorry, no access to matlab), it looks like:


// Signal Model
DeltaT = 0.1;
F = [1 DeltaT; 0 1];
G = [DeltaT^2/2; DeltaT];
H = [1 0];

x0 = [0;0];
sigma_a = 0.1;


Q = sigma_a^2;
R = 0.1;

N = 1000;

a = rand(1,N,"normal")*sigma_a;

x_truth(:,1) = x0;
for t=1:N,

x_truth(:,t+1) = F*x_truth(:,t) + G*a(t);
y(t) = H*x_truth(:,t) + rand(1,1,"normal")*sqrt(R);
end

Then, I can apply the Kalman filter equations to this $y$ (the noisy measurements).


// Kalman Filter
p0 = 100*eye(2,2);

xx(:,1) = x0;
pp = p0;

pp_norm(1) = norm(pp);
for t=1:N,
[x1,p1,x,p] = kalm(y(t),xx(:,t),pp,F,G,H,Q,R);
xx(:,t+1) = x1;
pp = p1;
pp_norm(t+1) = norm(pp);
end

So we have our noisy measurements $y$, and we've applied the Kalman filter to them and used the same signal model to generate $y$ as we do to apply the Kalman filter (a pretty big assumption, sometimes!).


Then following plots show the result.



Plot 1: $y$ and $x_k$ versus time.


enter image description here


Plot 2: A zoomed view of the first few samples:


enter image description here


Plot 3: Something you never get in real life, the true position vs the state estimate of the position.


enter image description here


Plot 4: Something you also never get in real life, the true velocity vs the state estimate of the velocity.


enter image description here


Plot 5: The norm of the state covariance matrix (something you should always monitor in real life!). Note that it very quickly goes from its initial very large value to something very small, so I've only shown the first few samples.


enter image description here



Plot 6: Plots of the error between the true position and velocity and their estimates.


enter image description here


If you study the case where the position measurements are exact, then you find that the Kalman udpate equations produce exact results for BOTH position and speed. Mathematically it's straightforward to see why. Using the same notation as the wikipedia article, exact measurements mean that $\mathbf{z}_{k+1}=x_{k+1}$. If you assume that the initial position and speed are known so that $\mathbf{P}_k=0$, then $\mathbf{P}_{k+1}^{-}=\mathbf{Q}$ and the Kalman gain matrix $\mathbf{K}_{k+1}$ is given by


$$ \mathbf{K}_{k+1} = \left(\begin{array}[c]{c}1\\ 2/dt\end{array} \right) $$


This means that the Kalman update procedure produces


$$ \begin{align*} \mathbf{\hat{x}}_{k+1} & = \mathbf{F}_{k+1}\mathbf{x}_k + \mathbf{K}_{k+1}\left(\mathbf{z}_{k+1} - \mathbf{H}_{k+1} \mathbf{F}_{k+1}\mathbf{x}_k\right)\\ & = \left(\begin{array}[c]{c}x_k + \dot{x}_k dt\\ \dot{x}_k\end{array} \right) + \left(\begin{array}[c]{c}1\\ 2/dt\end{array} \right) \left(x_{k+1} - \left( x_k + \dot{x}_k dt\right) \right)\\ & = \left(\begin{array}[c]{c}x_{k+1}\\ 2 \left(x_{k+1} - x_k \right) /dt - \dot{x}_k\end{array} \right) \end{align*} $$


As you can see, the value for the speed is given by exactly the formula you were proposing to use for the speed estimate. So although you couldn't see any kind of calculation $(x_k-x_{k-1})/dt$ for speed, in fact it is hidden in there after all.


Thursday, November 1, 2018

organic chemistry - Bond length comparison between two carbon atoms


Why is the bond length of double and triple bonds between two carbon atoms shorter than the single bond length between two carbon atoms?



Answer



In the case of a carbon-carbon single bond, 2 electrons are shared in the bond connecting the two carbon atoms. With a carbon-carbon double bond, 4 electrons are shared between the two carbon atoms and 6 electrons are shared in a triple bond. Having additional electrons between the two atoms 1) improves the bonding overlap (makes the bond stronger) between the two carbon atoms and 2) better screens the two carbon nuclei form each other.



Both of these factors, better bonding overlap and better nuclear screening, will allow the two carbon atoms to approach closer together. Consequently, the more electrons (or the more bonds) between two carbon atoms, the shorter the distance between them.


word choice - Difference between し and たり


For example,


京都でラーメンを食べたし金閣寺に行ったしお酒を買った。

京都でラーメンを食べたり金閣寺に行ったりお酒を買ったりした。

As far as I know, both are non-exclusive lists and たり isn't in chronological order (don't know about し). Is there any other difference besides that? The one I hear the most in Japan is し, but that might be just because it's Osaka and they have their own way of saying things.



Answer



You could say し is cumulative and たり is dispersive.


Repeating …し…し…し… is like combining multiple "... as well as ... as well as ... as well as ...", while …たり…たり…たり… is like lining up "(for example) ... or ... or ... or ...".


As long as the subject is singular, both eventually imply the same person do all the things so that the difference is somewhat obscured, but when you use them with plural subjects:



メンバーはみんなイケメンだ頭がいい歌がうまい
They are all good-looking AND smart AND good singers AND... at the same time



メンバーはみんなイケメンだったり頭がよかったり歌がうまかったり
They are all good-looking AND/OR smart AND/OR good singers AND/OR... (a certain member has one or more properties in the list)



fft - Best method to extract phase shift between 2 sinosoids, from data provided


I have been asking around if the way I was extracting phase shift (lag) was correct, and I ran into some trouble.


So in general, given 2 arrays of data of the same length, representing:



  1. the input sinusoid and

  2. the response, also a sinusoid.



So not knowing the functions that produced the input (but knowing the frequency, starting phase of the input, fs, and so on), what is the best way to find the phase lag?



  • should I do it "manually" by looking at the graphs and finding the phase lag at each component?

  • should I use FFT, like I have been trying?


any suggestions, links, books are welcome.



Answer



You can use the cross-correlation function to determine the lag between the two signals.


Voice Audio Detection algorithm


I have to detect speech intervals in large pre-recorded files in my project. I think, there won't be so much noise in the background (audio will be recordered in the room or even in the studio), but it still can be.


So, what are good VAD algorithms that I can use (algorithms, not libraries)?




periodic trends - Comparing radii in lithium, beryllium, magnesium, aluminium and sodium ions

Apparently the of last four, $\ce{Mg^2+}$ is closest in radius to $\ce{Li+}$. Is this true, and if so, why would a whole larger shell ($\ce{...