I am trying to identify/source an objective function package in Julia that has common objective functions (such as Rastrigin, Schwefel, etc.) in-built, so I do not need to retype the function via an f(x) = ... declaration.
Does such a package exist, and if so, what is it called?
Related
So I have been trying to adapt my python codes to Julia instead of fortran mainly because of the fact I have Jupiter to easily test my work on the fly. But in Julia 1, I am unable to find any easy way to redefine a already defined function in another cell to test it out.
For instance
function a(b);return b+4;end
and then in next cell I would like to test instead loose the condition and have it something like
function a(b,c);return b+c;end
But I do not want to change the name because I have other dependent functions in which I call a. The reason to do this is for prototyping the best possible way to define a and obviously this wouldn't be a part of the main code.
Any way how to do this ?
Julia uses multiple dispatch and these are two different functions (or more exactly two different methods of the same function). Hence, no change of name is needed.
julia> function a(b);return b+4;end
a (generic function with 1 method)
julia> function a(b,c);return b+c;end
a (generic function with 2 methods)
julia> methods(a)
# 2 methods for generic function "a":
[1] a(b) in Main at REPL[1]:1
[2] a(b, c) in Main at REPL[2]:1
Basically, rerunning a Jupyter cell will redefine the function (if it is the same set of parameter types) so there is no problem here.
More complicated situation is when you want to change a type of a constants because they go deeper into compiler. Constants cannot change their type.
Functions are constants. Hence, if you try to assign a non-function type it will trow an error.
julia> typeof(a) <: Function
true
julia> a = 5
ERROR: invalid redefinition of constant a
Stacktrace:
[1] top-level scope at REPL[9]:1
I have a module which builds up some levels of abstraction for a simulation I'd like to perform. Let's say the lowest level of abstraction is a node (which we build into systems, if we truncate this at two levels of abstraction), which is a subtype of an abstract type I define in the module. The nodes are updated with a user-defined update! function.
I want the user to be able to define a new node and update! function, but the update! function should be callable from the module's system_update! function. An example is provided below:
module test_pack
abstract type Node end
struct System{N<:Node}
nodes::Array{N,1}
end
function system_update!(s::System)
update!.(s.nodes)
end
export Node, System, system_update!
end
# import module
using Main.test_pack
# User-defined types and functions
mutable struct My_Node<:Node
state
end
function update!(n::My_Node)
n.state *= 2
end
# Define system of user defined nodes
sys = System([My_Node(1), My_Node(2)])
# Run the system
system_update!(sys)
Running this code gives
ERROR: LoadError: UndefVarError: update! not defined
However, if I move the definition of My_Node and update! to within the module and then export My_Node, the code executes and return the appropriate 2,4 output.
Is there a way I can enable the type of behavior I expect, where the user defines the type and update! function, but the module-defined System can call those functions?
One way of doing what you want would be to set things up in such a way that the update! function is defined by the module, and the code which defines the My_Node type (deriving from Node) also defines a specific method extending the update! function.
Here, since there is no default implementation for update! working on an argument of abstract type Node, an empty generic function can be defined to only mark the function as "belonging" to the module, without providing any implementation.
The implementation of the TestPack.update!(::My_Node) method explicitly extends this function, referring to it via a fully qualified name.
module TestPack
abstract type Node end
struct System{N<:Node}
nodes::Array{N,1}
end
function update! end
function system_update!(s::System)
update!.(s.nodes)
end
export Node, System, system_update!
end
# import module
using .TestPack
# User-defined types and functions
mutable struct My_Node<:Node
state
end
function TestPack.update!(n::My_Node)
n.state *= 2
end
sys = System([My_Node(1), My_Node(2)])
# Run the system
system_update!(sys)
The code above runs without problem and yields:
julia> sys
System{My_Node}(My_Node[My_Node(2), My_Node(4)])
As an aside, note that it is customary in Julia to use CamelCase notations for the name of modules; in the example above, I renamed your module to TestPack to follow this stylistic convention.
The module can also be referred to as using .TestPack instead of using Main.TestPack; this is called a relative module path.
I use the Intel Visual Fortran. According to Chapmann's book, declaration of function type in the routine that calls it, is NECESSARY. But look at this piece of code,
module mod
implicit none
contains
function fcn ( i )
implicit none
integer :: fcn
integer, intent (in) :: i
fcn = i + 1
end function
end module
program prog
use mod
implicit none
print *, fcn ( 3 )
end program
It runs without that declaration in the calling routine (here prog) and actually when I define its type (I mean function type) in the program prog or any other unit, it bears this error,
error #6401: The attributes of this name conflict with those made accessible by a USE statement. [FCN] Source1.f90 15
What is my fault? or if I am right, How can it be justified?
You must be working with a very old copy of Chapman's book, or possibly misinterpreting what it says. Certainly a calling routine must know the type of a called function, and in Fortran-before-90 it was the programmer's responsibility to ensure that the calling function had that information.
However, since the 90 standard and the introduction of modules there are other, and better, ways to provide information about the called function to the calling routine. One of those ways is to put the called functions into a module and to use-associate the module. When your program follows this approach the compiler takes care of matters. This is precisely what your code has done and it is not only correct, it is a good approach, in line with modern Fortran practice.
association is Fortran-standard-speak for the way(s) in which names (such as fcn) become associated with entities, such as the function called fcn. use-association is the way implemented by writing use module in a program unit, thereby making all the names in module available to the unit which uses module. A simple use statement makes all the entities in the module known under their module-defined names. The use statement can be modified by an only clause, which means that only some module entities are made available. Individual module entities can be renamed in a use statement, thereby associating a different name with the module entity.
The error message you get if you include a (re-)declaration of the called function's type in the calling routine arises because the compiler will only permit one declaration of the called function's type.
I've recently learnt about interface blocks when adding a function to my Fortran program. Everything works nice and neatly, but now I want to add a second function into the interface block.
Here is my interface block:
interface
function correctNeighLabel (A,i,j,k)
integer :: correctNeighLabel
integer, intent(in) :: i,j,k
integer,dimension(:,:,:),intent(inout) :: A
end function
function correctNeighArray (B,d,e,f)
character :: correctNeighArray
integer, intent(in) :: d,e,f
character, dimension(:,:,:),intent(inout) :: B
end function
end interface
It appears to me that this may not be the best option.
I've looked into subroutines, but I'm not very confident that it's the right solution. What I'm doing is relatively simple, and I need to pass arguments to the subroutine, but all the subroutines I've seen are a) complicated (i.e. too complicated for a function), and b) don't take arguments. They behave as though they manipulate variables without them being passed to them.
I've not really looked into modules properly, but from what I've seen it's not the right thing to use.
Which should I use when, and how do I go about it best?
Modules are always the right thing to use ;-)
If you have a very simple F90 program you can include functions and subroutines in the 'contains' block:
program simple
implicit none
integer :: x, y
x = ...
y = myfunc(x)
contains
function myfunc(x) result(y)
implicit none
integer, intent(in) :: x
integer :: y
...
end function myfunc
end program
Then the interface of the functions/subroutines will be known in the program and don't need to be defined in an interface block.
For more complex programs you should keep all functions/subroutines in modules and load them when required. So you don't need to define interfaces, either:
module mymod
implicit none
private
public :: myfunc
contains
function myfunc(x) result(y)
implicit none
integer, intent(in) :: x
integer :: y
...
end function myfunc
end module mymod
program advanced
use mymod, only: myfunc
implicit none
integer :: x, y
x = ...
y = myfunc(x)
end program advanced
The module and the program can (actually should) be in separate files, but the module has to be compiled before the actual program.
Seconding and extending what has already been said. It is better to put your procedures (subroutines and functions) into modules and "use" them because them you get automatic consistency checking of the interfaces with little effort. The other ways have drawbacks. If you define the interface with an interface block, then you have three things to maintain instead of two: the interface, the procedure itself and the call. If you make a change, then all three have to be modified to be consistent. If you use a module, only two have to be changed. A reason to use an interface block is if you don't have access to the source code (e.g., pre-compiled library) or the source code is in another language (e.g., you are using C code via the ISO C Binding).
The drawback to the "contains" approach is that contained procedures inherit all of the local variables of the parent program ... which is not very modular and can be very confusing if you forget this "feature".
alexurba's and MSB's answers are correct and useful as usual; let me just flesh out a little more detail on one point - if modules are the way to go (and they are), what are interfaces for at all?
For functions and subroutines in modules, anything that uses that module can automatically see those interfaces; the interfaces are generated when the module is compiled (that information, amongst other things, goes into the .mod file that's generated when you compile a module). So you don't need to write it yourself. Similarly, when you use a CONTAINed subprogram (which, agreeing with MSB, I find more confusing then helpful - they're much better thought of as closures or nested subroutines than external subroutines), the main program can already 'see' the interface explicitly and it doesn't need you to write it out for it.
Interface blocks are for when you can't do this - when the compiler isn't able to generate the explicit interface for you, or when you want something different than what is given. One example is when using C-Fortran interoperability in Fortran 2003. In that case, the Fortran code is linking against some C library (say) and has no way of generating a correct fortran interface to the C routine for you -- you have to do it yourself, by writing your own interface block.
Another example is when you do already know the interfaces to subroutines, but when you want to create a new interface to "hide" the subroutines behind - for instance, when you have one routine that operates on (say) integers, and one on reals, and you want to be able to call the same routine name on either and let the compiler sort it out based on the arguments. Such constructs are called generic routines and have been around since Fortran 90. In that case, you create an interface explicitly to this new generic routine, and list the interfaces to the "real" routines within that interface block.
I have a program that calls a subroutine which then calls a function. I am somewhat confused by Fortran's requirements for function type declaration. I have declared the type in the function (i.e. real function foo(...)), and the program works whether or not I declare the function in the subroutine declaration section.
My specific question is, will not declaring the function in the subroutine potentially lead to unexpected behavior in future? I have also seen the interface block and am wondering if this is necessary as well.
More generally, I am also interested in what Fortran is doing "behind the scenes" and why it would be more or less important to declare the function or use an interface block.
EDIT: Some sample code:
program foo
real :: a,b,c
call bar(a,b,c)
end program foo
subroutine bar(a,b,c)
real :: a,b,c
c = baz(a,b)
end subroutine bar
real function baz(a,b)
real :: a,b
baz = a*b
end function baz
The best approach is to declare the function in the function, then to place the function in a module. Then "use" the function from any main program or procedure (subroutine or function) that calls that function. That way the calling program or procedure will be aware of the interface to the function and will generate the correct code. In Fortran terminology, the interface is explicit. If the function is called from a procedure in the same module, you don't have to "use" it because procedures in a module are aware of each other. See Computing the cross product of two vectors in Fortran 90 for an example. Typically there is no need to use an interface unless you are calling a procedure to which you lack the source code, or which is in another language, e.g., C accessed via the ISO C Binding.