Violation access in time compilation (0xC0000005) - c++

The process I want to do is to make the FFT to an image (stored in “imagen”) , and then, multiply it with a filter ‘H’, after that, the inverse FFT will be done also.
The code is shown below:
int ancho;
int alto;
ancho=ui.imageframe->imagereader->GetBufferedRegion().GetSize()[0]; //ancho=widht of the image
alto=ui.imageframe->imagereader->GetBufferedRegion().GetSize()[1]; //alto=height of the image
double *H ;
H =matrix2D_H(ancho,alto,eta,sigma); // H is calculated
// We want to get: F= fft(f) ; H*F ; f'=ifft(H*F)
// Inicialization of the neccesary elements for the calculation of the fft
fftw_complex *out;
fftw_plan p;
int N= (ancho/2+1)*alto; //number of points of the image
out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*N);
double *in = (double*) imagen.GetPointer(); // conversion of itk.smartpointer --> double*
p = fftw_plan_dft_r2c_2d(ancho, alto, in, out, FFTW_ESTIMATE); // FFT planning
fftw_execute(p); // FFT calculation
/* Multiplication of the Output of the FFT with the Filter H*/
int a = alto;
int b = ancho/2 +1; // The reason for the second dimension to have this value is that when the FFT calculation of a real image is performed only the non-redundants outputs are calculated, that’s the reason for the output of the FFT and the filter ‘H’ to be equal.
// Matrix point-by-point multiplicaction: [axb]*[axb]
fftw_complex* res ; // result will be stored here
res = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*a*b);
res = multiply_matrix_2D(out,H, a, b);
The problem is located here, in the loop inside the function ‘multiply_matrix_2D’:
fftw_complex* prueba_r01::multiply_matrix_2D(fftw_complex* out, double* H, int M ,int N){
/* The matrix out[MxN] or [n0x(n1/2)+1] is the image after the FFT , and the out_H[MxN] is the filter in the frequency domain,
both are multiplied POINT TO POINT, it has to be called twice, one for the imaginary part and another for the normal part
*/
fftw_complex *H_cast;
H_cast = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*M*N);
H_cast= reinterpret_cast<fftw_complex*> (H); // casting from double* to fftw_complex*
fftw_complex *res; // the result of the multiplication will be stored here
res = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*M*N);
//Loop for calculating the matrix point-to-point multiplication
for (int x = 0; x<M ; x++){
for (int y = 0; y<N ; y++){
res[x*N+y][0] = out[x*N+y][0]*(H_cast[x*N+y][0]+H_cast[x*N+y][1]);
res[x*N+y][1] = out[x*N+y][1]*(H_cast[x*N+y][0]+H_cast[x*N+y][1]);
}
}
fftw_free(H_cast);
return res;
}
With the values of x = 95 and y = 93 being M = 191 and N = 96;
Uncontroled exception at 0x004273ab in prueba_r01.exe: 0xC0000005 acess infraction reading 0x01274000.
imagen http://img846.imageshack.us/img846/4585/accessviolationproblem.png
Where a lot of values of the variables are in red, and for translation issue: H_cast[][1] has in the value box : “Error30CXX0000 : impossible to evaluate the expression”.
I will really appreciate any kind of help with this please!!
Antonio

This part of the code
H_cast = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*M*N);
H_cast= reinterpret_cast<fftw_complex*> (H); // casting from double* to fftw_complex*
first allocates a new buffer for H_cast and then immediately sets it to point to the original H instead. It doesn't copy the data, just the pointer.
At the end of the function some buffer is free'd
fftw_free(H_cast);
which seems to free the data pointed to by H and not the buffer allocated in the function.
When getting back to the caller, the H there is lost!

There is an FFT class inside of ITK that can use fftw (USE_FFTW) from cmake for configuration. This class describes how to reference the ITK raw buffer memory from fftw.
PS: The upcoming ITKv4 has greatly improved the fftw compatibility.

Related

Inaccuracy of 1 dimensional FFTW3 derivatives in C++ despite using zero padding and 1/2 filter

