Np.vstack using torch in libtorch and pytorch

how can translate this numpy code to both pytorch and libtorch:

np.vstack([fourier_basis[:cutoff, :], fourier_basis[:cutoff, :] )])

I’m not sure what np.vstack is doing but torch.stack sounds like a good candidate :slight_smile:

thank’s, but torch.stack and torch.cat don’t work.

Yeah, well, it’s equivalent to stack for 1d inputs, to cat for >=2d. In your case cat.

torch.cat((a, b), dim=0) should work.
Essentially vstack concatenates row-wise.

1 Like

thanks , its ok.
in numpy :

filter_length = 4  
fourier_basis = np.fft.fft(np.eye(filter_length))
 cutoff = int((filter_length / 2 + 1))
np.vstack([np.real(fourier_basis[:cutoff, :]),np.imag(fourier_basis[:cutoff, :])])

is equal to pytorch:

fourier_basis_torch = torch.rfft(torch.eye(filter_length), 1, False) 
real = fourier_basis_torch[:,:,0].transpose(0,1)
imag = fourier_basis_torch[:,:,1].transpose(0,1)
torch.cat( (real[:cutoff, :],imag[:cutoff, :]), dim=0)

and in libtorch:

int64_t filterLength = 4;
int cutoff = (int)((filterLength / 2 + 1));
auto npFft = at::rfft(at::eye(filterLength),signal_ndim, onesided);
auto realPart = torch::nn::functional::_narrow_with_range(npFft,2,0,1);
realPart = at::transpose(realPart, 0, 1);    
realPart = realPart.view({realPart.size(0), realPart.size(1)}); 
auto imgPart = torch::nn::functional::_narrow_with_range(npFft,2,1,2);
imgPart =  at::transpose(imgPart, 0, 1);  
imgPart = imgPart.view({imgPart.size(0), imgPart.size(1)});         
auto out = at::cat({realPart, imgPart}, 0);