Passing an object from one module into a subroutine of another module - oop

I have two module files mod1.f95 and mod2.f95. Mod1 has mathematical functions such as rk4 and interpolation methods, and I have been trying to keep it general so that I can reuse the module for other projects. Mod2 has a class structure defined within it, Obj1, and is meant to be specific to this project. The issue is that a subroutine defined in mod1 now needs an object definition passed something along the lines as
subroutine driver(x1, x2, func, this)
real(kind=8) :: x1, x2
external :: func, this ! this is the Object
! ...
end subroutine driver
The error I get from this is
Type mismatch in argument 'this' at (1); passed TYPE(Obj1) to UNKOWN
I had a feeling this would happen, since the external keyword is meant for functions and subroutines, but I would like to pass an Object to the subroutine without having to hard code my mod2 into mod1 (i.e. using use mod2)
I tired this change
subroutine driver(x1, x2, func, this)
real(kind=8) :: x1, x2
class(Object) :: this
external :: func
! ...
end subroutine driver
but got Derived type 'object' at (1) is being used before it is defined.
I also tried type(Object) :: this with the same error produced.
To reiterate, I would like to see if there is a way to initialize an Object in a "general" sense so that other modules and files I create can just be linked this mod1 without having to change the code inside. Any advice would be appreciated!

Related

Fortran link modules for precision and global variable types

I am new to Fortran and trying to understand if the following is possible. My idea to structure the program is to declare the precision and variable types in one module. Then make use of those variables without declaring again the type in other modules or the main program.
module pre
implicit none
INTEGER, PARAMETER :: sp=SELECTED_REAL_KIND(6,37)
INTEGER, PARAMETER :: dp=SELECTED_REAL_KIND(15,307)
INTEGER, PARAMETER :: qp=SELECTED_REAL_KIND(33,4931)
REAL(dp), PARAMETER :: pi = 4.*ATAN(1.)
REAL(dp) :: H
REAL(dp) :: M
REAL(dp) :: KR
end module pre
Now I want to make use of all the variables in another module that contains one or more functions, such as:
module hon
use pre
implicit none
contains
function KE(H,M) result(KR)
KR = 2*PI/H/M
end function KE
end module hon
Then I use gfortran in this order:
gfortran -c mod_pre.f90
gfortran -c mod_hon.f90
Since 'module pre' is part of 'module hon' I compile in order, but gfortran shows an error.
With the code above I understand the variable types and parameters should have been included by USE; But the message I get from gfortran is that none of my variables have IMPLICIT type when I try to compile 'module hon'.
Could somebody clarify the problem or suggest a solution? I would like to avoid having my variables scattered in multiple modules.
Thanks!
In the function statement, the result(kr) says that the function result has name kr. This function result is not the same thing as the module variable kr. In particular, this function result makes inaccessible the module variable.
The function result is specific to the function itself and its properties must be declared within the function subprogram.
Similarly, the dummy arguments of the function, H and M, are distinct from the module variables and need to be declared in the function subprogram.
Beyond that, you perhaps have similar concerns to this other question.
To be clear, it isn't possible to say something like "all function results called kr and all dummy arguments called H or M have these characteristics". Each individual object must be given the properties.
However, although I don't recommend this, this is a situation where literal text inclusion (using a preprocessor or include file) could help you:
function ke(H, M) result (kr)
include 'resdummydecls'
...
end function
where the file has the declarations.

Private, Save attributes for variables in Fortran 90 modules

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

Fortran - Module Subroutine Argument Intent Confusion- INOUT vs OUT

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

Fortran tips in large modules

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.

File IO using polymorphic datatypes in Fortran

I am writing a library for importing geometries of many types (spheres,planes,NURBS surfaces, stl files...) into a scientific Fortran code. This kind of problem seems taylor-made for OOP because it is simple to define a type :: geom and then type,extends(geom) :: analytic and so on. The part I am having trouble with is the file IO.
My solution at this point is to write the parameters defining the shapes, including some flags which tell me which shape it is. When reading, I instantiate a class(geom) :: object, (since I don't know ahead of time which subtype it will be) but how can I read it?
I can't access any of the specific components of the subtype. I read that downcasting is verboten, and besides, the new allocate(subtype :: class) doesn't seem to work. The new READ(FORMATTED) doesn't seem to be implemented by ifort or gfortran. i.e.
module geom_mod
type :: geom
end type
type,extends(geom) :: sphere
integer :: type
real(8) :: center(3),radius
contains
generic :: READ(FORMATTED)=> read_sphere ! not implemented anywhere
end type
contains
subroutine read_geom(object)
class(geom),intent(out),pointer :: object
integer :: type
read(10,*) object%type ! can't access the subtype data yet
read(10,*) type
backspace(10)
if(type==1) then
allocate(sphere :: object)! downcast?
read(10,*) object ! doesn't work
end if
end read_geom
end module
Am I going about this all wrong? I could hack this using something other than polymorphism, but this seems cleaner everywhere else. Assistance would be greatly appreciated.
EDIT: sample program using IanH's module
program test
use geom_mod
implicit none
class(geom),allocatable :: object
open(10)
write(10,*) '1'
write(10,*) sphere(center=0,radius=1)
rewind(10)
call read(object) ! works !
end program test
Current gfortran and ifort do not implement defined input/output. I have not seen any evidence that this situation will change in the near future. However, apart from allowing some syntactic shortcuts that feature does not actually save you much work here.
One approach for this situation is to call a "factory" for extensions of geom that uses the data in the file to allocate the argument to the correct type, then hand off to a type bound procedure that reads in the type specific data. For example:
module geom_mod
implicit none
integer, parameter :: dp = kind(1.0d0)
type, abstract :: geom
contains
procedure(read_geom), deferred :: read
end type geom
abstract interface
subroutine read_geom(object)
import :: geom
implicit none
class(geom), intent(out) :: object
end subroutine read_geom
end interface
type, extends(geom) :: sphere
real(dp) :: center(3), radius
contains
procedure :: read => read_sphere
end type sphere
contains
subroutine read(object)
class(geom), intent(out), allocatable :: object
integer :: type
read (10, *) type
! Create (and set the dynamic type of object) based on type.
select case (type)
case (1) ; allocate(sphere :: object)
case default ; stop 'Unsupported type index'
end select
call object%read
end subroutine read
subroutine read_sphere(object)
class(sphere), intent(out) :: object
read (10, *) object%center, object%radius
end subroutine read_sphere
end module geom_mod
Current ifort (12.1.5) has issues with intent(out) polymorphic arguments that may require workarounds, but the general approach remains the same.
(Note that the subroutine read is not a type bound subroutine - to read a generic geom object use ''call read(object)'' in the conventional subroutine reference style.)