I am trying to check if my 1D fftw3 implementation is right by testing for the first derivative of a sinusoidal input sample. The original sample size is nX and I've padded it with zeros on both ends of the sample such that the new sample size is 3 * nX (nX3).
The accuracy without the padding wasn't good for the derivatives and it got worse with higher derivatives, making zero padding seem necessary.
However, the padded sample input has accuracy much lesser than that of the non-padded one. The accuracy was checked by comparing the first order derivative of sample input (sin(x)), real(out[]), with its analytical value, cos(x). The code is shown below.
#include<iostream>
#include<cmath>
#include<complex>
#include<fftw3.h>
using namespace std;
int main()
{
int i,ir,nX;
nX = 16;
int nX3, nX2; //padded array dimension = nX3
nX3 = 3*nX;
nX2=2*nX;
double Nd = (double)nX3;
int id;
double pi = M_PI;
std::complex<double> *in, *out;
in = (complex<double>*)malloc(nX3*sizeof(complex<double>));
if(in==NULL) { cout<<"inalloc error\n"<<endl;}
out = (complex<double>*)malloc(nX3*sizeof(complex<double>));
if(out==NULL) { cout<<"outalloc error\n"<<endl;}
fftw_complex *bt;
bt = (fftw_complex*)fftw_malloc(sizeof(fftw_complex)*nX3);
fftw_plan p, q;
p = fftw_plan_dft_1d(nX3, reinterpret_cast<fftw_complex*>(in), bt, FFTW_FORWARD,FFTW_MEASURE);
q = fftw_plan_dft_1d(nX3, bt, reinterpret_cast<fftw_complex*>(out), FFTW_BACKWARD,FFTW_MEASURE);
for(i=0;i<nX3;i++)
{
in[i] = {0.0,0.0}; //initialising padded input array
}
for(i=nX;i<nX2;i++)
{
double id = (double)(i-nX)*pi/nX;
//sinusoidal input in the central square of the padded array (3 squares)
//varies in 'i' direction
in[i] = complex<double>(sin(id),0.0);
//cout<<"i\t"<<i-nX<<"\t"<<in[i]<<endl;
}
fftw_execute(p); //fourier transform
double kx;
int x1;
kx = 2.0*pi/(double)nX3;
double kx1;
for(i=0;i<nX;i++)
{
double btr(0.0), btc(0.0); //temporary variables
id=i+nX;
if(id<nX3/2) //1/2 filter
{
x1 = id;
}
else if(id==nX3/2)
{
x1 = 0;
}
else
{
x1 = id-nX3;
}
kx1=kx*(double)x1;
//complex first derivative array 'bt[id]'
btr = -1.0*kx1*bt[id][1]; //real part
btc = kx1*bt[id][0]; //complex part
bt[id][0] = btr;
bt[id][1] = btc;
}
fftw_execute(q); //inverse fourier transform
for(i=0;i<nX;i++)
{
//input sample varies only in the i direction, hence out[i+nX] should be identical for all 'y' and 'z' points inside the central cube at a specific value of 'i'
double id = (double)i*pi/nX;
double c = cos(id); //analytical value of first derivative for comparison with 'out[i+NX]'
cout<<"i\t"<<i<<"\t"<<c<<"\t"<<real(out[i+nX])/Nd<<endl;
//analytical value 'c' compared with fftw3 result, 'out'
//normalising 'out[i+nX]' by dividing it by volume of padded array dimension nX3
}
free(bt);
free(in);
free(out);
fftw_destroy_plan(p);
fftw_destroy_plan(q);
}

FFT and FFTShift of matlab in FFTW library c++

