Taking a second derivative in FFTW3 - c

I have tested my code for some real functions using a forward FFT and IFFT (normalized the result), this works fine.
I would, however, like to take a second derivative of a real function. For simplicity sake, I take sin(2*pi*t) as a test case. Here is the relevant code I use (FFT functions in a library):
int main(void)
{
int i;
int nyh = (N/2) + 1;
double result_array[nyh][2];
double x_k[nyh][2];
double x_r[N];
FILE* psit;
psit=fopen("psitest.txt","w");
init();
fft(x, result_array); //function in a library, this has been tested
psi(result_array, x_k);
ifft(x_k, x_r); //function in a library, this has been tested
for(i=0;i<N;i++)
{
fprintf(psit, "%f\n", x_r[i]);
}
fclose(psit);
return 0;
}
void psi(double array[nyh][2], double out[nyh][2])
{
int i;
for ( i = 0; i < N/2; i++ )
{
out[i][0] = -4.0*pi*pi*i*i*array[i][0];
out[i][1] = -4.0*pi*pi*i*i*array[i][1];
}
out[N/2][0]=0.0;
out[N/2][1]=0.0;
}
void init()
{
int i;
for(i=0;i<N;i++)
{
x[i] = sin(2.0*pi*i/N);
}
}
Now here is the problem: This algorithm works perfectly for any function of the form sin( 2*pi*t*K), where K is an integer, but if I take as a test function sin(3*pi*t), the algorithm fails. I am not able to see the mistake in my coding.
Please note that because the function is real, I only need to take half of the k values. This is not the problem.

My guess is that sin(3*pi*t) introduces a discontinuity, since it does not give an integer number of cycles in your sample interval. For most FFT-related applications you would apply a window function to deal with such discontinuities, but obviously this will introduce an error term into your derivative and I'm not sure whether you will be able to correct for this.

I don't know if you have fixed this problem... But I guess the major problem is that sin(3 Pi t) is not periodic in the domain [0,1](sin(0) != sin (3 * Pi)).
FFT could not work properly...

Related

pass struct of arrays into function

