Evaluate a function with different KIND - fortran

Consider a function that adds two number (e.g. integer, Real). I have to write the same function with the same code many times but with different precision and then create an interface.
Can somebody give me an example how to do the same with Fortran select type.

No... But it is possible in a module
All the math for scalars and doubles already does exactly what you want, so the procedures would be mostly for functions or subroutines that are doing significantly more bespoke work than a simple add or multiply.
Do you have any starting example?
Is this for a course you are taking?
If it is for a course then search for "module procedure interface".

Related

Is there a library to convert C++ expressions to MathML or similar?

I have many calculations in my program. Now I want to convert these caculations to formulas that can be part of reports and documentation (PDF). I want to be 100% certain that the reports match the actual code. What I don't want to do is parse the code myself.
In proof-of-concepts I created classes that contain both the value and the string of an expression.
Expression a("a", 7);
Expression b("b", 3);
Expression c("c");
c = a * b;
std::cout << c.formula() << std::endl; // would print "c = a * b"
I don't want to handle all cases, such as if, loops, ... myself. So is there a library that can do the job?
Most ways of representing a formula don't have concise representations of every kind of C++ control flow structure. What more, C++ "math" isn't the same as abstract mathematical equations; C++ default integer math is bounded, floating point math isn't real numbers, etc.
You'd probably be better off removing the mathematics from the C++ code entirely. There are computing platforms that can produce formatted representations of their mathematics as part of their feature set.
This also depends on the kind of mathematics you are doing. If you are doing abstract algebra, you'd probably use a different program or engine than if you where doing number crunching simulations.
If you don't want to use a 3rd party program, what I would do in your situation is write my own domain specific language, and either parse it or use expression templates to build it, and then use the expression tree in two ways (one for computation and the other for display). My approach would probably be a bit different than what you are describing, but that is probably my abstract mathematics bias showing through.
Unless I am doing a LOT of calculation (like, many kilobytes of equations), the reliability of this would probably be lower than just transcribing the formulas.

FFTW in Fortran result contains only zeros

I have been trying to write a simple program to perform an fft on a 1D input array using fftw3. Here I am using a seismogram as an input. The output array is, however, coming out to contain only zeroes.
I know that the input is correct as I have tried doing the fft of the same input file in MATLAB as well, which gives correct results. There is no compilation error. I am using f95 to compile this, however, gfortran was also giving pretty much the same results. Here is the code that I wrote:-
program fft
use functions
implicit none
include 'fftw3.f90'
integer nl,row,col
double precision, allocatable :: data(:,:),time(:),amplitude(:)
double complex, allocatable :: out(:)
integer*8 plan
open(1,file='test-seismogram.xy')
nl=nlines(1,'test-seismogram.xy')
allocate(data(nl,2))
allocate(time(nl))
allocate(amplitude(nl))
allocate(out(nl/2+1))
do row = 1,nl
read(1,*,end=101) data(row,1),data(row,2)
amplitude(row)=data(row,2)
end do
101 close(1)
call dfftw_plan_dft_r2c_1d(plan,nl,amplitude,out,FFTW_R2HC,FFTW_PATIENT)
call dfftw_execute_dft_r2c(plan, amplitude, out)
call dfftw_destroy_plan(plan)
do row=1,(nl/2+1)
print *,out(row)
end do
deallocate(data)
deallocate(amplitude)
deallocate(time)
deallocate(out)
end program fft
The nlines() function is a function which is used to calculate the number of lines in a file, and it works correctly. It is defined in the module called functions.
This program pretty much tries to follow the example at http://www.fftw.org/fftw3_doc/Fortran-Examples.html
There might just be a very simple logical error that I am making, but I am seriously unable to figure out what is going wrong here. Any pointers would be very helpful.
This is pretty much how the whole output looks like:-
.
.
.
(0.0000000000000000,0.0000000000000000)
(0.0000000000000000,0.0000000000000000)
(0.0000000000000000,0.0000000000000000)
(0.0000000000000000,0.0000000000000000)
(0.0000000000000000,0.0000000000000000)
.
.
.
My doubt is directly regarding fftw, since there is a tag for fftw on SO, so I hope this question is not off topic
As explained in the comments first by #roygvib and #Ross, the plan subroutines overwrite the input arrays because they try the transform many times with different parameters. I will add some practical use considerations.
You claim you do care about performance. Then there are two possibilities:
You do the transform only once as you show in your code. Then there is no point to use FFTW_MEASURE. The planning subroutine is many times slower than actual plan execute subroutine. Use FFTW_ESTIMATE and it will be much faster.
FFTW_MEASURE tells FFTW to find an optimized plan by actually
computing several FFTs and measuring their execution time. Depending
on your machine, this can take some time (often a few seconds).
FFTW_MEASURE is the default planning option.
FFTW_ESTIMATE specifies that, instead of actual measurements of
different algorithms, a simple heuristic is used to pick a (probably
sub-optimal) plan quickly. With this flag, the input/output arrays are
not overwritten during planning.
http://www.fftw.org/fftw3_doc/Planner-Flags.html
You do the same transform many times for different data. Then you must do the planning only once before the first transform and than re-use the plan. Just make the plan first and only then you fill the array with the first input data. Making the plan before every transport would make the program extremely slow.

Compiling C++ code to .EXE which returns double [duplicate]

This question already has answers here:
What should main() return in C and C++?
(19 answers)
Closed 5 years ago.
I am working with a MATLAB optimization platform for black-box cost functions (BBCF).
To make the user free-handed, the utilized BBCF can be any executable file which inputs the input parameters of BBF and must output (return) the cost value of BBCF, so that the MATLAB BBCF optimizer finds the best (least cost) input parameter.
Considering that, from the one hand, my BBCF is implemented in C++, and from the other hand the cost value is a double (real number), I need to compile my code to an EXE file that outputs (returns) double.
But, to the best of my knowledge, when I compile a C++ code to EXE, it "mainly" compiles the main() function and its output is the output of main() function (i.e. 0 if running successful!).
An idea could be using a main function that returns double, and then, compiling such main() to EXE but, unfortunately, it is not possible in C++ (as explained in this link or as claimed in the 3rd answer of this question to be a bug of C++ neither of which are business of this question).
Can anyone provide an idea by which the EXE compiled form of a C++ code, outputs (returns) a double value?
This is not 'a bug in C++' (by the way, the bug might be in some C++ compiler, not in the language itself) - it's described in the standard that main() should return an integer:
http://en.cppreference.com/w/cpp/language/main_function
Regarding how to return a non-int from an executable, there are a couple of ways to do that. Two simplest (in terms of how to implement them) solutions come to my mind:
Save it to a file. Then either monitor that file in Matlab for changes (e.g. compare timestamps) or read after each execution of your EXE file depending on how you're going to use it. Not very efficient solution, but does the job and probably the performance penalty is negligible to that of your other calculations.
If you are fine with your cost value losing some numerical accuracy, you can just multiply the double value by some number (the larger this number, the more decimal places you will retain). Then round it, cast it to an int, have it returned from main(), cast it back to double in matlab and divide by the same number. The number used as the multiplier should be a power of 2 so that it doesn't introduce additional rounding errors. This method might be particularly useful if your cost value takes the values limited to the range [0, 1] or if you can normalize it to these values and you know that variations less than some threshold are not important.
In English, 'shall' is an even stronger imperative than 'must'.
Making a change like this would require changes to the operating system and shell. Such changes are unlikely to happen.
The easiest way to pass a double return would to to write it to standard output. Alternatively there are several methods available for interprocess communication.

Generic and specific functions to get real and imaginary parts of complex variables

In Fortran, I always work with double precision, so I have been using specific functions like dble and dimag to get real and imaginary parts of complex variables. However, for other functions like sin, I no longer use dsin because the former returns a value of proper kind (i.e., sin is a generic function). The same seems to hold for complex variables. So my question is:
1) What are the most recommended generic functions for getting real and imaginary parts?
-- It seems that real(z), aimag(z), and conjg(z) return a proper kind always (via experiments with gfortran), i.e., if z is double precision, those functions return double precision. Is this guaranteed? Also, is the behavior dependent on the standard used by the compiler? (i.e., Fortran 77 vs 90 or later, particularly for real(z)?)
2) If I (nevertheless) want to use specific functions that receives only double precision arguments and always return double precision values, what are the specific functions?
-- I have been using dble(z) and dreal(z), dimag(z), dconjg(z) up to now, but some web pages say that they are vendor extensions (though commonly supported by many compilers).
I have read various pages but the information is rather confusing (i.e., it is not very clear what is the "standard" way), so I would appreciate any advice on the choice of such functions.
As background, what do we mean by kinds of real and complex variables? Of course, you know what is meant by the kind of a real object.
A complex object consists of a real and an imaginary part. If a complex object has a given kind then each component is a real of kind corresponding to the kind of the complex object.
That's a long way of saying, if
complex(kind=k) z
then KIND(z%re) and KIND(z%im) both evaluate to k (using the complex part designators introduced by Fortran 2008 for clarity).
Now, the real intrinsic generic takes a complex expression and returns its real component. It does so subject to the following F2008 rule (13.7.138), where A is the argument:
If A is of type complex and KIND is not present, the kind type parameter is the kind type parameter of A.
So, yes: in current Fortran real without a requested kind will always give you a real of kind that of the complex's real component. Whether that's double precision or otherwise.
Similarly, aimag returns a real (corresponding to the imaginary part) of kind that of the complex number. Unlike real, aimag doesn't accept a kind= argument controlling the result kind.
Things are different for Fortran 77: there was no similar concept of kind, and just one complex.
dble is a standard intrinsic. Although this always returns a double precision it is still generic and will accept any numeric. dble(a) is the same as real(a,kind(0d0)), whatever the type of a. There is no (standard) specific.
dreal, dimag and dconjg are not standard intrinsics.
I suppose one could create specific wrappers around real if one cared greatly.

LPSolve - specify constant coefficients

I'm using LPSolve IDE to solve a LP problem. I have to test the model against about 10 or 20 sets of different parameters and compare them.
Is there any way for me to keep the general model, but to specify the constants as I wish? For example, if I have the following constraint:
A >= [c]*B
I want to test how the model behaves when [c] = 10, [c] = 20, and so on. For now, I'm simply preparing different .lp files via search&replace, but:
a) it doesn't seem too efficient
b) at some point, I need to consider the constraint of the form A >= B/[c] // =(1/[c]*B). It seems, however, that LPSolve doesn't recogize the division operator. Is specifying 1/[c] directly each time the only option?
It is not completely clear what format you use with lp_solve. With the cplex lp format for example, there is no better way: you cannot use division for the coefficient (or even multiplication for that matter) and there is no function to 'include' another file or introduce a symbolic names for a parameter. It is a very simple language, and not suitable for any complex task.
There are several solutions for your problem; it depends if you are interested in something fast to implement, or 'clean', reusable and with a short runtime (of course this is a compromise).
You have the possibility to generate your lp files from another language, e.g. python, bash, etc. This is a 'quick and dirty' solution: very slow at runtime, but probably the faster to implement.
As every lp solver I know, lp_solve comes with several modelling interfaces: you can for example use the GNU mp format instead of the current one. It recognizes multiplication, divisions, conditionals, etc. (everything you are looking for, see the section 3.1 'numeric expressions')
Finally, you have the possibility to use directly the lp_solve interface from another programming language (e.g. C) which will be the most flexible option, but it may require a little bit more work.
See the lp_solve documentation for more details on the supported input formats and the API reference.