I have a module that consists of many small subroutines and one main subroutine, which is the only one that is public. The rest of the subroutines are private and called by the main subroutine or within them. The main subroutine has to take all the necessary arguments to perform its work, but often when it delivers a task to a private subroutine, it has to pass again some of the arguments. I would like to avoid this when dealing with arrays. With scalar numbers I can simply define a module wide variable and assign it the corresponding value in the main subroutine:
module test
integer, private :: m, n
private :: foo
public :: main
contains
subroutine main(matrixA, m0, n0)
integer, intent(in) :: m0, n0
real, intent(inout) :: matrixA(m0,n0)
!assign values to module variables m & n
m = m0
n = n0
...
!no need to pass m0 & n0
call foo(matrixA)
end subroutine
subroutine foo(matrixA)
real, intent(inout) :: matrixA(m,n)
...
end subroutine
end module
I would like to also not need to pass matrixA at all. What is the best way to do this? By best, I mean giving the best performance.
I can't comment on the "best" way, but there are some things to say. And now the question has been edited to point "best" in the direction of performance I'll add something else.
The question appears to be made under the premise that arrays cannot be module variables. They can be, even allocatable/pointer (deferred-shape) ones.
In the examples that follow I'll make the assumption that the array dummy argument in main will be assumed-shape. This is just to make things simpler in the form; changing to explicit-shape is a simple extension.
First, just like we set m and n in the question, we can set a module array variable.
module test
private ! Have this as default
public main ! But we do want a way in
integer m, n
real, allocatable :: matrixA(:,:)
contains
! In this subroutine we're making an assumption that the person asking isn't
! wholly correct in not wanting to assume shape. But we can change that if
! required. It's just a more natural thing if one can.
subroutine main(matrix) ! Note, not passing m, n
real, intent(inout) :: matrix(:,:) ! It's assumed shape
m = SIZE(matrix,1)
n = SIZE(matrix,2)
matrixA = matrix ! Copy in to the module's matrixA
call foo()
! .... etc.
matrix = matrixA ! Copy back out to the dummy
end subroutine main
subroutine foo
! Here we have access to the module's matrixA
! And we do our stuff
end subroutine foo
end module test
Note the use of the assumed-shape dummy argument and the discussion above. To avoid copying in this example, one could think about whether using a pointer is a suitable thing.
With the copy, that's not going to be good performance (assuming the array is biiig). So:
module test
implicit none
private
integer m, n ! If we want these we'll have to set them somehow
real, allocatable, public :: matrixA(:,:)
public main
contains
subroutine main()
! Stuff with matrixA host-associated
end subroutine main
end module test
program hello
use test, only : matrixA, main
implicit none
matrixA = ... ! Set this: it's matrixA from the module
call main
end program hello
As we care about "performance" rather than "encapsulation" that seems like a reasonable thing. However, having encapsulation, performance and reduced-argument passing, we could consider, rather than using a module variable for matrixA, having the work subroutines internal to main.
module test
contains
subroutine main(matrixA)
real, intent(inout) :: matrixA(:,:)
call foo
contains
subroutine foo
! Here we have access to matrixA under host association
end subroutine foo
end subroutine main
end module test
In many circumstances I prefer this last, but wouldn't say it's best, or even preferred under all circumstances. Note, in particular, that if foo already has an internal subprogram we'll start to wonder about life.
I feel the first is rather extreme just to avoid passing as an argument.
Related
During the last few years, I have been creating several modules with subroutines that I then use for different projects. I am having problems when I define parameter variables in one of those project-specific files that conflict with a variable name defined within those modules. Is it possible to make those names subroutine-private or module-private?
Here is an example. Suppose I have the following module:
module mymod
implicit none
contains
subroutine test1(x)
real, intent(in) :: x(:)
print *, x**2.0
end subroutine test1
end module mymod
This module is then called by the main program
program main
use mymod
implicit none
real :: y
real,dimension(2,1),parameter :: x = [1.0,2.0]
y = 3.0
call test1(y)
end program main
In this case, given that x in the main program is defined as a parameter with different dimensions to the x in subroutine test1, there will be problems when compiling (shape matching rules violated). Is there any way of making x in module mymod private within the module?
I know an option could be to use "non-common" variable names in my modules or have a list of forbidden names, but that seems complicated at this point (requires editing too many files and lose consistency of notation with books/papers where these procedures are outlined), and would make collaboration with colleagues more difficult.
Two different questions in one:
Why is the example program failing to compile:
This has nothing to do with public or private, or x being defined in the program itself.
It has everything to do with the fact that in the module, x as a parameter is defined as a 1-d array, and in the main program, y is a scalar.
Try it, remove the declaration of x in the main program and it will still fail.
(In fact, the declaration doesn't work like that anyway, you declare x as a 2-d array (shape 2, 1), but then give it a 1-d array. You'd have to do something like:
real, dimension(2, 1), parameter x = reshape([1.0, 2.0], [2, 1])
But to get rid of the error you describe, you either need to change the subroutine interface by removing the (:) behind the real, intent(in) :: x, or change the call to call test1([y]).
What can you do when 2 modules import different variables of the same name:
It would be different if you were to say have this:
module modA
implicit none
real, parameter :: x = 2.0
contains
subroutine subA(k)
real, intent(in) :: k
print *, k*x
end subroutine subA
end module modA
module modB
implicit none
real :: x(3)
end module modB
program progtest
use modA
use modB
implicit none
call subA(x(1))
end program progtest
In this example, it would try to import the variable x from both modules.
Ways to avoid it:
Make one x private:
implicit none
real, parameter, private :: x = 2.0
or
real, parameter :: x = 2.0
private :: x
or
implicit none
private
real, parameter :: x = 2.0
public :: subA
Only import the parts that you need:
program progtest
use modA, only: subA
use modB
implicit none
...
Rename one or both of the x:
use modA
use modB, only: xB => x
...
call subA(xB(1))
This is part of a main program
PROGRAM program1
USE method
USE variables
IMPLICIT NONE
:
CALL method_init(A,a1end,C)
:
END PROGRAM program1
The call to method_init, contained in the module method, "initializes" a method in that it builds arrays a1end and C form the array A (other calls to other procedures contained in the module should follow).
Arrays a1end and C are part of the method, so they are both declared in the method module; the array A is not part of the method (it could be "solved" with another method), so it is declared in the module variables.
The arrays C and a1end could be used by subroutines not contained in the method module, so they must be declared before the CONTAINS statement.
So, the subroutine contained in the method module could use these variables without using them as input/output variables, but this would make unclear the role of the subroutine (the call would be simply CALL method_init, so "How does this subroutine operate? Which arrays does it use? And which modify? ..."), so I prefer to have the call as CALL method_init(A,a1end,C).
This means that the module method is like this
MODULE method
IMPLICIT NONE
REAL, DIMENSION(:,:), ALLOCATABLE :: C ! declared here to be used...
REAL, DIMENSION(:,:), ALLOCATABLE :: a1end ! ...by procedures outside this module
:
CONTAINS
SUBROUTINE method_init(A,a1end,C)
IMPLICIT NONE
REAL, DIMENSION(:,:), ALLOCATABLE, INTENT(IN) :: A ! deferred shape (it's allocated elsewhere in the main program)j
REAL, DIMENSION(:,:), ALLOCATABLE, INTENT(OUT) :: C ! declared here to be used...
REAL, DIMENSION(:,:), ALLOCATABLE, INTENT(OUT) :: a1end ! ...as input/output variables
:
ALLOCATE(C( ),a1end( ))
:
END SUBROUTINE method_init
END MODULE method
I'd like to know if this is a correct way of programming. Is it just a matter of taste?
EDIT The question, in short, is:
Is a correct way of programming to use variables defined in a module as input/output arguments of procedure contained in the module itself? Or it is better to write subroutines with no arguments? Or everything is just a matter of taste?
The questions/answers linked by #Vladimir F make me think that yes, it' a matter of taste. Nevertheless none of these question touches the specific point I'm interested into (i.e. procedures that are in a module and use a variable defined in the module as input/output arguments).
My answer would be that you did the right choice as I would always recommend to write procedures with all its parameters and avoid using global variables (like C and a1end in your example).
However, many people in Fortran use to use global variables and would not bother passing these arguments, sometimes for wrong reason (like "it's faster to write").
But it is still totally correct to use global variable in a module if you imagine the latter as being a box containing its own specific and unique set of parameters. Maybe then you would want to specify them as Fortran parameter (with the associated keyword).
When you question yourself about passing arguments or using global variables for a function/subroutine, a simple choice would be whether or not your function is bound to be called/reused with other different parameters somewhere else in your code, or sometime later in your development process.
This is particularly true when you think of your module as a box that you can unplug and give to a mate for his own needs, then you might want your method_init to be more flexible, thus expliciting the arguments.
Note: in your example, I would recommend to name your subroutine arguments differently than your module's variables in order to avoid any confusion in the code and be able to use them without any conflict:
MODULE method
IMPLICIT NONE
REAL, DIMENSION(:,:), ALLOCATABLE :: C
REAL, DIMENSION(:,:), ALLOCATABLE :: a1end
CONTAINS
SUBROUTINE method_init(A,my_a1end,my_C)
IMPLICIT NONE ! Already specified above
REAL, DIMENSION(:,:), ALLOCATABLE, INTENT(IN) :: A
REAL, DIMENSION(:,:), ALLOCATABLE, INTENT(OUT) :: my_C
REAL, DIMENSION(:,:), ALLOCATABLE, INTENT(OUT) :: my_a1end
ALLOCATE(my_C( ),my_a1end( ))
! Here you can work with module's C and a1end
! Given that they have been effectively allocated
! You can also test whether C and my_C are the same object or not (pointerwise speaking)
END SUBROUTINE method_init
END MODULE method
I am trying to add access restrictions to some of the variables (using private attribute) in a module but I need to use those variables in subsequent invocations of routines within that module:
module MyMod
private
integer,allocatable :: A(:)
public :: init,calc
contains
subroutine init()
! allocating and initializing A
end subroutine init
subroutine calc()
! Using A
end subroutine
end module
Questions:
Is this true that the private variable will not be in the scope of the program which uses this module.
If the answer to 1 is yes, then I would think that I can use save attribute for this variable. Please correct me if I am wrong?
Is this the proper way to perform this task?
Yes, if you put a private statement into your module without any further specification, you set the default accessibility to private.
For the first question, the Fortran 2008 Standard (Cl. 4.5.2.2 §3) states that:
If a type definition is private, then the type name, and thus the structure constructor (4.5.10) for the type, are accessible only within the module containing the definition, and within its descendants.
So A will not be accessible from anywhere outside the module or submodule (descendant).
For the second question, yes - you can use save here. (This is not related to the accessibility attribute). In fact, starting with Fortran 2008, this is implied for module variables, see for the Fortran 2008 Standard (Cl. 5.3.16 §4) [thanks #francescalus]:
A variable, common block, or procedure pointer declared in the scoping unit of a main program, module, or submodule implicitly has the SAVE attribute, which may be confirmed by explicit specification [...]
If I understood your third question correctly, it is related to the initialization. You could realize this with a function/subroutine to which you pass an array for initialization:
module MyMod
! ...
contains
! ...
subroutine init( A_in )
implicit none
integer, intent(in) :: A_in(:)
! allocating and initializing A
allocate( A(size(A_in)) )
A = A_in
end subroutine
end module
Inside init() you create a copy of A_in which is only accessible within the module. As long as calc() is part of the module (or a submodule thereof), it has full access to A.
To add to the answer by Alexander Vogt an implication of the save attribute.
This attribute gives precisely the effect you seem to be after (from F2008 5.3.16):
The SAVE attribute specifies that a local variable of a program unit or subprogram retains its association status, allocation status, definition status, and value after execution of a RETURN or END statement unless [something not applicable here]
In your example, A is a local variable of the module (and so a program unit) MyMod.
This means that, after the call to init which, presumably, allocates A and sets values that status is retained after the subroutine returns. Those values are then available come the call to calc. Both init and calc, of course, refer to the same A through host association.
You mention Fortran 90, so there is a subtle change (again as mentioned in that other answer). Before Fortran 2008 module variables would require the save attribute explicitly giving in some circumstances for this effect to come about. There's no harm in giving the save attribute explicitly if you aren't sure how your compiler treats the code (and some would say it's good practice, anyway).
This is another way of accomplishing what you want to do while avoiding the 'save'.
module MyMod
private
public :: myType, init
type myType
private
integer, allocatable :: A(:)
end type myType
contains
subroutine init(obj, n)
type(myType), intent(inout) :: obj
integer, intent(in) :: n
allocate(obj%A(n), source=-9999999)
end subroutine init
end module MyMod
program test
use MyMod, only: myType, init
type(myType) :: m ! m is an opaque object
call init(m, 10)
end program test
In this example, m is an opaque object - I can create the object, pass it around, but not access its contents (the array A in this case). This way, I am hiding my data. As long as my object m is in scope, I can operate on the data hidden in the object through routines contained in the module myMod.
If you have access to a modern compiler that supports Fortran 2003, you can rewrite the module as
module MyMod
private
public :: myType
type myType
private
integer, allocatable :: A(:)
contains
procedure, public :: init
end type myType
contains
subroutine init(obj, n)
class(myType), intent(inout) :: obj
integer, intent(in) :: n
allocate(obj%A(n), source=-9999999)
end subroutine init
end module MyMod
program test
use MyMod, only: myType
type(myType) :: m ! m is an opaque object
call m%init(10)
end program test
Lets say there is a vector:
REAL(KIND=dp), DIMENSION(maxn) :: rho
which is allocated values in an initial subroutine (along with dp and maxn) and is called from the main program.
The main program then calls a module which contains a (different) subroutine to evolve rho. The subroutine argument for rho is defined as:
SUBROUTINE sum_density(a, b, c, ....., rho)
In this subroutine rho is declared as:
REAL(KIND=dp), DIMENSION(maxn), INTENT(OUT) :: rho
Yet the code contains the following line, prior to any values being associated with rho:
foo1= foo2*foo3(i)/rho(i)
I would have thought that the module subroutine would not have had access to the rho defined in the main program. I expected the compiler to complain and require the intent to be changed to (INOUT) or say something like rho is undefined. Even if I do change it to (INOUT) there is no difference in the results. The module subroutine must be accessing the value of rho in the main program and using it even though the intent is declared as OUT.
My question is - In this scenario what is the difference between using in INTENT(OUT) and the INTENT(INOUT)?
With the INTENT(OUT) the program is not standard conforming, because it accesses the array which has an undefined value.
However, the software implementation is likely to work, because of the way explicit shape arrays are usually implemented - by passing the address of the array. If the array you passed was non-contiguous, let's say
rho(::2)
the compiler is likely to create a copy, which is passed and you are likely to encounter a problem, because the array may contain garbage with intent(out).
Regarding the warning, they are not obligatory but compilers do warn about this if you use flags such as -warn or -Wall.
For intent(in) the difference comes out when you try to modify rho. If you try that the compiler has to issue an error.
About the scope:
It is not really correct to talk about the scope here, the original rho is definitely not in the scope of the subroutine, only the dummy argument is. The re-use of the same name is perhaps confusing. Imagine they are actually called rho1 in the program and rho2 in the subroutine. Then it is clear that rho1 is not in the scope of the subroutine, but rho2 is.
Now, rho2 is not guaranteed to have the same value as rho1 at the start of the subroutine with intent(out), but it is guaranteed to have it with intent(inout). The reason is that the argument passing may be implemented using copy-in and copy-out and the copy-in can be omitted for intent(out).
Consider this code:
module m
contains
subroutine sub(a2)
real, intent(out) :: a2(4)
print *,a2
a2 = 2
end subroutine
end
use m
real :: a1(8)
a1 = 1
call sub(a1(::2))
end
With some compiler it prints 4 times one, as one might expect, but with others or with some compiler parameters it prints garbage:
sunf90 intent2.f90
./a.out
5.879759E-39 0.0E+0 0.0E+0 0.0E+0
I hope this is not a too stupid question, but is it possible to have functions or subroutines where I can pass the type of an array like
subroutine foo(array, arr_type)
implicit none
arr_type, dimension(:) :: array
*Do something with array*
end subroutine
or do I have to write a subroutine for each possible arr_type (e.g. integer, double precision,...) and overload the subroutine with an interface ?
Yes and no... You can bundle several functions/subroutines with different dummy arguments using an interface:
module foos
interface foo
module procedure foo_real
module procedure foo_int
end interface
contains
subroutine foo_real( a )
implicit none
real,intent(inout) :: a(:)
! ...
end subroutine
subroutine foo_int( a )
implicit none
integer,intent(inout) :: a(:)
! ...
end subroutine
end module
I know of no (simple) possibility to pass arrays with arbitrary basic type. You could take a look at transfer - but there be dragons ;-)
You could experiment with Fortran 2003's unlimited polymorphism. Write your subroutine a bit like this:
subroutine foo(array)
implicit none
class(*), dimension(:) :: array
! Do something with array
end subroutine
From the point of view of abbreviating code this won't save you much because you're likely to have to write something like
use, intrinsic :: iso_fortran_env, only : real32, real64
.
.
.
select type (element=>array(1))
type is (real(real32))
! Code for 32-bit reals
type is (real(real64))
! Code for 64-bit reals
type is (integer)
! Code for integers of default kind
class is (shape)
! Code for shapes
class default
! Sweep up everything else
end select
But you may end up writing as many lines as if you follow Alexander Vogt's entirely sensible approach.
EDIT, after comments
What this approach won't deliver, because Fortran doesn't include its intrinsic types in any sort of type hierarchy, is a code such as
select type (element=>array(1))
class is (number)
! Code for any type and kind of Fortran number
That would be useful, but I don't see it happening soon.