what is the exact equivalent of this MATLAB line code in C++ and using FFTW?
fftshift(fft(x,4096)));
note: X is an array of 4096 double data.
now I use these lines of code in c++ and FFTW to compute fft
int n = 4096
fftw_complex *x;
fftw_complex *y;
x = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * n);
y = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * n);
for (int i=0; i<n; i++)
{
x[i][REAL] = MyDoubleData[i];
x[i][IMAG] = 0;
}
fftw_plan plan = fftw_plan_dft_1d(n, x, y, FFTW_FORWARD, FFTW_ESTIMATE);
fftw_execute(plan);
fftw_destroy_plan(plan);
fftw_cleanup();
It is just equivalent of FFT function in MATLAB.
Is there any equivalent function for FftShift in FFTW library?
The FFTW function calls you've provided would be the equivalent of fft(x,4096). If x is real, matlab knows to give you the conjugate symmetric FFT (I think). If you want to do this with FFTW, you need to use the r2c and c2r functions (real-to-complex/complex-to-real).
You have to do the shift yourself. You can do direct substitution (poor performance, but should be intuitive)
for (int i=0; i<n; i++)
{
fftw_complex tmp;
int src = i;
int dst = (i + n/2 - 1) % n;
tmp=y[src];
y[src]=x[dst];
y[dst]=tmp;
}
Alternatively use a couple memcpy's (and/or memmove's) or modify your input data
The output of the fftw is stored base on following format of frequencies sequence:
[0....N-1]
Where N is number of frequencies and is oven.
And fftshift change it to:
[-(N-1)/2,..., 0..., (N-1)/2]
but you should note that fftw output has equivalent as:
[0,.., N-1] is same as [0,...,(N-1)/2,-(N-1)/2,...,-1]
This means that in DFT, frequency -i is same as N-i.

Matrix multiplication issues using C++ Eigen, and matlab mexFunction

// computing the matrix operation here
// resultEigen = Input matrix
// result1Eigen = hidden bias
// result2Eigen = visible bias
// result3Eigen = weight matrix
MatrixXd H;
MatrixXd V;
double well[36];
Map<MatrixXd>( well, H.rows(), H.cols() ) = H;
H = resultEigen * result3Eigen + result1Eigen;
mexPrintf("H is here\n");
for (int i=0; i<36; i++)
{
mexPrintf("%d\n",H);
}
mexPrintf("\n");
I need to build a reconstructing function for my RBM and since direct matrix multiplication could get me a better result, I have been referring to eigen library to solve my issues but I am facing some difficulties.
when running the above code I end up getting a single value for the H matrix and I wonder why!
Moreover the parameters used in for the computation of H have been initiated as follows:
double *data1 = hbias;
Map<VectorXd>hidden_bias(data1,6,1);
VectorXd result1Eigen;
double result1[6];
result1Eigen = hidden_bias.transpose();
Map<VectorXd>(result1, result1Eigen.cols()) = result1Eigen;
// next param
double *data2 = vbias;
Map<VectorXd>visible_bias(data2,6,1);
VectorXd result2Eigen;
double result2[6];
result2Eigen = visible_bias.transpose();
Map<VectorXd>(result2, result2Eigen.cols()) = result2Eigen;
// next param
double *data3 = w;
Map<MatrixXd>weight_matrix(data3,n_visible,n_hidden);
MatrixXd result3Eigen;
// double result3[36];
mxArray * result3Matrix = mxCreateDoubleMatrix(n_visible, n_hidden, mxREAL );
double *result3=(double*)mxGetData(result3Matrix);
result3Eigen = weight_matrix.transpose();
Map<MatrixXd>(result3, result3Eigen.rows(), result3Eigen.cols()) = result3Eigen
At last I also face issues printing out data using std::cout from inside the mexFunction.
Thanks for any hints.
The problem is in the printing code which should be:
mexPrintf("%d\n",H(i));
Then, there is no need to duplicate vectors and matrices. For instance, result1 is useless, as you can get a raw pointer to the data stored in result1Eigen using result1Eigen.data(). Likewise, you can directly assign weight_matrix.transpose() to Map<MatrixXd>(result3,...), and I don't see the purpose of well.
Finally, if sizes are really known at compile-time, then better using Matrix<double,6,1> instead of a VectorXd and Matrix<double,6,6> instead of a MatrixXd. Yo ucan expect significant speedup.

Mathgl Dens() plot not working

