Fortran - explicit interface - compilation

I'm very new to Fortran, and for my research I need to get a monster of a model running, so I am learning as I am going along. So I'm sorry if I ask a "stupid" question.
I'm trying to compile (Mac OSX, from the command line) and I've already managed to solve a few things, but now I've come across something I am not sure how to fix. I think I get the idea behind the error, but again, not sure how to fix.
The model is huge, so I will only post the code sections that I think are relevant (though I could be wrong). I have a file with several subroutines, that starts with:
!==========================================================================================!
! This subroutine simply updates the budget variables. !
!------------------------------------------------------------------------------------------!
subroutine update_budget(csite,lsl,ipaa,ipaz)
use ed_state_vars, only : sitetype ! ! structure
implicit none
!----- Arguments -----------------------------------------------------------------------!
type(sitetype) , target :: csite
integer , intent(in) :: lsl
integer , intent(in) :: ipaa
integer , intent(in) :: ipaz
!----- Local variables. ----------------------------------------------------------------!
integer :: ipa
!----- External functions. -------------------------------------------------------------!
real , external :: compute_water_storage
real , external :: compute_energy_storage
real , external :: compute_co2_storage
!---------------------------------------------------------------------------------------!
do ipa=ipaa,ipaz
!------------------------------------------------------------------------------------!
! Computing the storage terms for CO2, energy, and water budgets. !
!------------------------------------------------------------------------------------!
csite%co2budget_initialstorage(ipa) = compute_co2_storage(csite,ipa)
csite%wbudget_initialstorage(ipa) = compute_water_storage(csite,lsl,ipa)
csite%ebudget_initialstorage(ipa) = compute_energy_storage(csite,lsl,ipa)
end do
return
end subroutine update_budget
!==========================================================================================!
!==========================================================================================!
I get error messages along the lines of
budget_utils.f90:20.54:
real , external :: compute_co2_storage
1
Error: Dummy argument 'csite' of procedure 'compute_co2_storage' at (1) has an attribute that requires an explicit interface for this procedure
(I get a bunch of them, but they are essentially all the same). Now, looking at ed_state_vars.f90 (which is "used" in the subroutine), I find
!============================================================================!
!============================================================================!
!---------------------------------------------------------------------------!
! Site type:
! The following are the patch level arrays that populate the current site.
!---------------------------------------------------------------------------!
type sitetype
integer :: npatches
! The global index of the first cohort in all patches
integer,pointer,dimension(:) :: paco_id
! The number of cohorts in each patch
integer,pointer,dimension(:) :: paco_n
! Global index of the first patch in this vector, across all patches
! on the grid
integer :: paglob_id
! The patches containing the cohort arrays
type(patchtype),pointer,dimension(:) :: patch
Etc etc - this goes one for another 500 lines or so.
So to get to the point, it seems like the original subroutine needs an explicit interface for its procedures in order to be able to use the (dummy) argument csite. Again, I am SO NEW to Fortran, but I am really trying to understand how it "thinks". I have been searching what it means to have an explicit interface, when (and how!) to use it etc. But I can't figure out how it applies in my case. Should I maybe use a different compiler (Intel?). Any hints?
Edit: So csite is declared a target in all procedures and from the declaration type(site type) contains a whole bunch of pointers, as specified in sitetype. But sitetype is being properly used from another module (ed_state_vars.f90) in all procedures. So I am still confused why it gives me the explicit interface error?

"explicit interface" means that the interface to the procedure (subroutine or function) is declared to the compiler. This allows the compiler to check consistency of arguments between calls to the procedure and the actual procedure. This can find a lot of programmer mistakes. You can do this writing out the interface with an interface statement but there is a far easier method: place the procedure into a module and use that module from any other entity that calls it -- from the main program or any procedure that is itself not in the module. But you don't use a procedure from another procedure in the same module -- they are automatically known to each other.
Placing a procedure into a module automatically makes its interface known to the compiler and available for cross-checking when it is useed. This is easier and less prone to mistakes than writing an interface. With an interface, you have to duplicate the procedure argument list. Then if you revise the procedure, you also have to revise the calls (of course!) but also the interface.
An explicit interface (interface statement or module) is required when you use "advanced" arguments. Otherwise the compiler doesn't know to generate the correct call
If you have a procedure that is useed, you shouldn't describe it with external. There are very few uses of external in modern Fortran -- so, remove the external attributes, put all of your procedures into a module, and use them.

