Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm studying some FFT code's and I'm looking for the possibility to recreate a (cycling) sound that as been decomposed with a fast fourrier transform.
I tried by adding several sinuzoidal curves but it doesn't work at all.
I'm working with C++ but any help will be welcomed.
Thanks
It seems that have to answer my question alone... also I understood that the IFFT was what I looked for,I found a slower function but perfect for me:
void inverseDFT(const double *a, const double *b, const int &N, double *&s)
{
// note: this code is not optimised at all, written for clarity not speed.
for (int x = 0; x < N; ++x)
{
s[x] = a[0];
for (int k = 1; k <= N / 2; ++k)
{
s[x] += a[k] * cos(2 * M_PI / N * k * x) + b[k] * sin(2 * M_PI / N * k * x);
}
}
}
It works perfectly, maybe it will help someone else.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
and I'm having difficulty to drawing a line on the screen using the X, Y, Z coordinates of a CSV or TXT file. I tried with the line render and also with swipe trail, but I could not. Thanks for your help
Read a file e.g using StreamReader.ReadToEnd
var fileContent = "";
(using var reader = new StreamReader(path))
{
fileContent = reader.ReadToEnd();
}
Assuming a CSV/txt content like
23.46, 1.0, 2.4
0.003, 7.038, 3
...
Parse the content e.g. using SplitCSVLine from CSVReader
private static string[] SplitCsvLine(string line)
{
return (from System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(line,
#"(((?<x>(?=[,\r\n]+))|""(?<x>([^""]|"""")+)""|(?<x>[^,\r\n]+)),?)",
System.Text.RegularExpressions.RegexOptions.ExplicitCapture)
select m.Groups[1].Value).ToArray();
}
use it together with float.TryParse(string, out float) like
var lines = fileContent.Split('/n');
var points = new List<Vector3>();
foreach(var line in lines)
{
var parts = SplitCsvLine(line);
float x = float.TryParse(parts[0], out x) ? x : 0;
float y = float.TryParse(parts[1], out y) ? y : 0;
float z = float.TryParse(parts[2], out z) ? z : 0;
points.Add(new Vector3(x, y, z));
}
where
float x = float.TryParse(parts[0], out x) ? x : 0;
is a short form of writing
float x;
if(!float.TryParse(parts[0], out x))
{
x = 0;
// Alternatively you could also declare this point as invalid
// and not add this point at all
continue;
}
or, if you know the content will only exactly contain those numeric symbols and commas, no special characters, you could also simply use
var parts = line.Split(',');
And finally apply those points e.g. to a LineRenderer using SetPositions
GetComponent<LineRenderer>().SetPositions(points);
There might be more efficient options though.
I have a highly imbalanced data, I know that some users suggesting using InfoGainLoss loss function, however, I am facing few errors when I tried to add this function to Caffe layers.
I have the following questions, I really appreciate if someone guides me:
How can I add this layer to Caffe? Does anyone know any sources/ codes of this layer?
I want to apply it for image segmentation and the proportion of some classes varies. How can I create the H matrix (a stack of weights) for my images? And how infoGainLoss layer can read a specific weight matrix (H) related to that specific image?
After adding the cpp and cu version of InforGainLoss layer to caffe, should I remake Caffe?
I am sorry for few question, but all are my concern and related to each other. I will be thankful to get some help and support.
Thanks
1.If you copy from current infogain_loss_layer.cpp you can easily adapt. For forward pass change line 59-66 like:
// assuming num = batch size, dim = label size, image_dim = image height * width
Dtype loss = 0;
for (int i = 0; i < num; ++i) {
for(int k = 0; k < image_dim; k++) {
int label = static_cast<int>(bottom_label[i*image_dim+k]);
for (int j = 0; j < dim; ++j) {
Dtype prob = std::max(bottom_data[i *image_dim *dim+ k * dim + j], Dtype(kLOG_THRESHOLD));
loss -= infogain_mat[label * dim + j] * log(prob);
}
}
}
Similarly for backward pass you could change line 95-101 like:
for (int i = 0; i < num; ++i) {
for(int k = 0; k < image_dim; k++) {
const int label = static_cast<int>(bottom_label[i*image_dim+k]);
for (int j = 0; j < dim; ++j) {
Dtype prob = std::max(bottom_data[i *image_dim *dim+ k * dim + j], Dtype(kLOG_THRESHOLD));
bottom_diff[i *image_dim *dim+ k * dim + j] = scale * infogain_mat[label * dim + j] / prob;
}
}
}
This is kind of naive. I don't seem to find any option for optimization. You will also need to change some setup code in reshape.
2.In this PR suggestion is that for diagonal entries in H put min_count/|i| where |i| is the number of samples has label i. Everything else as 0. Also see this . As for loading the weight matrix H is fixed for all input. You can load it as lmdb file or in other ways.
3.Yes you will need to rebuild.
Update:
As Shai pointed out the infogain pull for this has already been approved this week. So current version of caffe supports pixelwise infogain loss.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am working on a website at the moment and have run into a problem with a triangle pattern.
The designer mocked the site up with triangular tiles and patterns :
Please note that I had to remove most of the content to post it here, but there is content on top of the triangular pattern.
I have done some research on how to implement the triangles in HTML,CSS and possibly JS(?) and came up with three possible options:
background-image
clipping divs and positioning them
using svg and positioning this
The problem with a background-image is that some of these tiles will later change on click and show things etc. So they really shouldn't be on a picture
I have started clipping and positioning divs, but this is just taking forever and I am starting to feel like this cannot be the best solution. Loads of fiddling and I think I will later have problems with inconsistencies
I don't have much experience working with svg, but I would have to draw them all one by one and position them as well (right? this is an assumption). Doesn't seem like the best practice approach.
Does anyone have any input on how I could solve this or do I just have to follow through with one of the solutions named above, as there is no quicker way.
I would really appreciate any ideas.
Thanks Anton
If you decide to go with the SVG route then the code to create the triangles can be relatively small. Store the colors in an array of arrays. Store the horizontal and vertical distance between triangles in two variables (e.g. dx and dy). Then loop through the colors array to draw the individual triangles.
JavaScript code...
var svgNS = "http://www.w3.org/2000/svg";
function drawTriangles() {
var svg = document.getElementById("mySvg");
var colors = [
["#0000FF", "#0044FF", "#0088FF", "#00CCFF"],
["#4400FF", "#4444FF", "#4488FF", "#44CCFF"],
["#8800FF", "#8844FF", "#8888FF", "#88CCFF"],
["#CC00FF", "#CC44FF", "#CC88FF", "#CCCCFF"],
];
var n = colors.length;
var m = colors[0].length;
var dx = 100;
var dy = 75;
for (var i = 0; i < n; i++) {
for (var j = 0; j < m; j++) {
var polygon = document.createElementNS(svgNS, "polygon");
var point0 = svg.createSVGPoint();
var point1 = svg.createSVGPoint();
var point2 = svg.createSVGPoint();
if ((i + j) % 2 === 0) {
point0.x = j * dx;
point0.y = i * dy;
point1.x = (j + 1) * dx;
point1.y = (i + 1) * dy;
point2.x = (j + 1) * dx;
point2.y = (i - 1) * dy;
} else {
point0.x = (j + 1) * dx;
point0.y = i * dy;
point1.x = j * dx;
point1.y = (i - 1) * dy;
point2.x = j * dx;
point2.y = (i + 1) * dy;
}
polygon.setAttribute("fill", colors[i][j]);
polygon.points.appendItem(point0);
polygon.points.appendItem(point1);
polygon.points.appendItem(point2);
svg.appendChild(polygon);
}
}
}
drawTriangles();
<svg id="mySvg" width="400" height="225"></svg>
If css shapes are an option, i would recommend to use them.
https://css-tricks.com/examples/ShapesOfCSS/
However you chose to create the boundaries of your containers, if you embed the svg directly into the html, you can access all the elements the same way you access html elements, and with them you can get their vertices. This way you could use that information to create the shapes.
The downside of that approach is that it is highly depending on javascript, if it is disabled or fails, the complete layout will fail, too. But you can react on layout changes at runtime.
To overcome this you might be able to process the svg on the server, but there you are missing out the final dimensions, what might not be problem if you use percentage values to position your content containers, but a huzzle to code.
All in all, if got this right, creating such a layout where content is arranged in triangles will need a lot of code in each case.
If the page will stay small and not much content be assigned, than doing everything by hand might be faster.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I want to implement MonteCarlo using CUDA.
I write my code on Win8 PC using Visual Studio2012/CUDA 5.5/GT 720M and it runs well.
Then I tried to compile my code in REHL5.3/Tesla C1060/CUDA 2.3 but the result turned out wrong.
Then I want to use cuda-gdb to debug it
but, when I compile my code like this:
nvcc -arch=sm_13 -o my_program my_program.cu
the result is wrong.
However I can't debug it because it's not debug-able code.
When I compile it like this:
nvcc -g -G -arch=sm_13 -o my_program my_program.cu
The result, this time, get correct...
So still I can't find my bug by debugging it...
the code looks like this, the function __device__ double monte_carlo_try() is not in the real code.
the problem is, if I check the value of test[], I find the values are all correct.
So there should be some error in the reduction part.
#include<stdio.h>
#include<cuda_runtime.h>
#include<device_launch_parameters.h>
#include<cuda.h>
#include<malloc.h>
#include<time.h>
#define B 4 //block number
#define T 4 //number of threads per block
#define P 4 //number of paths per thread
__device__ float monte_carlo_try()
{
return 3.0;
}
__global__ void monte_carlo(float*test, float*result)
{
int bid=blockIdx.x;
int tid=threadIdx.x + blockIdx.x * blockDim.x;
int idx=threadIdx.x;
__shared__ float cache[T];
cache[idx]=0;
float temp=0;
for(int i=0;i<P;i++)
{
temp+=monte_carlo_try(); //monte_carlo_try: __device__ function do monte carlo test
}
cache[idx]=temp;
test[tid]=cache[idx];
__syncthreads();
//result[] is the output, and I use test[] to check whether I have got the right cache[idx]
//and the value of test[] is same with what I expect
int i=blockDim.x/2;
while(i>0)
{
if(idx<i)
cache[idx]+=cache[idx+i];
__syncthreads();
i/=2;
}
result[bid]=cache[0];
}
int main()
{
void check_err(cudaError_t );
cudaSetDevice(0);
cudaError_t s_flag;
float *dev_v;
float *dev_test;
s_flag=cudaMalloc((void**)&dev_v,B*sizeof(float));
check_err(s_flag);
cudaMalloc((void**)&dev_test,B*T*sizeof(float));
check_err(s_flag);
monte_carlo<<<B,T>>>(dev_test,dev_v);
s_flag=cudaGetLastError();
check_err(s_flag);
float v[B];
float test[B*T];
s_flag=cudaMemcpy(v,dev_v,B*sizeof(float),cudaMemcpyDeviceToHost);
check_err(s_flag);
s_flag=cudaMemcpy(test,dev_test,B*T*sizeof(float),cudaMemcpyDeviceToHost);
check_err(s_flag);
float sum=0;
for(int i=0;i<B;i++)
{
sum+=v[i];
}
printf("result:%f\n",sum/(B*T*P));
for(int i=0;i<B*T;i++)
{
printf("test[%d]=%f\n",i,test[i]);
}
cudaFree(dev_v);
cudaFree(dev_test);
return 0;
}
void check_err(cudaError_t f)
{
if(f != cudaSuccess)
printf("error msg:%s\n",cudaGetErrorString(f));
}
You probably mean for this line in main():
cudaMalloc((void**)*dev_test,B*T*sizeof(float));
to read like this instead:
cudaMalloc((void**)&dev_test,B*T*sizeof(float));
Additionally, you call
monte_carlo(dev_test,dev_v);
Since monte_carlo is a CUDA kernel, you probably should be setting the number of blocks and threads the kernel should launch with:
monte_carlo<<<num_blocks, threads_per_block>>>(dev_test, dev_v);
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I'm trying to write two inverse functions.
If we pass to function A value 10 it returns for example 4,86 and if we pass that number to function B it should give us back original 10.
I'm using something like this in function A:
output = sqrt(inputForA / range) * inputForA;
So is it possible to reverse it in function B and calculate inputForA only knowing output and range.
You just need to factor that equation to single out inputForA. Here are the algebraic steps:
output = sqrt(inputForA / range) * inputForA
output / inputForA = sqrt(inputForA / range)
sq(output) / sq(inputForA) = inputForA / range
range * sq(output) / sq(inputForA) = inputForA
range * sq(output) = cube(inputForA)
So the cube root of range times the output squared should give you your original input. I don't have a good way of showing that in here though...
You just have to use basic math. output = pow(inputForA, 3. / 2.) * pow(range, 1. / 2.) so inputForA = pow(output * pow(range, 1. / 2.), 2. / 3.). This only works if inputForA and scale have the same sign, but the first function is only defined on that interval, so this is okay (since sqrt is only defined for positive values).
In Python:
scale = 7.
def f(x):
return math.sqrt(x / scale) * x
def g(y):
return math.pow(y * math.pow(scale, 1. / 2), 2. / 3)
print g(f(10))
10.0
print f(g(10))
10.0
You could also have used Wolfram alpha to get the answer: