Fortran, static library creating and simplifying (newbie here) - fortran

I'm somewhat new to Fortran, but I'm starting to collect a lot of functions and subroutines in modules that I use over and over again. I've been trying to build my own library so that I could call some of these functions and subroutines from new source code that I write. So far I've been able to get the subroutines to work, but not the functions. I just don't know how to call the function from with in the code.
Here's an example. The following function takes in an integer and returns the Identity matrix.
module test
contains
function IDENTITY(rows) !RETURNS THE IDENTITY MATRIX
real, dimension(rows,rows) :: IDENTITY
integer, intent(in) :: rows
integer :: i, j
!f2py intent(in) rows
!f2py intent(out) IDENTITY
!f2py depend(rows) IDENTITY
IDENTITY = ZEROS(rows,rows)
do i = 1, rows
do j = 1, rows
if (i == j) then
IDENTITY(i,j) = 1
endif
enddo
enddo
end function IDENTITY
end module
Now I compile this into an object file then archive it into a library. I then write a small program in which I'd like to use this function--and here's the problem I want to avoid. I've figured I have to put a \use\ statement in my source so that it will use the module. Then I've got to include the path to the .mod when compiling. But eventually, I'm going to have a whole section full of use statements. I'd like to avoid having to do all those things and just make everything nice and neat. Is there a way? Any help would be great,
Thank You

You can put many subroutines and functions into the contains section of one module. You don't need a separate module for each. It makes sense to organize your code by creating modules/files for related procedures (subroutines and functions).
Libraries are a good strategy that I used to use. In this era
I usually don't bother with the library. Compilers are so fast that I just compile the files with the modules needed by the program. It depends on how big your code is.
You invoke a subroutine with a call statement. You invoke a function by using it in an expression such as an assigment statement:
x = sin (y)
matrix = identity (n)
P.S. Instead of:
do i = 1, rows
do j = 1, rows
if (i == j) then
IDENTITY(i,j) = 1
endif
enddo
enddo
why not:
do i = 1, rows
IDENTITY(i,i) = 1
enddo
Do you have a function ZEROS to zero your matrix? The language will do that with an assigment statement:
IDENTITY = 0.0

Related

How to verify in Fortran whether an iterative formula of a non-linear system will converge

How to verify in Fortran whether an iterative formula of a non-linear system will converge to the root near (x,y)?
It was easy for a programming language which support symbolic computations. But how to do that in Fortran? Like getting partial derivative of the component functions and check whether they bounded near the root. But I couldn't do that in fortran or haven't the idea how to do that. It will be a great help for me if anyone give me some idea for the following non-linear system now or if possible for a general case.
I want to use Fixed point iteration method for this case
Main system:
x^2+y=7
x-y^2=4
Iterative form (given):
X(n+1)=\sqrt(7-Y(n)),
Y(n+1)=-\sqrt(X(n)-4),
(x0,y0)=(4.4,1.0)
Theorem (which I follow)
The issue is, I need to check the boundedness of the partial derivatives of \sqrt(7-Y) and -\sqrt(X-4) on some region around (x0,y0)=(4.4,1.0). I can write the partial derivative function in fortran but how to evaluate so many values and check it is bounded around the (4.4,1.0).
Update
One possibly right solution would be to get arrays of values around (4.4,1.0) like (4.4-h,1.0-h)*(4.4+h,1.0+h) and evaluate the defined partial derivative function and approximate their boundedness. I haven't encounter such problem in Fortran, so any suggestion on that also can help me a lot.
If you just want to check the boundedness of a function on a grid, you can do something like
program verify_convergence
implicit none
integer, parameter :: dp = selected_real_kind(15, 307)
real(dp) :: centre_point(2)
real(dp) :: step_size(2)
integer :: no_steps(2)
real(dp) :: point(2)
real(dp) :: derivative(2)
real(dp) :: threshold
integer :: i,j
real(dp) :: x,y
! Set fixed parameters
centre_point = [4.4_dp, 1.0_dp]
step_size = [0.1_dp, 0.1_dp]
no_steps = [10, 10]
threshold = 0.1_dp
! Loop over a 2-D grid of points around the centre point
do i=-no_steps(1),no_steps(1)
do j=-no_steps(2),no_steps(2)
! Generate the point, calculate the derivative at that point,
! and stop with a message if the derivative is not bounded.
point = centre_point + [i*step_size(1), j*step_size(2)]
derivative = calculate_derivative(point)
if (any(abs(derivative)>threshold)) then
write(*,*) 'Derivative not bounded'
stop
endif
enddo
enddo
write(*,*) 'Derivative bounded'
contains
! Takes a co-ordinate, and returns the derivative.
! Replace this with whatever function you actually need.
function calculate_derivative(point) result(output)
real(dp), intent(in) :: point(2)
real(dp) :: output(2)
output = [sqrt(7-point(2)), -sqrt(point(1)-4)]
end function
end program
I know the function calculate_derivative doesn't do what you want it to, but I'm not sure what function you actually want from your question. Just replace this function as required.
The main question is different: How can you calculate the solution of the mathematical problem without the help of any software? If you know that, we can program it in fortran or any language.
In particular, and assuming that n=0,1,2,3... to solve your problem you need to know X(0) and Y(0). With this you calculate
X(1)=\sqrt(7-Y(0)),
Y(1)=-\sqrt(X(0)-4)
Now you know X(1) and Y(1), then you can calculate
X(2)=\sqrt(7-Y(1)),
Y(2)=-\sqrt(X(1)-4)
etc.
If your system of equations converge to something, until some iterations (for example, n=10, 20, 100) you going the check that. But because the nature of fortran, it will not give you the solution in a symbolic way, it is not its goal.

Can I make a variable persist across multiple function calls but be local to each thread in openMP fortran?

Using openMP in Fortran, is there any way to create a variable which is local to each thread but saved between function calls? Basically like a 'save' variable which is local to each thread.
For example, I'm trying to implement the Box-Muller transform to generate uniform random numbers, with the following code (which I know works perfectly when NOT called in an openMP parallel region):
function rand_norm(seed)
implicit none
integer*8, intent(inout) :: seed
real*8 :: rand_norm
real*8 :: u, v
real*8, save :: second_rand
integer, save :: avail_flag = 0
if (avail_flag.eq.1) then
rand_norm = second_rand
avail_flag = 0
return
end if
avail_flag = 1
u = rand_float(seed)
v = rand_float(seed)
second_rand = sqrt(-2.D0*log(u))*cos(2.D0*PI*v)
rand_norm = sqrt(-2.D0*log(u))*sin(2.D0*PI*v)
end function
However, the problem arises that when calling this from within a parallel region, the two 'save' variables are now shared between threads, which defeats the purpose.
Is there any simple way to make these two variables local to each thread, but still persist between function calls?
I'm aware there are other ways to solve this problem (which I have done in a fairly messy way in the past), so if what I'm asking isn't directly possible, what is the best way to get around the issue? Should I just feed in the 'saved' values as arguments to the function?

Function declared in module using interface