It's been now days that I'm trying to figure out what is wrong but can't because mostly there are very limited documentation that I can find about error handling with the Dens() function in Mathgl. The following is my question. I'm trying to build a spectrogram from an input signal. I have created a M*N array which holds my DFT data. where M=no of rows=total no of windowing used for that signal and N= total no of samples in each Window. There is an X matrix which is of size(M,1) which holds the time data and another matrix /y of size(N,1) which holds normalized frquency data (in db) where least db is 0 and max db =1. The DFT data array of size (M,N) holds value ranging from 0-1 of datatype float. The following is my code.
vector fftstore = dSTFT(&signal, signalLength, windowSize,hopSize);
int num_rows=fftstore.size()/windowSize;
float *m_gl = new float[num_rows * windowSize];
memset( m_gl,0,num_rows*windowSize*sizeof(float));
float *m_glstart;
m_glstart=m_gl;
//t m_gl[num_rows][windowSize]={0};
float *begin_loc;
begin_loc=&fftstore[0];
float *end_loc;
end_loc=&fftstore[0]+windowSize;
//t *dest;
//st=m_gl;
float *offset;
for(int kk=0; kk<num_rows; kk++)
{
offset=m_glstart+(kk*windowSize+0);
//oat offset=&m_gl[kk*windowSize+0];
std::copy(begin_loc, end_loc, offset);
begin_loc+=windowSize;
end_loc+=windowSize;
}
//r(vector<float>::iterator it = fftstore.begin(); it != fftstore.end(); it++) {
//out << *it << endl;
//
//converting M_gl to double
double *m_gldob = new double[num_rows * windowSize];
memset( m_gldob,0,num_rows*windowSize*sizeof(double));
for (int id=0;id<num_rows;id++){
for(int ij=0;ij<4096;ij++){
m_gldob[id * windowSize + ij]=double(m_gl[id * windowSize + ij]);
}
}
//mgl plotting
double xdat[num_rows][1];
memset( xdat,0,num_rows*1*sizeof(int));
for (int xt=1;xt<=num_rows;xt++){
xdat[xt-1][1]=((100*(2*xt-1))/(2*xt));
}
double ydat[windowSize][1];
memset( ydat,0,windowSize*1*sizeof(int));
for (int yf=1;yf<=windowSize;yf++){
ydat[yf-1][1]=(yf*(1/windowSize));
}
double xst;
xst=xdat[0][0];
double xend=xdat[num_rows-1][1];
double yst=ydat[0][0];
double yend=ydat[windowSize-1][1];
double *px;
double *py;
double *pdat;
px=&xdat[0][0];
py=&ydat[0][0];
pdat=m_gldob;
mglGraph gr;
mglData mgl_x;
mglData mgl_y;
mglData mgl_dat;
mgl_dat.Link(m_gldob,num_rows*windowSize,1);//c *
mgl_dat.Rearrange(num_rows,windowSize);
mgl_x.Link(px,num_rows,1);
mgl_y.Link(py,windowSize,1);
mgl_x.Norm();//c
mgl_y.Norm();//c
gr.SetQuality(6);
gr.Alpha(true);
gr.SetRange('x',xst,xend);
gr.SetRange('y',yst,yend);
gr.SetRange('c',0.0, 1.0);
gr.Box();
gr.Dens(mgl_x,mgl_y,mgl_dat);
gr.Colorbar();
gr.WriteBMP("/home/koyel/test1.bmp");
delete[] m_gl;
return 0;
this code runs to give me an output which looks like the following:
http://i.stack.imgur.com/8uAq6.png
can you tell me whats going wrong? Thanks!

fftw - Access violation error