I ran into the same problems you encountered whilst I was trying to install ED2 on my mac 10.9. I fixed it by including all the subroutines in that file in a module, that is:
module mymodule
contains
subroutine update_budget(csite,lsl,ipaa,ipaz)
other subroutines ecc.
end module mymodule
The same thing had to be done to some 10 to 15 other files in the package.
I have compiled all the files and produced the corresponding object files but now I am getting errors about undefined symbols. However I suspect these are independent of the modifications so if someone has the patience this might be a way to solve at least the interface problem.

Related

Fortran OOP no reasons compilation aborted

So I have a module for an allocatable class array. When I try to access that array from the module where the class is, I get a compilation aborted without reason. I guess its may be related to the module with the array also using the module, so it is in some kind of recursion when I call the module from the module with the class. compilation aborted from VS community 2019
One may ask why I have a dedicated module for the class array, this is actually to prevent recursion with the class. As I have tried having the array in a more general module as global value, but it would lead to a crash related to nested too deep.
The module with the array:
module sys2_moleculesArray
use type3_crossMol_class, only: type3_crossMol
implicit none
class(type3_crossMol),dimension(:),allocatable :: type3_crossMol_tagArray
end module sys2_moleculesArray
parts of the class array:
module type3_crossMol_class
use sys2_paramData
use sys2_type3ParamData
implicit none
...
type :: type3_crossMol
integer(kind=4) :: index,x,y,rotType,checkMol_index
integer,dimension(4,2) :: molBondedTo
integer,dimension(20) :: potentialNeighMol
contains
procedure :: initialise => initialise
procedure :: addAtom => addAtom
procedure :: getPotentialNeigh => getPotentialNeigh
procedure :: test => test
end type type3_crossMol
contains
...
subroutine test(this)
use sys2_type3ParamData, only:cur_type3_mol_number
use sys2_moleculesArray
implicit none
integer :: n
class(type3_crossMol):: this
do n=1,cur_type3_mol_number
print*, "b4 potential",type3_crossMol_tagArray(n)%index
end do
end subroutine test
I guess I can do what I want to do by doing the array manipulation outside the module with the class, but I would like to keep the code sort of organised, with the subroutine inside the class. So any help regarding the issue, at least a more detail reason, would be great!
You apparently have a circular dependency.
module sys2_moleculesArray uses type3_crossMol_class
module type3_crossMol_class uses sys2_moleculesArray
which one should be compiled first?
Weird that VS doesn't have a mechanism to check that, though.

Type mismatch when calling a function in qtp

I am using QTP 11.5 for automating a web application.I am trying to call an action in qtp through driverscript as below:
RFSTestPath = "D:\vf74\D Drive\RFS Automation\"
LoadAndRunAction RFStestPath & LogInApplication,"Action1",oneIteration
Inside the LogInApplication(Action1) am calling a login function as:
Call fncLogInApplication(strURL,strUsesrName,strPasssword)
Definition of fncLogInApplication is written in fncLogInApplication.vbs
When I associate the fncLogInApplication.vbs file to driverscript, am able to execute my code without any errors. But when I de-associate .vbs file from driverscript and associate it to LogInApplication test am getting "Type mismatch: 'fncLogInApplication'"
Can anyone help me in the association please. I want fncLogInApplication to be executed when I associate to LogInApplication not to the main driverscript.
Please comment back if you require any more info
There is only one set of associated libraries that is active at any one time: That is always the outermost test's one.
This means if test A calls test B, test B will be executed with the libraries loaded based upon test A´s associated libraries list, not B's.
This also means that if B depends on a library, and B associated this library, but is called from test A (which does not associated this library), then B will fail to call (locate) the function since the associated libraries of B are never loaded (only those from A are). (As would A, naturally.).
If you are still interested: "Type mismatch" is QTPs (or VBScript´s) poor way of telling you: "The function called is not known, so I bet you instead meant an array variable dereference, and the variable you specified is equal to empty, so it is not an array, and thus cannot be dereferenced as an array variable, which is what I call a 'type mismatch'."
This reasoning is valid, considering the syntax tree of VB/VBScript: Function calls and array variable dereferences cannot be formally differentiated. Syntactically, they are very similar, or identical in most cases. So be prepared to handle "Type mismatch" like the "Unknown function referenced" message that VB/VBScript never display when creating VBScript code.
You can, however, load the library you want in test B´s code (for example, using LoadFunctionLibrary), but this still allows A to call functions from that library once B loaded it and returned from A´s call. This, and all the possible variations of this procedure, however, have side-effects to aspects like debugging, forward references and visibility of global variables, so I would recommend against it.
Additional notes:
There is no good reason to use CALL. Just call the sub or function.
If you call a function and use the result it returns, you must include the arguments in parantheses.
If you call a sub (or a function, and don´t use the result it returns), you must not include the arguments in parantheses. If the sub or function accepts only one argument, it might look like you are allowed to put it in parantheses, but this is not true. In this case, the argument is simply treated like a term in parantheses.
The argument "bracketing" aspects just listed can create very nasty bugs, especially if the argument is byRef, also due (but not limited) to the fact that VBScripts unfortunately allows you to pass values for a byRef argument (where a variable parameter is expected), so it is generally a good idea to put paranthesis only where it belongs (i.e. where absolutely needed).