I have a code as follows:
The function is declared in a module using an interface block
module my_subs
implicit none
interface
function cross(a,b)
integer, dimension(3) :: cross
integer, dimension(3), intent(in) :: a, b
end function cross
end interface
end module my_subs
program crosstest
use my_subs
implicit none
integer, dimension(3) :: m, n
integer, dimension(3) :: r
m = [1, 2, 3]
n = [4, 5, 6]
r = cross(m,n)
write(*,*) r
end program crosstest
function cross(a,b)
implicit none
integer, dimension(3) :: cross
integer, dimension(3), intent(in) :: a, b
cross(1) = a(2)*b(3) - a(3)*b(2)
cross(2) = a(3)*b(1) - a(1)*b(3)
cross(3) = a(1)*b(2) - a(2)*b(1)
end function cross
According to this website, the use of interface blocks allows main programs and external subprograms to interface appropriately. However, I tested different mismatch of array size scenarios, I got the following result:
Change dimension at line 6 to 2 and 4, the code cannot be compiled;
Change dimension at line 7 to 2, the code can be compiled and produce the correct output;
Change dimension at line 7 to 4, the code cannot be compiled;
Change dimension at line 27 to 2 and 4, the code can be compiled and produce the correct output;
Change dimension at line 28 to 2 and 4, the code can be compiled and produce the correct output;
I am confuse about the different scenarios I performed, because I suppose the use of interface can help me to detect any mismatch of array size. In this case, is it better for me to move the function cross(a,b) into the module my_subs using contains?
You can check the interface by putting some declarations in function cross that test whether the interface as declared in module my_subs matches what function cross thinks its interface should be:
interface in function cross:
module my_subs
implicit none
interface
function cross(a,b)
integer, dimension(3) :: cross
integer, dimension(3), intent(in) :: a, b
end function cross
end interface
end module my_subs
program crosstest
use my_subs
implicit none
integer, dimension(3) :: m, n
integer, dimension(3) :: r
m = [1, 2, 3]
n = [4, 5, 6]
r = cross(m,n)
write(*,*) r
end program crosstest
function cross(a,b) result(res)
use my_subs, only: check => cross
implicit none
integer, dimension(3) :: res
integer, dimension(3), intent(in) :: a, b
procedure(check), pointer :: test => cross
res(1) = a(2)*b(3) - a(3)*b(2)
res(2) = a(3)*b(1) - a(1)*b(3)
res(3) = a(1)*b(2) - a(2)*b(1)
end function cross
gfortran zaps this in all cases of mismatch you tested. I'm not sure that it should: if TKR of a dummy argument matches, shouldn't the rules of sequence association produce a correct invocation of the procedure? I haven't used submodules, but I think that they might do roughly the same thing as my example does.
When using an interface block to provide an explicit interface within a scope (in this case, in the module, which is then used by the main program) it is a requirement on the programmer that the specified interface matches the actual procedure.1
As given first, these things match happily. Changing the size of the function result or dummy arguments of one statement of the procedure but not the other creates a mismatch. Such code is a violation of the Fortran standard.
In general, a compiler isn't required to detect this violation. It may take your interface block on faith or it may do some extra work to see whether it should believe you. This latter is possible, especially if the external procedure is given in the same file as the interface block. You may see some error messages relating to this.
Further, if the interface block is given, the compiler will test the reference to the procedure against the interface, not the procedure's actual definition.
One failing, on the programmer's part, is if the actual argument isn't compatible with the dummy argument. Such a case is when the dummy argument is an explicit shape array but the actual argument is smaller than the dummy argument. [It isn't an error to have the actual argument larger.]
This problem is one of your cases:
interface
function cross(a,b)
integer, dimension(3) :: cross
integer, dimension(4), intent(in) :: a, b ! Dummy extent 4
end function cross
end interface
print*, cross([1,2,3], [4,5,6]) ! Actuals extent 3
end
Again, a compiler isn't obliged to notice this for you. It's being nice in the case where it can detect the problem.
Now, in another case you are stating that the function result is an array of shape [4] or [2]. But you are trying to assign that to an array of shape [3]. That won't work.
In conclusion, if you use an interface block to provide an explicit interface for an external procedure make sure it is correct. Turning the external procedure into a module procedure means it's the compiler's responsibility, not yours, to have the correct interface visible.
1 "Matching" here means that the characteristics of the procedure as stated by the interface block are consistent with the procedure's definition. The extents of the function result and dummy arguments are part of this. A procedure defined pure needn't have the interface block stating it is pure.

Fortran modules and C++ with Eigen

I am a Fortran user and a complete newbie to C++ and Eigen. I use modules in Fortran to be able to keep my variables, arrays and matrices in different groups and use them as needed. How to implement the idea of modules in Fortran in C++ so that I am able to pass on the data between different subroutines? I cannot paste the entire Fortran code as it is too large and there will be many new concepts which I would like to write directly in C++. Perhaps, a sample snippet or document showing how to pass on the information between C++ routines could be useful. I want to do something like this (and much more) in C++:
!*************************************************************************
! **** module file: module.f95 ****
module global
save
integer, allocatable :: kod(:,:)
end module
module local
save
integer, allocatable :: kode(:)
real*8, allocatable :: func1(:)
integer pts
end module
module fileunits
save
integer,parameter :: file1 = 11, file2 = 12
end module
!*************************************************************************
! Main program
program main
use global
use local
use fileunits
implicit none
int i,j,k,n
open(unit=file1,file='input.dat')
open(unit=file2,file='output.dat')
read(file1, *) n,pts
allocate(kod(n,pts))
allocate(kode(pts), func1(pts))
do I = 1, n
read(file1, *) (kod(i,j),j=1,pts)
do J=1,pts
kode(j) = kode(i,j)
end do
call proc1
write(file2,*) ((func1(j), j =1, pts)
end do
end program
subroutine proc1
use local
implicit none
int j
do j=1,pts
funct1(j) = kode(j) * kode(j)
...
...
end do
end subroutine

Fortran SAVE statement

I've read about the save statement in the (Intel's) language reference document, but I cannot quite grasp what it does. Could someone explain to me in simple language what it means when the save statement is included in a module ?
In principal when a module goes out-of-scope, the variables of that module become undefined -- unless they are declared with the SAVE attribute, or a SAVE statement is used. "Undefined" means that you are not allowed to rely on the variable having the previous value if you again use the module -- it might have the previous value when you re-access the module, or it might not -- there is no guarantee. But many compilers don't do this for module variables -- the variables probably retain their values -- it isn't worth the effort for the compiler to figure out whether a module remains in scope or not and probably module variables are treated as global variables -- but don't rely on that! To be safe, either use "save" or "use" the module from the main program so that it never goes out of scope.
"save" is also important in procedures, to store "state" across invocations of the subroutine or function (as written by #ire_and_curses) -- "first invocation" initializations, counters, etc.
subroutine my_sub (y)
integer :: var
integer, save :: counter = 0
logical, save :: FirstCall = .TRUE.
counter = counter + 1
write (*, *) counter
if (FirstCall) then
FirstCall = .FALSE.
....
end if
var = ....
etc.
In this code fragment, "counter" will report the number of invocations of subroutine x. Though actually in Fortran >=90 one can omit the "save" because the initialization in the declaration implies "save".
In contrast to the module case, with modern compilers, without the save attribute or initialization-on-a-declaration, it is normal for local variables of procedures to lose their values across invocations. So if you attempt to use "var" on an later call before redefining it in that call, the value is undefined and probably won't be the value calculated on a previous invocation of the procedure.
This is different from the behavior of many FORTRAN 77 compilers, some of which retained the values of all local variables, even though this wasn't required by the language standard. Some old programs were written relying on this non-standard behavior -- these programs will fail on the newer compilers. Many compilers have an option to use the non-standard behavior and "save" all local variables.
LATER EDIT: update with a code example that shows incorrect usage of a local variable that should have the save attribute but doesn't:
module subs
contains
subroutine asub (i, control)
implicit none
integer, intent (in) :: i
logical, intent (in) :: control
integer, save :: j = 0
integer :: k
j = j + i
if ( control ) k = 0
k = k + i
write (*, *) 'i, j, k=', i, j, k
end subroutine asub
end module subs
program test_saves
use subs
implicit none
call asub ( 3, .TRUE. )
call asub ( 4, .FALSE. )
end program test_saves
Local variable k of the subroutine is intentionally misused -- in this program it is initialized in the first call since control is TRUE, but on the second call control is FALSE, so k is not redefined. But without the save attribute k is undefined, so the using its value is illegal.
Compiling the program with gfortran, I found that k retained its value anyway:
i, j, k= 3 3 3
i, j, k= 4 7 7
Compiling the program with ifort and aggressive optimization options, k lost its value:
i, j, k= 3 3 3
i, j, k= 4 7 4
Using ifort with debugging options, the problems was detected at runtime!
i, j, k= 3 3 3
forrtl: severe (193): Run-Time Check Failure. The variable 'subs_mp_asub_$K' is being used without being defined
Normally, local variables go out of scope once execution leaves the current procedure, and so have no 'memory' of their value on previous invocations. SAVE is a way of specifying that a variable in a procedure should maintain its value from one call to the next. It's useful when you want to store state in a procedure, for example to keep a running total or maintain a variable's configuration.
There's a good explanation here, with an example.
A short explanation could be: the attribute save says that the value of a variable must be preserved across different calls to the same subroutine/function. Otherwise normally when you return from a subroutine/function, "local" variables lose their values since the memory where those vars were stored is released. It is like static in C, if you know this language.