I implemented a fftw (fftw.org) example to use Fast Fourier transforms...
This is the code....
I load an image that I convert from uint8_t to double (this code works fine...).
string bmpFileNameImage = "files/testDummyFFTWWithWisdom/onechannel_image.bmp";
BMPImage bmpImage(bmpFileNameImage);
vector<double>pixelColors;
vector<uint8_t> image = bmpImage.copyBits();
toDouble(image,pixelColors,256,256, 1);
int width = bmpImage.width();
int height = bmpImage.height();
I use wisdom files to improve the performance
FILE * file = fopen("wisdom.fftw", "r");
if (file) {
fftw_import_wisdom_from_file(file);
fclose(file);
}
///* fftw variables */
fftw_complex *out;
double *wisdomInput = (double *) fftw_malloc(sizeof(double)*width*2*(height/2 +1 ));
const fftw_plan forward =fftw_plan_dft_r2c_2d(width,height, wisdomInput,reinterpret_cast<fftw_complex *>(wisdomInput),FFTW_PATIENT);
const fftw_plan inverse = fftw_plan_dft_c2r_2d(width, height,reinterpret_cast<fftw_complex *>(wisdomInput),wisdomInput, FFTW_PATIENT);
file = fopen("wisdom.fftw", "w");
if (file) {
fftw_export_wisdom_to_file(file);
fclose(file);
}
Finally, I execute the fftw library.... I receive an Access violation error with the first
function (fftw_execute_dft_r2c) and I don't know why... I read this tutorial:
http://www.fftw.org/fftw3_doc/Multi_002dDimensional-DFTs-of-Real-Data.html#Multi_002dDimensional-DFTs-of-Real-Data.
I do a malloc with (ny/2+1) how it is explained.... . I don't understand why it is not working.... I am testing different sizes...
out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * width *(height / 2 + 1));
double *result =(double *)fftw_malloc(width * (height+2) * sizeof(double));
fftw_execute_dft_r2c(forward,&pixelColors[0],out);
fftw_execute_dft_c2r(inverse,out,result);
Regards.
This is the corrected code.
It had a few mistakes:
It was reading a wrong wisdom.fftw file (from some old test...). Now, It always creates a new fftw_plan and a new file.
I misunderstood how it works the fftw library with in-place and out-of-place parameters. I had to change mallocs for the correct padding for "in-place" (I added +2 in malloc functions).
In order to restore the image, I had to divide by its size ((width+2) * height) how it is explained in this link.
`
/* load image */
string bmpFileNameImage = "files/polyp.bmp";
BMPImage bmpImage(bmpFileNameImage);
int width = bmpImage.width();
int height = bmpImage.height();
vector<double> pixelColors;
vector<uint8_t> image = bmpImage.copyBits();
//get one channel from the image
Uint8ToDouble(image,pixelColors,bmpImage.width(),bmpImage.height(),1);
//We don't reuse old wisdom.fftw... It can be corrupt
/*
FILE * file = fopen("wisdom.fftw", "r");
if (file) {
fftw_import_wisdom_from_file(file);
fclose(file);
} */
double *wisdomInput = (double *) fftw_malloc(sizeof(double)*height*(width+2));
const fftw_plan forward =fftw_plan_dft_r2c_2d(width,height,wisdomInput,reinterpret_cast<fftw_complex *>(wisdomInput),FFTW_PATIENT);
const fftw_plan inverse = fftw_plan_dft_c2r_2d(width,height,reinterpret_cast<fftw_complex *>(wisdomInput),wisdomInput, FFTW_PATIENT);
double *bitsColors =(double *)fftw_malloc((width) * height * sizeof(double));
for (int y = 0; y < height; y++) {
for (int x = 0; x < width+2; x++) {
if (x < width) {
int currentIndex = ((y * width) + (x));
bitsColors[currentIndex] = (static_cast<double>(result[y * (width+2) + x])) / (height*width);
}
}
}
fftw_free (wisdomInput);
fftw_free (out);
fftw_free (result);
fftw_free (bitsColors);
fftw_destroy_plan(forward);
fftw_destroy_plan(inverse);
fftw_cleanup();
}
`
fftw_execute_dft_r2c(forward,&pixelColors[0],out);
What are you doing here ? The array has already a pointer.
Change it to fftw_execute_dft_r2c(forward,pixelColors[0],out); it should work now.
Maybe the problem is here (http://www.fftw.org/doc/New_002darray-Execute-Functions.html):
[...] that the following conditions are met:
The input and output arrays are the same (in-place) or different (out-of-place) if the plan was originally created to be in-place or
out-of-place, respectively.
In the plan you are using in-place transformation parameters (with bad allocation, BTW, since:
double *wisdomInput = (double *) fftw_malloc(sizeof(double)*width*2*(height/2 +1 ));
should be:
double *wisdomInput = (double *) fftw_malloc(sizeof(fftw_complex)*width*2*(height/2 +1 ));
to be suitable for output too).
But you're calling fftw_execute_dft_r2c function with out-of-place parameters.