Why does the following Fortran code allocate on the stack/heap depending on the contents of a derived type?

I do not understand why the following program segfaults with a SIGSEGV if the bar field is present in containerType, and works without problems if it is commented out. I'm on x86_64, compiling with both gfortran-4.4.6 and gfortran-4.6.3.
As I understand it, using a pointer to containerType should force the allocation of the contained big array to happen on the heap but that doesn't seem to be the case. Running valgrind on the executable gives me
Warning: client switching stacks? SP change: 0x7ff000448 --> 0x7fe0603f8
to suppress, use: --max-stackframe=16384080 or greater
(The rest of the output is IMHO not relevant, but I could edit it in if required). This indicates to me that there's a stack overflow; presumably due to allocating the 8*8*8*4000 * 8(bytes per real) = 16384000 bytes on the stack.
When I comment out the bar field, valgrind is perfectly happy. To make matters even stranger, compiling under gfortran-4.6.3 with '-O' also makes the problem go away (but not under gfortran-4.4.6).
Either I've stumbled on a compiler bug, or (more likely, as I'm pretty new to Fortran) I don't understand where data is allocated. Could someone enlighten me what's going on?
The code in question:
main.f90:
program main
use problematicArray
implicit none
type (containerType),pointer :: container
allocate(container)
container%foo%arrayData = 17.0
write(*,*) container%foo%arrayData(7,7,7,100)
deallocate(container)
write(*,*) 'Program finished'
end program main
problematicArray.f90:
module problematicArray
implicit none
private
integer, parameter, public :: dim1 = 4000
type, public :: typeWith4DArray
real(8), dimension(8,8,8,dim1) :: arrayData
end type typeWith4DArray
type :: typeWithChars
character(4), dimension(:), allocatable :: charData
end type typeWithChars
type, public :: containerType
type(typeWith4DArray) :: foo
type(typeWithChars) :: bar
end type containerType
end module problematicArray
This must be a bug in gfortran. I do not see anything wrong there. It also works in Intel and Oracle compilers. Best to report it to gfortran developers. I tried it with only a 2 days old build of the gfortran 4.8 trunk.
The error has nothing to do with stack/heap difference. It simply crashes during the allocate statement. It does not even work with stat= and errmsg= set.
Just a note, you can have the module and the main program inside a single source file.

Intel MKL Pardiso solver compiling with Visual Studio

