Mathgl Dens() plot not working - c++

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!

Related

transform syntax and structures containing vectors c++

I have a problem with the syntax of the function std::transform. So, I have a structure AirportInfo that contains information about the airports. Every structure is then arranged in a dictionary, so that they have unique IDs. In the structure there is a vector of pairs m_routes which contains the ID of the destination airport and also whether the flight is direct or not. (In this case only direct flight are to be considered, because all non-direct flights have already been deleted, so the second item of the pair will always be 0). The function calculateDistanceBetween returns the distance between 2 airports, by knowing their coordinates, that are being stored also in the structure in pos. Now I have to calculate the distance for every route, but I cannot get over the syntax :( Any Help will be appreciated, Thank you!
This piece of code works
// Calculates the distance between two points on earth specified by longitude/latitude.
// Function taken and adapted from http://www.codeproject.com/Articles/22488/Distance-using-Longitiude-and-latitude-using-c
float calculateDistanceBetween(float lat1, float long1, float lat2, float long2)
{
// main code inside the class
float dlat1 = lat1 * ((float)M_PI / 180.0f);
float dlong1 = long1 * ((float)M_PI / 180.0f);
float dlat2 = lat2 * ((float)M_PI / 180.0f);
float dlong2 = long2 * ((float)M_PI / 180.0f);
float dLong = dlong1 - dlong2;
float dLat = dlat1 - dlat2;
float aHarv = pow(sin(dLat / 2.0f), 2.0f) + cos(dlat1) * cos(dlat2) * pow(sin(dLong / 2), 2);
float cHarv = 2 * atan2(sqrt(aHarv), sqrt(1.0f - aHarv));
// earth's radius from wikipedia varies between 6,356.750 km and 6,378.135 km
// The IUGG value for the equatorial radius of the Earth is 6378.137 km
const float earth = 6378.137f;
return earth * cHarv;
}
struct AirportInfo
{
std::string m_name;
std::string m_city;
std::string m_country;
float pos[2]; // x: latitude, y: longitude
std::vector<std::pair<int, int>> m_routes; // dest_id + numStops
std::vector<float> m_routeLengths;
float m_averageRouteLength;
};
Here is what causes the trouble:
//- For each route in AirportInfo::m_routes, calculate the distance between start and destination. Store the results in AirportInfo::m_routeLengths. Use std::transform() and calculateDistanceBetween().
void calculateDistancePerRoute(std::map<int, AirportInfo>& airportInfo)
{ //loop all structures
for(int i = 0; i < airportInfo.size(); i++ ){
// START END SAVE
std::transform(airportInfo[i].pos[0], airportInfo[i].pos[1], /*...*/ , airportInfo[i].m_routeLengths.begin(),
calculateDistanceBetween);
}
std::cout << "Calculate distance for each route" << std::endl;
}
Use std::back_inserter(airportInfo[i].m_routeLengths) (and if performance is important, reserve vector sizes in advance), instead of airportInfo[i].m_routeLengths.begin(). Also, iterating by index when there is nothing "enforcing" that the indecies in the map are going from 0...map.size() is not safe, you should prefer using a vector for the shown usecase.
I think this is something like what you want:
void calculateDistancePerRoute(std::map<int, AirportInfo>& airportInfo)
{
for(int i = 0; i < airportInfo.size(); i++ )
{
float currentPosX = airportInfo.at(i).pos[0];
float currentPosY = airportInfo.at(i).pos[1];
std::transform(airportInfo.begin(), airportInfo.end(), std::back_inserter(airportInfo.at(i).m_routeLengths), [&] (const auto& otherAirport)
{
return calculateDistanceBetween(currentPosX, currentPosY, otherAirport.second.pos[0], otherAirport.second.pos[1]);
});
}
}
Example in Godbolt

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);
}

How to measure the rate of rise of a variable

I am reading in a temperature value every 1 second/minute (this rate is not crucial). I want to measure this temperature so that if it begins to rise rapidly above a certain threshold I perform an action.
If the temperature rises above 30 degrees ( at any rate ) I increase the fan speed.
I think I must do something like set old temperature to new temp and then each time it loops set old temp to the current temp of the engine. But I am not sure if I need to use arrays for the engine temp or not.
Of course you can store just one old sample, then check difference like in:
bool isHot(int sample) {
static int oldSample = sample;
return ((sample > 30) || (sample - oldSample > threshold));
}
It's OK from C point of view, but very bad from metrology point of view. You should consider some conditioning of your signal (in this case temperature) to smothen out any spikes.
Of course you can add signal conditioning letter on. For (easy) example look at Simple Moving Avarage: https://en.wikipedia.org/wiki/Moving_average
If you want control the fan speed "right way" you should consider learning a bit about PID controller: https://en.wikipedia.org/wiki/PID_controller
Simple discrete PID:
PidController.h:
class PidController
{
public:
PidController();
double sim(double y);
void UpdateParams(double kp, double ki, double kd);
void setSP(double setPoint) { m_setPoint = setPoint; } //set current value of r(t)
private:
double m_setPoint; //current value of r(t)
double m_kp;
double m_ki;
double m_kd;
double m_outPrev;
double m_errPrev[2];
};
PidController.cpp
#include "PidController.h"
PidController::PidController():ControllerObject()
{
m_errPrev[0] = 0;
m_errPrev[1] = 0;
m_outPrev = 0;
}
void PidController::UpdateParams(double kp, double ki, double kd)
{
m_kp = kp;
m_ki = ki;
m_kd = kd;
}
//calculates PID output
//y - sample of y(t)
//returns sample of u(t)
double PidController::sim(double y)
{
double out; //u(t) sample
double e = m_setPoint - y; //error
out = m_outPrev + m_kp * (e - m_errPrev[0] + m_kd * (e - 2 * m_errPrev[0] + m_errPrev[1]) + m_ki * e);
m_outPrev = out; //store previous output
//store previous errors
m_errPrev[1] = m_errPrev[0];
m_errPrev[0] = e;
return out;
}

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.

Violation access in time compilation (0xC0000005)

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.