I am trying to pass a struct of 2D arrays and to do calculations on them.
typedef struct{
float X[80][2];
float Y[80][2];
float Z[80][2];
int T[80][2];
int K[80];
} STATS;
void MovingAverage(STATS *stat_array, int last_stat) {
//Average = Average(Prev) + (ValueToAverage/n) - (Average(Prev)/n)
stat_array->**X**[last_stat][0] = stat_array->**X**[last_stat][0] +
(stat_array->**X**[last_stat][1] / stat_array->T[last_stat][0]) -
(stat_array->**X**[last_stat][0] / stat_array->T[last_stat][0]);
}
calling the function:
MovingAverage(*stat_array, last_stat);
My question is:
how do I access in a generic way to X Y and Z inside MovingAverage function?
Edit:
void MovingAverage(STATS *stat_array, int last_stat, (char *(array_idx)) {
//Average = Average(Prev) + (ValueToAverage/n) - (Average(Prev)/n)
stat_array->**array_idx**[last_stat][0] =
stat_array->**array_idx**[last_stat][0] +
(stat_array->**array_idx**[last_stat][1] /
stat_array->T[last_stat][0]) -
(stat_array->**array_idx**[last_stat][0] /
stat_array->T[last_stat][0]);
}
I know it won't work, but just to demonstrate my willings,
Somebody here (not me) could probably come up with some preprocessor magic to do what you're asking, but that is a solution I would not pursue. I consider it bad practice since macros can quickly get hairy and tough to debug. You can't have "variables" inside your source code, if that makes sense. During the build procedure, one of the first things that runs is the preprocessor, which resolves all your macros. It then passes that source code to the compiler. The compiler is not going to do any text substitutions for you, it cranks on the source code it has. To achieve what you want, write a function that operates on the type you want, and call that function with all your types. I'd change your MovingAverage function to something like this:
void MovingAverage(float arr[80][2], const int T[80][2], int last_stat)
{
arr[last_stat][0] = ... // whatever calculation you want to do here
}
int main(void)
{
STATS stat_array;
int last_stat;
// .. initialize stat_array and last_stat
// now call MovingAverage with each of your 3 arrays
MovingAverage(stat_array.X, stat_array.T, last_stat);
MovingAverage(stat_array.Y, stat_array.T, last_stat);
MovingAverage(stat_array.Z, stat_array.T, last_stat);
...
return 0;
}

Program will not return a value back

So, I am creating a GUI in which you are able to calculate either the molar mass, mass or moles and I cannot seem to get a calculation back when I call my methods. I am using parallel arrays and I am thinking that may be the problem. Btw, molarMass was declared globally but I didn't know how to format it on here. Thanks.
private void btnGoActionPerformed(java.awt.event.ActionEvent evt) {
int indexOfElements = cmbElements.getSelectedIndex();
Double numberOfMass = Double.parseDouble(txtInputMass.getText());
Double numberOfMoles = Double.parseDouble(txtInputMoles.getText());
if (chkMoles.isSelected()==true)
{
txtAnswer.setText(solveForMoles(numberOfMass).toString() + " mol");
}
else if (chkMolarMass.isSelected()==true)
{
txtAnswer.setText(solveForMolarMass(numberOfMass, numberOfMoles).toString() + "
g/mol");
}
else if (chkMass.isSelected()==true)
{
txtAnswer.setText(solveForMass(numberOfMoles).toString() + " g");
}
else
{
txtAnswer.setText ("Please make a selection");
}
private Double solveForMoles (double mass){
int indexOfElements = cmbElements.getSelectedIndex();
double numberOfMoles = mass/molarMass[indexOfElements];
return (Double.parseDouble (x.format(numberOfMoles)));
}
private Double solveForMass (double moles){
int indexOfElements = cmbElements.getSelectedIndex();
double numberOfMass = moles*molarMass[indexOfElements];
return (Double.parseDouble (x.format(numberOfMass)));
}
private Double solveForMolarMass (double masss, double moless){
double numberOfMolarMass = masss/moless;
return (Double.parseDouble(x.format (numberOfMolarMass)));
}
I'd recommend that you make some changes:
Encapsulate all those calculations into a sensible Java object rather than parallel arrays. Java's an object-oriented language.
Move all the calculations outside of the UI. Write that calculation object, JUnit test it thoroughly, then introduce it into the UI. Computer science, and all problem solving, is best done using divide and conquer.

Is it possible to exchange a C function implementation at run time?

I have implemented a facade pattern that uses C functions underneath and I would like to test it properly.
I do not really have control over these C functions. They are implemented in a header. Right now I #ifdef to use the real headers in production and my mock headers in tests. Is there a way in C to exchange the C functions at runtime by overwriting the C function address or something? I would like to get rid of the #ifdef in my code.
To expand on Bart's answer, consider the following trivial example.
#include <stdio.h>
#include <stdlib.h>
int (*functionPtr)(const char *format, ...);
int myPrintf(const char *fmt, ...)
{
char *tmpFmt = strdup(fmt);
int i;
for (i=0; i<strlen(tmpFmt); i++)
tmpFmt[i] = toupper(tmpFmt[i]);
// notice - we only print an upper case version of the format
// we totally disregard all but the first parameter to the function
printf(tmpFmt);
free(tmpFmt);
}
int main()
{
functionPtr = printf;
functionPtr("Hello world! - %d\n", 2013);
functionPtr = myPrintf;
functionPtr("Hello world! - %d\n", 2013);
return 0;
}
Output
Hello World! - 2013
HELLO WORLD! - %D
It is strange that you even need an ifdef-selected header. The code-to-test and your mocks should have the exact same function signatures in order to be a correct mock of the module-to-test. The only thing that then changes between a production-compilation and a test-compilation would be which .o files you give to the linker.
It is possible With Typemock Isolator++ without creating unnecessary new levels of indirection. It can be done inside the test without altering your production code. Consider the following example:
You have the Sum function in your code:
int Sum(int a, int b)
{
return a+b;
}
And you want to replace it with Sigma for your test:
int Sigma(int a, int b)
{
int sum = 0;
for( ; 0<a ; a--)
{
sum += b;
}
return sum;
}
In your test, mock Sum before using it:
WHEN_CALLED: call the method you want to fake.
ANY_VAL: specify the args values for which the mock will apply. in this case any 2 integers.
*DoStaticOrGlobalInstead: The alternative behavior you want for Sum.
In this example we call Sigma instead.
TEST_CLASS(C_Function_Tests)
{
public:
TEST_METHOD(Exchange_a_C_function_implementation_at_run_time_is_Possible)
{
void* context = NULL; //since Sum global it has no context
WHEN_CALLED(Sum (ANY_VAL(int), ANY_VAL(int))).DoStaticOrGlobalInstead(Sigma, context);
Assert::AreEqual(2, Sum(1,2));
}
};
*DoStaticOrGlobalInstead
It is possible to set other types of behaviors instead of calling an alternative method. You can throw an exception, return a value, ignore the method etc...
For instance:
TEST_METHOD(Alter_C_Function_Return_Value)
{
WHEN_CALLED(Sum (ANY_VAL(int), ANY_VAL(int))).Return(10);
Assert::AreEqual(10, Sum(1,2));
}
I don't think it's a good idea to overwrite functions at runtime. For one thing, the executable segment may be set as read-only and even if it wasn't you could end up stepping on another function's code if your assembly is too large.
I think you should create something like a function pointer collection for the one and the other set of implementations you want to use. Every time you want to call a function, you'll be calling from the selected function pointer collection. Having done that, you may also have proxy functions (that simply call from the selected set) to hide the function pointer syntax.

How to make external Mathematica functions interruptible?

I had an earlier question about integrating Mathematica with functions written in C++.
This is a follow-up question:
If the computation takes too long I'd like to be able to abort it using Evaluation > Abort Evaluation. Which of the technologies suggested in the answers make it possible to have an interruptible C-based extension function? How can "interruptibility" be implemented on the C side?
I need to make my function interruptible in a way which will corrupt neither it, nor the Mathematica kernel (i.e. it should be possible to call the function again from Mathematica after it has been interrupted)
For MathLink - based functions, you will have to do two things (On Windows): use MLAbort to check for aborts, and call MLCallYieldFunction, to yield the processor temporarily. Both are described in the MathLink tutorial by Todd Gayley from way back, available here.
Using the bits from my previous answer, here is an example code to compute the prime numbers (in an inefficient manner, but this is what we need here for an illustration):
code =
"
#include <stdlib.h>
extern void primes(int n);
static void yield(){
MLCallYieldFunction(
MLYieldFunction(stdlink),
stdlink,
(MLYieldParameters)0 );
}
static void abort(){
MLPutFunction(stdlink,\" Abort \",0);
}
void primes(int n){
int i = 0, j=0,prime = 1, *d = (int *)malloc(n*sizeof(int)),ctr = 0;
if(!d) {
abort();
return;
}
for(i=2;!MLAbort && i<=n;i++){
j=2;
prime = 1;
while (!MLAbort && j*j <=i){
if(i % j == 0){
prime = 0;
break;
}
j++;
}
if(prime) d[ctr++] = i;
yield();
}
if(MLAbort){
abort();
goto R1;
}
MLPutFunction(stdlink,\"List\",ctr);
for(i=0; !MLAbort && i < ctr; i++ ){
MLPutInteger(stdlink,d[i]);
yield();
}
if(MLAbort) abort();
R1: free(d);
}
";
and the template:
template =
"
void primes P((int ));
:Begin:
:Function: primes
:Pattern: primes[n_Integer]
:Arguments: { n }
:ArgumentTypes: { Integer }
:ReturnType: Manual
:End:
";
Here is the code to create the program (taken from the previous answer, slightly modified):
Needs["CCompilerDriver`"];
fullCCode = makeMLinkCodeF[code];
projectDir = "C:\\Temp\\MLProject1";
If[! FileExistsQ[projectDir], CreateDirectory[projectDir]]
pname = "primes";
files = MapThread[
Export[FileNameJoin[{projectDir, pname <> #2}], #1,
"String"] &, {{fullCCode, template}, {".c", ".tm"}}];
Now, here we create it:
In[461]:= exe=CreateExecutable[files,pname];
Install[exe]
Out[462]= LinkObject["C:\Users\Archie\AppData\Roaming\Mathematica\SystemFiles\LibraryResources\
Windows-x86-64\primes.exe",161,10]
and use it:
In[464]:= primes[20]
Out[464]= {2,3,5,7,11,13,17,19}
In[465]:= primes[10000000]
Out[465]= $Aborted
In the latter case, I used Alt+"." to abort the computation. Note that this won't work correctly if you do not include a call to yield.
The general ideology is that you have to check for MLAbort and call MLCallYieldFunction for every expensive computation, such as large loops etc. Perhaps, doing that for inner loops like I did above is an overkill though. One thing you could try doing is to factor the boilerplate code away by using the C preprocessor (macros).
Without ever having tried it, it looks like the Expression Packet functionality might work in this way - if your C code goes back and asks mathematica for some more work to do periodically, then hopefully aborting execution on the mathematica side will tell the C code that there is no more work to do.
If you are using LibraryLink to link external C code to the Mathematica kernel, you can use the Library callback function AbortQ to check if an abort is in progress.

modifying regula falsi method to the secant method

I have implemented the regula falsi method. I am trying to modify it so it becomes the secant method. A pdf I read mentioned that it is essentially the same with just one change.
Future guesses for my 'm' value should have a slightly different formula, instead of:
m = a - f(a) * ( (b-a)/( f(b)-f(a) ) );
it should be:
m = a - f(a) * ( (m-a)/( f(m)-f(a) ) );
but unfortunately it doesn't work (It never finds the root). What should I fix to get this into the secant method?
source code as follows:
#include <stdio.h>
#include <math.h>
void
secant(double a, double b, double e, double (*f)(double), int maxiter ) {
double m, fm, fa, fb;
int i;
fa=(*f)(a);
fb=(*f)(b);
m = a - fa * ( (b-a)/( fb - fa ) );
fm=(*f)(m);
for(i=0; i<maxiter; i++) {
if ( fabs(fm) <= e ) {
printf("f(%f) = %f\n", m, fm);
return;
} else if ((fa*fm) < 0) {
b=m;
fb=fm;
} else {
a=m;
fa=fm;
}
// the guess below works for regula falsi method:
// m = a - fa * ( (b-a)/(fb - fa));
//this was supposed to be the change to turn this into the secant method
m = a - fa * ( (m-a)/(fm - fa) );
fm=(*f)(m);
}
}
int main(){
secant(1,4,0.0001,sin,500);
return 0;
}
Thanks in advance
EDIT: Ok after playing around with pen and paper I finally got it it wasnt a simple change as I initially thought:
void secant(double a, double b, double e, double (*f)(double), int maxiter ) {
double m, fm, fa, fb;
int i;
fa=(*f)(a);
fb=(*f)(b);
for(i=0; i<maxiter; i++) {
m = a - fa * ( (b-a)/(fb - fa) );
fm=(*f)(m);
if ( fabs(fm) <= e ) {
printf("f(%f)=%f, iter: %d\n", m,fm,i);
return;
}
a=b;
b=m;
fa=fb;
fb=fm;
}
}
It's easier for the secant method to not find the root. Are you sure it should find it?
For testing, here is an example: http://www.mathcs.emory.edu/ccs/ccs315/ccs315/node18.html
(example 4.7) You'd want to run that example ( f(x)=x^6-x-1 , x0=1 x1=2, root x=1.347)
Either the PDF is wrong or you misunderstood it. Without reading the PDF it is impossible to say which or explain further. When I explain both methods, I say that the difference between regula falsi and secant method is the rule for updating a and b.
Compute the first two iterations of the secant method by hand. Then modify your program to print the values of a, b and m at every iteration (or use a debugger). That should give you a hint of what is happening.
On your example, the secant method should converge in a few iterations.
Secant method is an open-bracket method, whereas Regula-Falsi is closed-bracket type. So, your PDF is correct. To modify Regula-Falsi method to secant method you have to change the closed-bracket to open type.
See this example for Regula-Falsi method.
Here, the coding is such that one interval always remains constant.
Now, here is a sample program for Secant method.
Here, like the Regula method, two initial guesses are taken, but both the intervals keep on changing until the correct root is obtained. Obtain the initial two guesses manually.
And, about the rate of convergence, for Secant method it is super-linear, whereas for Regula it is linear. So, secant method converges way faster.

Resources