I am trying to do create a simple example in order to use the Pardiso solver inside MKL Intel library. I have been following the examples provided but if I place the call to Pardiso in a subroutine it does not work. I am afraid that is something related to the INCLUDE statement or the linking aspect.
Arrays used by all subroutines are contained in a module called variables
MODULE variables
INTEGER :: M ! Lines
INTEGER :: N ! Columns
REAL*8, DIMENSION(:,:), ALLOCATABLE :: MATRA ! original matrix
INTEGER, DIMENSION(:), ALLOCATABLE :: ROWSA,COLSA ! ia and ja in pardiso
REAL*8, dimension(:), ALLOCATABLE :: VALSA, RHSVC, SOLVC ! a, b, x
END MODULE variables
The file containing the program is as follows:
INCLUDE 'mkl_pardiso.f90'
program PardisoFortran
use variables
use mkl_pardiso
implicit none
! do some stuff to create the matrices
call create_matrices
call INITPARDISO
end program
Finally the file initpardiso
subroutine INITPARDISO
USE VARIABLES
USE mkl_pardiso
! pardiso variable declaration
TYPE(MKL_PARDISO_HANDLE), ALLOCATABLE :: pt(:)
INTEGER maxfct, mnum, mtype, phase, nrhs, error, msglvl
INTEGER, ALLOCATABLE, DIMENSION(:) :: iparm
INTEGER i, idum
REAL*8 waltime1, waltime2, ddum
! --- then I allocate and fill the variables
! Finally I can call pardiso
phase = 11 ! only reordering and symbolic factorization phase
CALL pardiso_64 (PT, maxfct, mnum, mtype, phase, M, VALSA, COLSA, &
ROWSA, idum, nrhs, iparm, msglvl, ddum, ddum, error)
end subroutine
Now, I added also the Additional Include Directories to Visual Studio project configuration (that is
C:\Program Files (x86)\Intel\ComposerXE-2011\mkl\include;
C:\Program Files (x86)\Intel\ComposerXE-2011\mkl\lib\intel64;
C:\Program Files (x86)\Intel\ComposerXE-2011\mkl\lib\ia32)
If I comment the call to pardiso everything works perfectly, otherwise it stops compilation with this error:
Error 1 error #6285: There is no matching specific subroutine for this generic subroutine call. [PARDISO_64] ....PardisoFortran\initpardiso.f 144
Any idea for that? Is that a problem of the INCLUDE statement on top? where should I include it?
I believe that pardiso_64 is a subroutine version which uses 64-bit integers. Your code snippets show no evidence that you have taken measures to ensure that your integers are 64-bit. I suppose you may have used compiler options or other means to tell the compiler to default to 64-bit integers.
The error message you post is typical of the error messages you get when there is a mis-match between dummy and actual arguments when calling a library generic procedure. Suppose that your integers are only 32-bit, then the compiler is looking for, and failing to find, a routine named pardiso_64 which takes 32-bit integer arguments.
I don't think that the error has anything to do with the include statement.
I see one problem in your code. The parameter 'ddum' was a scalar. It should be an array of dimension (M, nrhs). There could be more problems. I need to see the entire code to help.
As usual, the best place to ask Intel MKL related questions is the MKL forum: http://software.intel.com/en-us/forums/intel-math-kernel-library. Post your question there, with your entire program attached. You will get an answer much quicker!

What is the explicit difference between the fortran intents (in,out,inout)?

