<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	
	xmlns:georss="http://www.georss.org/georss"
	xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
	>

<channel>
	<title>R convolve Archives - CenterSpace</title>
	<atom:link href="https://www.centerspace.net/tag/r-convolve/feed" rel="self" type="application/rss+xml" />
	<link>https://www.centerspace.net/tag/r-convolve</link>
	<description>.NET numerical class libraries</description>
	<lastBuildDate>Tue, 01 Mar 2016 18:42:44 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.1.1</generator>
<site xmlns="com-wordpress:feed-additions:1">104092929</site>	<item>
		<title>Convolution, Correlation, and the FFT</title>
		<link>https://www.centerspace.net/convolution-correlation-and-the-fft</link>
					<comments>https://www.centerspace.net/convolution-correlation-and-the-fft#respond</comments>
		
		<dc:creator><![CDATA[Paul Shirkey]]></dc:creator>
		<pubDate>Tue, 03 Nov 2009 00:26:58 +0000</pubDate>
				<category><![CDATA[NMath]]></category>
		<category><![CDATA[Circular Convolution]]></category>
		<category><![CDATA[Convolution]]></category>
		<category><![CDATA[Convolution .NET class]]></category>
		<category><![CDATA[Convolution in C#]]></category>
		<category><![CDATA[Convolution in R]]></category>
		<category><![CDATA[Correlation]]></category>
		<category><![CDATA[Correlation .NET class]]></category>
		<category><![CDATA[Fast Convolution]]></category>
		<category><![CDATA[FFT]]></category>
		<category><![CDATA[Linear Convolution]]></category>
		<category><![CDATA[R convolve]]></category>
		<guid isPermaLink="false">http://www.centerspace.net/blog/?p=347</guid>

					<description><![CDATA[<p>A discussion of the relationships of convolution, correlation and the Fourier transform, including examples porting code from R to NMath.</p>
<p>The post <a rel="nofollow" href="https://www.centerspace.net/convolution-correlation-and-the-fft">Convolution, Correlation, and the FFT</a> appeared first on <a rel="nofollow" href="https://www.centerspace.net">CenterSpace</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Most scientists and programmers understand the basic implementation details of their chosen math library.  However, when algorithms are ported from one library to another, problems are hard to avoid.  This seems to be particularly so when dealing with convolutions, correlations and the FFT &#8211; fundamental building blocks in many areas of computation.  Frequently the theoretical concepts are clear, but when the bits hit the silicon, the confusion (at least for myself) starts.</p>
<p>To start eliminating some of this confusion, it&#8217;s important to understand two fundamental relationships between these three transforms.</p>
<p><center><br />
<img decoding="async" src="http://latex.codecogs.com/gif.latex?\mathcal{F}\{f*g\} = \mathcal{F}\{f\} \cdot \mathcal{F}\{g\}" title="\mathcal{F}\{f*g\} = \mathcal{F}\{f\} \cdot \mathcal{F}\{g\}" /><br />
</center><br />
This is known as the Convolution Theorem, where the italic F represents the Fourier transform, and the splat, convolution.   This basic equality, along with the FFT, is used to compute large convolutions efficiently.  The correlation operator has a similar analogous theorem, and this is where some of the problems start.</p>
<p><center><br />
<img decoding="async" src="http://latex.codecogs.com/gif.latex?\mathcal{F}\{f\star g\}=(\mathcal{F}\{f\})^* \cdot \mathcal{F}\{g\}" title="\mathcal{F}\{f\star g\}=(\mathcal{F}\{f\})^* \cdot \mathcal{F}\{g\}" /><br />
</center></p>
<p>The star is the correlation operator.  Note that the first Fourier transform is conjugated, and that this breaks some basic symmetries in correlation that are found in convolution.</p>
<h2> Convolution in R </h2>
<p>If you happen to be porting code from R, the R language (v. 2.10.0) is distributed with a <code> convolve </code> function which actually, by default, returns the correlation.  This is unfortunate and is a source of confusion for anybody porting a prototype from R to CenterSpace&#8217;s NMath, or to other math library for that matter.</p>
<p>Briefly, in R</p>
<pre lang="r">
kernel <- c(1, 2, 3, 1, 0, 0)
data <- c(1, 2, 3, 4, 5, 6)
convolve(kernel, data)
</pre>
<p>will result in:</p>
<pre lang="r">
[18 17 22 33 32 25] 
</pre>
<p>Now this is a strange result, on a couple of fronts.  First, this isn't the convolution, and second, it isn't the correlation either!   Supposing that we want to compute the correlation between this kernel and signal, we would be expecting precisely,</p>
<pre lang="r">
[0 0 1 5 11 18 25 32 32 17 6 ].
</pre>
<p>Conflating correlation with convolution in one function is certain to cause confusion, because among many other reasons, convolution is communitive, and correlation is not.  In general, for correlation,</p>
<p><center><br />
<img decoding="async" src="http://latex.codecogs.com/gif.latex?f\star g \ne g \star f" title="f\star g \ne g \star f" /><br />
</center></p>
<p>yet for convolution,</p>
<p><center><br />
<img decoding="async" src="http://latex.codecogs.com/gif.latex?f * g = g * f" title="f * g = g * f" /><br />
</center></p>
<p>If g or h satisfy certain symmetry properties, correlation can gain back the communitive property.  </p>
<p>Back to our correlation example above, if we exchange the arguments <code> kernel </code> and <code> data </code> in R's convolve() function we get a different answer.</p>
<pre lang="r">
convolve(data,kernel)
</pre>
<p>gives us,</p>
<pre lang="r">
[18 25 32 33 22 17 ].
</pre>
<p>There is part of a correlation swimming around in that vector, but the last three numbers given by R are not part of a linear correlation.   Many users naturally take those 6 numbers incorrectly as the  linear correlation (or worse convolution) of the <code> kernel </code> and <code> data </code>.  This brings us to our next topic.</p>
<h2> Fast Convolution </h2>
<p>The fast Fourier transform is used to compute the convolution or correlation for performance reasons.  This FFT based algorithm is often referred to as 'fast convolution', and is given by,</p>
<p><center><br />
<img decoding="async" src="http://latex.codecogs.com/gif.latex?\small f*g = \mathcal{F}^{-1} \{\mathcal{F}\{f\} \cdot \mathcal{F}\{g\}\}." title="\small f*g = \mathcal{F}^{-1} \{\mathcal{F}\{f\} \cdot \mathcal{F}\{g\}\}." /></center></p>
<p>In the discrete case, when the two sequences are the same length, <code> N </code>, the FFT based method requires <code> O(N log N) </code> time, where a direct summation would require <code> O(N*N) </code> time.</p>
<p>This asymptotic runtime performance makes the FFT method the defacto standard for computing convolution.  However, this is unfortunate because if the kernel is much smaller than the data,  the direct summation is actually faster than using the FFT.  This is not a rare special case, and is actually very common in signal filtering, wavelet transforms, and image processing applications.  This also brings to light that many libraries (including R) require both inputs to be zero padded to the same length (typically a power of 2) - immediately eliminating this optimization and always forcing the use of the FFT technique.</p>
<p>Returning to our example above.  If we remove the unnecessary padding from the kernel, and recompute the correlation, we arrive at,</p>
<p><img decoding="async" src="http://latex.codecogs.com/gif.latex?\small \texttt{[1 2 3 1]} \star \texttt{[1 2 3 4 5 6] = [1 5 11 18 25 32 32 17 6 ]}" title="\small \texttt{[1 2 3 1]} \star \texttt{[1 2 3 4 5 6] = [1 5 11 18 25 32 32 17 6 ]}" /></p>
<p>Now since both the correlation (and the convolution) spread the signal data by <code> kernel.Length() - 1 = 3 </code> elements, most (engineering) users are interested in the correlation exclusively where the kernel fully overlaps the signal data.  This windowing would then give us,</p>
<p><img decoding="async" src="http://latex.codecogs.com/gif.latex?\small \texttt{[18 25 32]}" title="\small \texttt{[18 25 32]}" /></p>
<p>which are the first three numbers provided by R's <code> convolve </code> function.  The latter three numbers are the results of a <em> circular </em>, not a linear, correlation.  This is probably not the result most engineers are looking for unless they are filtering a periodic signal or an image wrapped on a cylinder.  Circular correlation wraps the data end-to-end in a continuous loop when summing, by effectively joining the first and last elements of the data array.</p>
<p>The circular correlation for this running example would look like the following table.  </p>
<pre class="code">
[1 2 3 4 5 6]
[1 2 3 1 - -] = 18
[- 1 2 3 1 -] = 25
[- - 1 2 3 1] = 32
[1 - - 1 2 3] = 33 (circular)
[3 1 - - 1 2] = 22 (circular)
[2 3 1 - - 1] = 17 (circular)
</pre>
<p>The top array is the data, and the arrays below represent the kernel sweeping across the data step by step.</p>
<p>The difference between the circular and linear correlation is restricted to the edges of the correlation where the (unpadded) kernel does not fully overlap the data.   The circular and linear correlations are identical in the areas where the kernel fully overlaps the data - which in many applications is the area of interest.</p>
<h2> Convolution & Correlation Classes in the NMath library </h2>
<p>CenterSpace's convolution and correlation classes rigorously and efficiently compute their respective transformation correctly, regardless of the computational technique used.  This means that zero padding by the application programmer is no longer necessary, and in fact is discouraged.   As is reflexively using the 'fast convolution' technique when direct summation is actually faster.  </p>
<p>When a NMath convolution or correlation class is constructed, it estimates the number of MFlops needed by all competing techniques and chooses the fastest computational method.  Zero padding will introduce errors into this MFlops estimation process.</p>
<h3> Classes </h3>
<p>The CenterSpace NMath library offers the following eight classes.</p>
<ul>
<li>{Double | Float}1DConvolution
<li>{DoubleComplex | FloatComplex}1DConvolution
<li>{Double | Float}1DCorrelation
<li>{DoubleComplex | FloatComplex}1DCorrelation
</ul>
<p>The two sets of correlation and convolution classes have completely symmetric interfaces.</p>
<p><em> Code Examples </em><br />
If you are currently porting code from a system that uses the FFT 'fast correlation' technique, I will now outline how you would port that code to NMath.  </p>
<p>Porting our running R-example from above to NMath, and assuming that what you need is <em> linear </em> correlation, the NMath code would look like:</p>
<pre lang="csharp">
DoubleVector kernel = new DoubleVector(1, 2, 3, 1);
DoubleVector data = new DoubleVector(1, 2, 3, 4, 5, 6);
      
Double1DCorrelation corr = new Double1DCorrelation(kernel, data.Length);
DoubleVector correlation = corr.Correlate(data);
DoubleVector corr_full_kernel_overlap = 
  corr.TrimConvolution(correlation, CorrelationBase.Windowing.FullKernelOverlap);
      
DoubleVector corr_centered = 
  corr.TrimConvolution(correlation, CorrelationBase.Windowing.CenterWindow);

// correlation =            [1 5 11 18 25 32 32 17 6]
// corr_centered =              [11 18 25 32 32 17]
// corr_full_kernel_overlap =      [18 25 32]
</pre>
<p>Note that the windowing method, <code> TrimConvolution() </code> does not copy any data.  It just creates a windowed view (reference) into the underlying convolution vector.  Windowing of native arrays are not supported because a copy would be required.</p>
<p>The CenterSpace NMath libraries currently do not support circular convolution, so if that is required due to the circular symmetry / periodicity of the data, the circular convolution or correlation must be computed using our FFT classes directly.</p>
<pre lang="csharp">
// Compute circular correlation via FFT's.
// Zero-padding is required here.
// Typically pad to the nearest power of 2.
double[] nhkernel = { 1, 2, 3, 1, 0, 0};      
double[] data = { 1, 2, 3, 4, 5, 6 };
      
// Build FFT classes
 // and setup the correct scaling.
 fft = new DoubleComplexForward1DFFT(nhkernel.Length);
 ifft = new DoubleComplexBackward1DFFT(nhkernel.Length);
 ifft.SetScaleFactorByLength();

// Build the complex vectors of the real data
DoubleComplexVector kernelz = 
new DoubleComplexVector(new DoubleVector(nhkernel), new DoubleVector(nhkernel.Length));

DoubleComplexVector dataz = 
  new DoubleComplexVector(new DoubleVector(data), new DoubleVector(nhkernel.Length));

// Compute.  The next five lines 
// implement the fast correlation algorithm.
fft.FFTInPlace(kernelz);
fft.FFTInPlace(dataz);
dataz = NMathFunctions.Conj(dataz)
DoubleComplexVector prodz = kernelz * dataz;
ifft.FFTInPlace(prod);
r = new DoubleVector(NMathFunctions.Real(prod));
// r = [18 17 22 33 32 25] 
</pre>
<p>
<em>-Paul</em></p>
<p>See our <a href="/topic-fast-fourier-transforms/">FFT landing page </a> for complete documentation and code examples.</p>
<p>The post <a rel="nofollow" href="https://www.centerspace.net/convolution-correlation-and-the-fft">Convolution, Correlation, and the FFT</a> appeared first on <a rel="nofollow" href="https://www.centerspace.net">CenterSpace</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.centerspace.net/convolution-correlation-and-the-fft/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">347</post-id>	</item>
	</channel>
</rss>
