How to create not squared images using ccfits? - c++

I'd like to create a not squared set of images using ccfits. I can make a single one in the primaryHDU, like this:
long axes[2] = { jmax, imax };
std::auto_ptr<CCfits::FITS> pFits(0);
pFits.reset ( new CCfits::FITS ( "fitfile.fits", FLOAT_IMG, 2, axes ) );
std::valarray<double> h2a0array ( jmax * imax );
for ( int i = 0 ; i < imax ; i++
for ( int j = 0 ; j < jmax ; j++ )
h2a0array [ j + jmax * i ] = i + j;
pFits->pHDU().write ( fpixel, imax * jmax, h2a0array );
But I don't know how to add other not-squared images to my FITS file. I guess I have to use the CCFITS::addImage function, but can only obtain squared images using it:
long fpixel ( 1 );
std::vector<long> extAx ( 2, dim );
CCfits::ExtHDU* imageExt2 = pFits->addImage ( "h2a0array", FLOAT_IMG, extAx );
imageExt2->write ( fpixel, imax * jmax, h2a0array );
The extAx vector contains only two values, the first is the dimension (1D, 2D, 3D) of the image to add to the FITS file, the second is its size. I don't know any other way to add an image to a FITS file. If someone does, your help is strongly welcome!
Thanks,
Arnaud.

The vector of the last argument of addImage can have any dimension
and different axis lengths in the dimensions. There is no requirement that
the axis lengths are the same ("square" as you seem to call it):
vector<long> extAx ;
extAx.push_back(imax) ;
extAx.push_back(jmax) ;
extAx.push_back(kmax) ;
pFits->addImage("h2a0array", FLOAT_IMG, extAx );

Related

C++ Average VectorXcd along axis

I am a beginner in C++ programming. I try working with arrays and the Eigen module. Now I came across a problem I could solve in hours. Maybe it is pretty basic, but I am lost.
QPair<int, double> ConnectivityMeasures::calcImaginaryCoherence(const RowVectorXd& vecFirst, const RowVectorXd& vecSecond, int iNumberEpochs)
{
Eigen::FFT<double> fft;
int N = std::max( vecFirst.cols(), vecSecond.cols() ) ;
//Compute the NFFT
int b = ceil( log2(2.0 * N - 1) ) ;
int fftsize = pow(2,b) ;
//Zero Padding --> Cropping/Extending the Signal to the NFFT size. Cropping=Deleting Values; Extending=Fill up with Zeros
RowVectorXd xImCohInputVecFirst = RowVectorXd::Zero(fftsize) ;
xImCohInputVecFirst.head(vecFirst.cols() ) = vecFirst ;
RowVectorXd xImCohInputVecSecond = RowVectorXd::Zero(fftsize) ;
xImCohInputVecSecond.head( vecSecond.cols() ) = vecSecond ;
//FFT for freq domain to both vectors
RowVectorXcd freqvec ;
RowVectorXcd freqvec2 ;
fft.fwd(freqvec, xImCohInputVecFirst) ;
freqvec.conjugate() ;
fft.fwd(freqvec2, xImCohInputVecSecond) ;
freqvec2.conjugate() ;
// Calculate PowerSpectralDensitiy (PSD) and CrossSpectralDensity(CSD)
VectorXcd Rxy(iNumberEpochs, fftsize);
VectorXcd Rxx(iNumberEpochs, fftsize);
VectorXcd Ryy(iNumberEpochs, fftsize);
for (int i = 0; i < iNumberEpochs; i++)
{
Rxy[i] = sqrt( pow((freqvec[i].real() * freqvec2[i].real() + freqvec[i].imag() * freqvec2[i].imag()), 2 ) + pow((freqvec[i].real() * freqvec2[i].imag() + freqvec[i].imag() * freqvec2[i].real()), 2) );
Rxx[i] = ( pow(freqvec[i], 2) );
Ryy[i] = ( pow(freqvec2[i], 2) );
}
// Average PSD, CSD over the Number of Epochs; not over channels
RowVectorXcd Rxy_mean(freqvec) = Rxy.mean() ;
RowVectorXcd Rxx_mean(freqvec) = Rxx.mean() ;
RowVectorXcd Ryy_mean(freqvec2) = Ryy.mean() ;
So my problem starts here. I have a 2D Array for my Rxy, Rxx and Ryy values. Stored like [number of epochs, number of frequencies].
Now I want to average all frequency values of each epoch to a single value and store them as Rxy_mean, Ryy_mean and Rxx_mean
My Compiler spit out ' Syntax error: missing ";" before "=" '
Does anyone can say how to fix this, proceed or point out my mistake with a simple example ?
Thanks in advance,
Daniel

changing from double to long double in c++ no more gives correct results

In order to increase the accuracy, I have been trying to upgrade a program from double to long double. However, I got the following error.
haread.cpp:178:43: error: no match for ‘operator*’ in ‘2.0e+0 *
std::operator+ [with _Tp = long double](((((const std::complex)KEp) + ((long unsigned int)(((long unsigned int)i) *
32ul)))), ((const std::complex)(& energia)
The line was
phicheb[1][i] = (2.0*(KEp[i] + energia)/dE)-phistate[is][i] ;
The arrays were dynamically defines using 'new'. All the variables are long double. The problem was obtained for all the cases when some number is multiplying the complex array. So, I changed 2.0 to 2.0L and all the similar cases. So, now the compilation is successful. However, my program does not work properly anymore. Do I need to suffix L all the long doubles that I have defined? I have defined them as follows:
long double xmin = 1.6 ;
long double xmax = 7.0 ;
I am not even sure from where to start. Any suggestions?
The compiler is gcc version 4.6.2 (SUSE Linux).
EDIT:
for ( int is = 0 ; is < nstates ; is++ ){
for ( int i = 0 ; i < xgrid ; i++ ) phi[i] = phistate[is][i];
fft(&phi[0], &kphi[0], -1);
for ( int i = 0 ; i < xgrid ; i++ ){
kphi[i] = akx2[i]*kphi[i]*ixgrid; //calculates the KE using Fourier transform
}
fft(&kphi[0],&KEp[0],1);
for ( int i = 0 ; i < xgrid ; i++ ){
x = xmin + (i*dx) ;
energia = complex<long double>(0.0,0.0);
energia = hmatrix[is][is][i]*phistate[is][i] ; //Potential energy
phicheb[0][i] = phistate[is][i];
phicheb[1][i] = (2.0L*(KEp[i] + energia)/dE)-phistate[is][i] ;
}
for ( int j = 2 ; j < ncheb ; j++ ){ //this is a recursion relation
for ( int i = 0 ; i < xgrid ; i++ ) phi[i] = phicheb[j-1][i];
fft(&phi[0], &kphi[0], -1);
for ( int i = 0 ; i < xgrid ; i++ ){
kphi[i] = akx2[i]*kphi[i]*ixgrid;
}
fft(&kphi[0],&KEp[0],1) ;
for ( int i = 0 ; i < xgrid ; i++ ){
x = xmin + (i*dx) ;
energia = complex<long double>(0.0,0.0);
energia = hmatrix[is][is][i]*phi[i];
phicheb[j][i] = (2.0L*((2.0L*(KEp[i] + energia)/dE) - phicheb[j-1][i])) - phicheb[j-2][i]; //recursion
}
}
for ( int i = 0 ; i < xgrid ; i++){
for ( int j = 0 ; j < ncheb ; j++ ){
phistate_new[is][i] += chebc[j]*phicheb[j][i] ;
}
}
}
This is the core of the code. It is used for the propagation of wavefuction on a grid. I will try to explain the code as less technical as possible. I have the values of phistate[0][i], which is the wavefunction corresponding to a ground state (the rest of the states are all zero). Then I calculate the energy of the system (the Kinetic Energy using Fourier transform and the Potential Energy is already given). Now, using a particular method (the Chebychev method), I propagate the wavefunction in time. This method is based on a recursion relation. In this recursion, the propagation is calculated using a polynomial expansion. Chebc are long double coefficients, the values of which are well defined. All the variables whose definition are not shown, are long double.
When I use just double instead of long double, I have no problem getting results. When using long double, phistate_new, my result, has all it's values given by NaN.
Well, yes, a literal value of type long double needs to have an L postfix. So use 2.0L rather than 2.0 (of type double) or 2.0f (of type float).
However, from the error message, your claim that all variables are long double is false.
At least one of the variables is of type std::complex<long double> and the error message indicates that an operation involving one or more of your variables does not exist.
That means you're not understanding what the code does. Which means there will be more to getting it working correctly than changing all things of type double to long double, and fixing type of literal values.
It is not possible to provide more specific advice, as you have not provided enough information. In particular, you would need to supply a small and complete sample of code that illustrates your problem(s).

Gaussian blur not uniform

I have been trying to implement a simple Gaussian blur algorithm, for my image editing program. However, I have been having some trouble making this work, and I think the problem lies in the below snippet:
for( int j = 0; j < pow( kernel_size, 2 ); j++ )
{
int idx = ( i + kx + ( ky * img.width ));
//Try and overload this whenever possible
valueR += ( img.p_pixelArray[ idx ].r * kernel[ j ] );
valueG += ( img.p_pixelArray[ idx ].g * kernel[ j ] );
valueB += ( img.p_pixelArray[ idx ].b * kernel[ j ] );
if( kx == kernel_limit )
{
kx = -kernel_limit;
ky++;
}
else
{
kx++;
}
}
kx = -kernel_limit;
ky = -kernel_limit;
A brief explanation of the code above: kernel size is the size of the kernel (or matrix) generated by the Gaussian blur formula. kx and ky are variables to be used for iterating over the kernel. i is the parent loop, that nests this one, and goes over every pixel in the image. Each value variable simply holds a float R, G, or B value, and is used afterwards to obtain the final result. The if-else is used to increase kx and ky. idx is used to find the correct pixel. kernel limit is a variable set to
(*kernel size* - 1) / 2
So I can have kx going from -1 ( with a 3x3 kernel ) to +1, and the same thing with ky. I think the problem lies with the line
int idx = ( i + kx + ( ky * img.width ));
But I am not sure. The image I get is:
As can be seen, the color is blurred in a diagonal direction, and looks more like some kind of motion blur than Gaussian blur. If someone could help out, I would be very grateful.
EDIT:
The way I fill the kernel is as follows:
for( int i = 0; i < pow( kernel_size, 2 ); i++ )
{
// This. Is. Lisp.
kernel[i] = (( 1 / ( 2 * pi * pow( sigma, 2 ))) * pow (e, ( -((( pow( kx, 2 ) + pow( ky, 2 )) / 2 * pow( sigma, 2 ))))));
if(( kx + 1 ) == kernel_size )
{
kx = 0;
ky++;
}
else
{
kx++;
}
}
Few problems:
Your Gaussian misses brackets (even though you already have plenty..) around 2 * pow( sigma, 2 ). Now you multiply by variance instead of divide.
But what your problem is, is that your gaussian is centered at kx = ky = 0, as you let it run from 0 to kernel_size, instead of from -kernel_limit to kernel_limit. This results in the diagonal blurring. Something like the following should work better
kx = -kernel_limit;
ky = -kernel_limit;
int kernel_size_sq = kernel_size * kernel_size;
for( int i = 0; i < kernel_size_sq; i++ )
{
double sigma_sq = sigma * sigma;
double kx_sq = kx * kx;
double ky_sq = ky * ky;
kernel[i] = 1.0 / ( 2 * pi * sigma_sq) * exp(-(kx_sq + ky_sq) / (2 * sigma_sq));
if(kx == kernel_limit )
{
kx = -kernel_limit;
ky++;
}
else
{
kx++;
}
}
Also note how I got rid of your lisp-ness and some improvements: use some intermediate variables for clarity (compiler will optimize them away if anyway you ask it to); simple multiplication is faster than pow(x, 2); pow(e, x) == exp(x).

Replacing for-loops using thrust::transform

I am trying to optimize my code by implementing for loops on threads of the GPU. I am trying to eliminate two for loops using thrust::transform. The code in C++ looks like:
ka_index = 0;
for (int i = 0; i < N_gene; i++)
{
for (int j = 0; j < n_ka_d[i]; j++ )
{
co0 = get_coeff0(ka_vec_d[ka_index]);
act[i] += (co0*ka_val_d[ka_index]);
ka_index++;
}
act[i] = pow(act[i],n);
}
I am estimating co-efficients for an ordinary differential equation(ODE) in the above loops
and have transferred all the data onto the device using thrust. Consider the case where the number of genes is represented by N_gene. The fist for loop has to run N_gene number of times. The second for loop is restricted by the number of activators(other friendly genes in the gene pool) of each gene. Each gene has a number of activators(friendly genes whose presence increases the concentration of gene i) represented by elements of n_ka vector. Value of n_ka[i] can vary from 0 to N_gene - 1. ka_val represents the measure of activation for each activator ka. ka_vec_d has the gene index which activates gene i.
I am trying to represent these loops using iterators, but unable to do so. I am familiar with using thrust::for_each(thrust::make_zip_iterator(thrust::make_tuple)) for a single for loop, but having a tough time coming up with a way to implement two for loops using counting_iterator or transform iterators. Any pointers or help to convert these two for loops will be appreciated. Thanks for your time!
This looks like a reduce problem. I think you can use thrust::transform with zip iterators and thrust::reduce_by_key. A sketch of this solution is:
// generate indices
std::vector< int > hindices;
for( size_t i=0 ; i<N_gene ; ++i )
for( size_t j=0 ; j<n_ka_d[i] ; ++j )
hindices.push_back( i );
thrust::device_vector< int > indices = hindices;
// generate tmp
// trafo1 implements get_coeff0( get< 0 >( t ) ) * get< 1 >( t);
thrust::device_vector< double > tmp( N );
thrust::transform(
thrust::make_zip_iterator(
thrust::make_tuple( ka_vec_d.begin() , ka_val_d.begin() ) ) ,
thrust::make_zip_iterator(
thrust::make_tuple( ka_vec_d.end() , ka_val_d.end() ) ) ,
tmp.begin() , trafo1 );
// do the reduction for each ac[i]
thrust::device_vector< int > indices_out( N );
thrust::reduce_by_key( indices.begin() , indices.end() , tmp.begin() ,
ac.begin() , indices_out.begin() );
// do the pow transformation
thrust::transform( ac.begin() , ac.end() , ac.begin() , pow_trafo );
I this this can also be optimized by transform_iterators to reduce the number of calls of thrust::transform and thrust::recuce_by_key.

What is the most efficient way to enumerate vertices of k dimensional hypercube in C++?

Basic Question: I have a k dimensional box. I have a vector of upper bounds and lower bounds. What is the most efficient way to enumerate the coordinates of the vertices?
Background: As an example, say I have a 3 dimensional box. What is the most efficient algorithm / code to obtain:
vertex[0] = ( 0, 0, 0 ) -> ( L_0, L_1, L_2 )
vertex[1] = ( 0, 0, 1 ) -> ( L_0, L_1, U_2 )
vertex[2] = ( 0, 1, 0 ) -> ( L_0, U_1, L_2 )
vertex[3] = ( 0, 1, 1 ) -> ( L_0, U_1, U_2 )
vertex[4] = ( 1, 0, 0 ) -> ( U_0, L_1, L_2 )
vertex[5] = ( 1, 0, 1 ) -> ( U_0, L_1, U_2 )
vertex[6] = ( 1, 1, 0 ) -> ( U_0, U_1, L_2 )
vertex[7] = ( 1, 1, 1 ) -> ( U_0, U_1, U_2 )
where L_0 corresponds to the 0'th element of the lower bound vector & likewise U_2 is the 2nd element of the upper bound vector.
My Code:
const unsigned int nVertices = ((unsigned int)(floor(std::pow( 2.0, double(nDimensions)))));
for ( unsigned int idx=0; idx < nVertices; ++idx )
{
for ( unsigned int k=0; k < nDimensions; ++k )
{
if ( 0x00000001 & (idx >> k) )
{
bound[idx][k] = upperBound[k];
}
else
{
bound[idx][k] = lowerBound[k];
}
}
}
where the variable bound is declared as:
std::vector< std::vector<double> > bound(nVertices);
but I've pre-sized it so as not to waste time in the loop allocating memory. I need to call the above procedure about 50,000,000 times every time I run my algorithm -- so I need this to be really efficient.
Possible Sub-Questions: Does it tend to be faster to shift by k instead of always shifting by 1 and storing an intermediate result? (Should I be using >>= ??)
It will probably go faster if you can reduce conditional branching:
bound[idx][k] = upperLowerBounds[(idx >> k) & 1][k];
You might improve things even more if you can interleave the upper and lower bounds in a single array:
bound[idx][k] = upperLowerBounds[(k << 1) | (idx >> k)&1];
I don't know if shifting idx incrementally helps. It's simple enough to implement, so it's worth a try.