After searching for a while in books, here on stackoverflow and on the general web, I have found that it is difficult to find a straightforward explanation to the real differences between the fortran argument intents. The way I have understood it, is this:
intent(in) -- The actual argument is copied to the dummy argument at entry.
intent(out) -- The dummy argument points to the actual argument (they both point to the same place in memory).
intent(inout) -- the dummy argument is created locally, and then copied to the actual argument when the procedure is finished.
If my understanding is correct, then I also want to know why one ever wants to use intent(out), since the intent(inout) requires less work (no copying of data).
Intents are just hints for the compiler, and you can throw that information away and violate it. Intents exists almost entirely to make sure that you only do what you planned to do in a subroutine. A compiler might choose to trust you and optimize something.
This means that intent(in) is not pass by value. You can still overwrite the original value.
program xxxx
integer i
i = 9
call sub(i)
print*,i ! will print 7 on all compilers I checked
end
subroutine sub(i)
integer,intent(in) :: i
call sub2(i)
end
subroutine sub2(i)
implicit none
integer i
i = 7 ! This works since the "intent" information was lost.
end
program xxxx
integer i
i = 9
call sub(i)
end
subroutine sub(i)
integer,intent(out) :: i
call sub2(i)
end
subroutine sub2(i)
implicit none
integer i
print*,i ! will print 9 on all compilers I checked, even though intent was "out" above.
end
intent(in) - looks like pass by value (and changes of this are not reflected in outside code) but is in fact pass by reference and changing it is prohibited by the compiler. But it can be changed still.
intent(out) - pass somehow by reference, in fact a return argument
intent(inout) - pass by reference, normal in/out parameter.
Use intent(out) if is is plain out, to document your design. Do not care for the very little performance gain if any. (The comments suggest there is none as intent(in) is technically also pass by reference.)
It's not clear if parts of the OP's questions were actually answered. In addition, certainly there seems to be much confusion and various errors in the ensuing answers/discussions that may benefit from some clarifications.
A) The OP's question Re
" then I also want to know why one ever wants to use intent(out), since the intent(inout) requires less work (no copying of data)."
may not have answered, or at least too directly/correctly.
First, to be clear the Intent attributes have at least TWO purposes: "safety/hygiene", and "indirect performance" issues (not "direct performance" issues).
1) Safety/Hygiene: To assist in producing "safe/sensible" code with reduced opportunity to "mess things" up. Thus, an Intent(In) cannot be overwritten (at least locally, or even "globally" under some circumstances, see below).
Similarly, Intent(Out) requires that the Arg be assigned an "explicit answer", thus helping to reduce "rubbish" results.
For example, in the solution of perhaps the most common problem in computational mathematics, i.e. the so-called "Ax=b problem", the "direct result/answer" one is looking for is the values for the vector x. Those should be Intent(Out) to ensure x is assigned an "explicit" answer. If x was declared as, say, Intent(InOut) or "no Intent", then Fortran would assign x some "default values" (probably "zero's" in Debug mode, but likely "rubbish" in Release mode, being whatever is in memory at the Args pointer location), and if the user did not then assign the correct values to x explicitly, it would return "rubbish". The Intent(Out) would "remind/force" the user to assign values explicitly to x, and thus obviating this kind of "(accidental) rubbish".
During the solution process, one would (almost surely) produce the inverse of matrix A. The user may wish to return that inverse to the calling s/r in place of A, in which case A should be Intent(InOut).
Alternatively, the user may wish to ensure that no changes are made to the matrix A or the vector b, in which case they would be declared Intent(In), and thus ensuring that critical values are not overwritten.
2 a) "Indirect Performance" (and "global safety/hygiene"): Although the Intents are not directly for influencing performance, they do so indirectly. Notably, certain types of optimisation, and particularly the Fortran Pure and Elemental constructs, can produce much improved performance. These settings typically require all Args to have their Intent's declared explicitly.
Roughly speaking, if the compiler knows in advance the Intent's of all vars, then it can optimise and "stupidity check" the code with greater ease and effectiveness.
Crucially, if one uses Pure etc constructs, then, with high probability, there will be a "kind of global safety/hygiene" as well, since Pure/Elemental s/p's can only call other Pure/Elemental s/p's and so one CANNOT arrive at a situation of the sort indicated in "The Glazer Guy's" example.
For example, if Sub1() is declared as Pure, then Sub2() must also be declared as Pure, and then it will be required to declare the Intents at all levels, and so the "garbage out" produced in "The Glazer Guy's" example could NOT happen. That is, the code would be:
Pure subroutine sub_P(i)
integer,intent(in) :: i
call sub2_P(i)
end subroutine sub_P
Pure subroutine sub2_P(i)
implicit none
! integer i ! not permitted to omit Intent in a Pure s/p
integer,intent(in) :: i
i = 7 ! This WILL NOT WORK/HAPPEN, since Pure obviates the possibility of omitting Intent, and Intent(In) prohibits assignment ... so "i" remains "safe".
end subroutine sub2_P
... on compile, this would produce something like
" ||Error: Dummy argument 'i' with INTENT(IN) in variable definition context (assignment) at (1)| "
Of course, sub2 need not be Pure to have i declared as Intent(In), which, again would provide the "safety/hygiene" one is looking for.
Notice that even if i was declared Intent(InOut) it would still fail with Pure's. That is:
Pure subroutine sub_P(i)
integer,intent(in) :: i
call sub2_P(i)
end subroutine sub_P
Pure subroutine sub2_P(i)
implicit none
integer,intent(inOut) :: i
i = 7 ! This WILL NOT WORK, since Pure obviates the possibility of "mixing" Intent's.
end subroutine sub2_P
... on compile, this would produce something like
"||Error: Dummy argument 'i' with INTENT(IN) in variable definition context (actual argument to INTENT = OUT/INOUT) at (1)|"
Thus, strict or wide reliance on Pure/Elemental constructs will ensure (mostly) "global safety/hygiene".
It will not be possible to use Pure/Elemental etc in all cases (e.g. many mixed language settings, or when relying on external libs beyond your control, etc).
Still, consistent usage of Intents, and whenever possible Pure etc, will produce much benefit, and eliminate much grief.
One can simply get into the habit of declaring Intents everywhere all the time when it is possible, whether Pure or not ... that is the recommended coding practice.
... this also brings to the fore another reason for the existence of BOTH Intent(InOut) and Intent(Out), since Pure's must have all Arg's Intent's declared, there will be some Args that are Out only, while others are InOut (i.e. it would be difficult to have Pure's without each of In, InOut, and Out Intents).
2 b) The OP's comments expecting "performance improvements "since no copying is required" indicates a misunderstanding of Fortran and its extensive use of pass by reference. Passed by reference means, essentially, only the pointers are required, and in fact, often only the pointer to the first element in an array (plus some little hidden array info) is required.
Indeed, some insight may be offered by considering "the old days" (e.g. Fortran IV, 77, etc), when passing an array might have been coded as follows:
Real*8 A(1000)
Call Sub(A)
Subroutine Sub(A)
Real*8 A(1) ! this was workable since Fortran only passes the pointer/by ref to the first element of A(1000)
! modern Fortran may well throw a bounds check warning
In modern Fortran, the "equivalent" is to declare A as Real(DP) A(:) in the s/r (though strictly speaking there are various settings that benefit from passing the array's bounds and declaring explicitly with the bounds, but that would a lengthy digression for another day).
That is, Fortran does not pass by value, nor "make copies" for Args/Dummy vars. The A() in the calling s/r is the "same A" as that used in the s/r (Of course, in the s/r, one could make a copy of A() or whatever, which would create additional work/space requirements, but that is another matter).
It is for this reason primarily that the Intent's do not directly impact performance to a great extent, even for large array Arg's etc.
B) Regarding the "pass by Value" confusion: Although the various response above do confirm that using Intent is "not pass by value", it may be helpful to clarify the matter.
It may help to change the wording to "Intent is always pass by reference". This is not the same as "not pass by value", and it is an important subtlety. Notably, not only are Intents "byRef", Intent can PREVENT pass by value.
Although there are special/much more complex settings (e.g. mixed-language Fortran DLL's etc) where much additional discussion is required, for the most part of "standard Fortran", Args are passed by Ref. A demonstrations of this "Intent subtlety" can be seen in a simple extension of "The Glazer Guys" example, as:
subroutine sub(i)
integer, intent(in) :: i, j
integer, value :: iV, jV
call sub2(i)
call sub3(i, j, jV, iV)
end
subroutine sub2(i)
implicit none
integer i
i = 7 ! This works since the "intent" information was lost.
end
subroutine sub3(i, j, jV, iV)
implicit none
integer, value, Intent(In) :: i ! This will work, since passed in byRef, but used locally as byVal
integer, value, Intent(InOut) :: j ! This will FAIL, since ByVal/ByRef collision with calling s/r,
! ||Error: VALUE attribute conflicts with INTENT(INOUT) attribute at (1)|
integer, value, Intent(InOut) :: iV ! This will FAIL, since ByVal/ByRef collision with calling s/r,
! ... in spite of "byVal" in calling s/r
! ||Error: VALUE attribute conflicts with INTENT(INOUT) attribute at (1)|
integer, value, Intent(Out) :: jV ! This will FAIL, since ByVal/ByRef collision with calling s/r
! ... in spite of "byVal" in calling s/r
! ||Error: VALUE attribute conflicts with INTENT(OUT) attribute at (1)|
jV = -7
iV = 7
end
That is, anything with an "Out" aspect to it must be "byRef" (at least in normal settings), since the calling s/r is expecting "byRef". Thus, even if all the s/r's declare Args as "Value", they are "byVal" only locally (again in standard settings). So, any attempt by the called s/r to return an Arg that is declared as Value with any sort of Out Intent, will FAIL due to the "collision" of the passing styles.
If it must be "Out" or "InOut" and "Value", then one cannot use Intent: which is somewhat more than simply saying "it is not pass by value".

Resources