This question already has answers here:
Obtaining current host name from Cray Fortran
(3 answers)
Closed 6 years ago.
I am running a fortran code on a cluster equiped with linux system. When the code begin to run, I want it to output some basic information of the node where it is running, especially the node name. How to do it in fortran.
If your code is parallelised with MPI - which is kind of common for a code running on a cluster - then just call MPI_Get_processor_name() that just does exactly this.
If not, just use the iso_c_binding module to call the C function gethostname(), which again just does that.
EDIT: here is an example on how to call gethostname() with the iso_c_binding module. I'm definitely not an expert with that so it might not be the most effective one ever...
module unistd
interface
integer( kind = C_INT ) function gethostname( hname, len ) bind( C, name = 'gethostname' )
use iso_c_binding
implicit none
character( kind = C_CHAR ) :: hname( * )
integer( kind = C_INT ), VALUE :: len
end function gethostname
end interface
end module unistd
program hostname
use iso_c_binding
use unistd
implicit none
integer( kind = C_INT ), parameter :: sl = 100
character( kind = C_CHAR ) :: hn( sl )
character( len = sl ) :: fn
character :: c
integer :: res, i, j
res = gethostname( hn, sl )
if ( res == 0 ) then
do i = 1, sl
c = hn( i )
if ( c == char( 0 ) ) exit
fn( i: i ) = c
end do
do j = i, sl
fn( j: j ) = ' '
end do
print *, "->", trim( fn ), "<-"
else
print *, "call to gethostname() didn't work..."
end if
end program hostname
If the information you want is contained in an environment variable the easy way is just to get its value from a call to get_environment_variable. For the hostname
program gethost
character*32 hostname
call get_environment_variable('HOST',hostname)
write(*,*) 'My gracious host is ',trim(hostname)
end program gethost
Related
How can I add a method to the string table and modify self inside it ?
Basically, I'm trying to mimic the behaviour of the io.StringIO.read method in python, which reads n char in the string and returns them, modifying the string by "consuming" it.
I tried this:
function string.read(str, n)
to_return = str:sub(1, n)
str = str:sub(n + 1)
return to_return
end
local foo = "heyfoobarhello"
print(string.read(foo, 3))
print(foo)
Output is:
hey
heyfoobarhello
I expected the second line to be only foobarhello.
How can I achieve this ?
To mimic Python's io.StringIO class, you must make an object that stores both the underlying string and the current position within that string. Reading from an IO stream normally does not modify the underlying data.
local StringIO_mt = {
read = function(self, n)
n = n or #self.buffer - self.position + 1
local result = self.buffer:sub(self.position, self.position + n - 1)
self.position = self.position + n
return result
end,
}
StringIO_mt.__index = StringIO_mt
local function StringIO(buffer)
local o = {buffer = buffer, position = 1}
setmetatable(o, StringIO_mt)
return o
end
local foo = StringIO"heyfoobarhello"
print(foo:read(3))
print(foo:read())
Output:
hey
foobarhello
I don't recommend adding this class or method to Lua's string library, because the object has to be more complex than just a string.
You can add methods to the datatype string independently from the string table.
Short example that shows that the string methods even work if string table gets deleted...
string=nil
return _VERSION:upper():sub(1,3)
-- Returning: LUA
So you can add a method...
-- read.lua
local read = function(self, n1, n2)
return self:sub(n1, n2)
end
getmetatable(_VERSION).__index.read=read
return read
...for all strings.
( Not only _VERSION )
And use it...
do require('read') print(_VERSION:read(1,3):upper()) end
-- Print out: LUA
I am looking for a way to read numerical expressions in Fortran.
With numerical expression I mean dsqrt(0.5d0)/3.d0+1.d0 or something rather then the translated 1.235... real version.
With reading I mean
open(unit=UnitNumber,file="FileName")
read(UnitNumber, *) ....
I try to define in the reading statement the format, for instanceread(unitNumber,"(15F24.17)") but it does not help. I am
I am wondering if I can do it only internally, defining real(8), parameter :: dsqrt(0.5d0)/3.d0+1.d0 .
Maybe the use of FORMAT syntax could help?
As suggested by #agentp, interpreted languages like Python and Julia can parse a string directly as a piece of code, so utilizing such a feature may be convenient for your purpose. But if you definitely need to achieve the same goal in Fortran, another approach (with least effort!) may be simply to call eval() in such languages, for example:
module util
use iso_fortran_env, only: dp => real64
implicit none
contains
subroutine eval( expr, ans, x, y )
character(*), intent(in) :: expr
real(dp), intent(out) :: ans
real(dp), intent(in), optional :: x, y
character(len(expr)+200) cmd, sx, sy
integer u
sx = "" ; sy = ""
if ( present(x) ) write( sx, "(' x = ', es25.15, ' ; ')" ) x
if ( present(y) ) write( sy, "(' y = ', es25.15, ' ; ')" ) y
write( cmd, "(a)" ) &
"python -c ""from __future__ import print_function, division ; " // &
"from math import * ; " // trim(sx) // trim(sy) // &
"print( eval( '" // trim(expr) // "' ))"" > tmp.dat"
call system( trim( cmd ) )
open( newunit=u, file="tmp.dat", status="old" )
read( u, * ) ans
close( u )
call system( "rm -f tmp.dat" )
end subroutine
end module
program main
use util, only: dp, eval
implicit none
character(200) str
real(dp) ans
str = "sqrt( 2.0 ) + 1000.0"
call eval( str, ans )
print *, "ans = ", ans
str = "acos( x ) + 2000.0"
call eval( str, ans, x= -1.0_dp )
print *, "ans = ", ans
str = "10 * x + y"
call eval( str, ans, x= 1.0_dp, y= 2.0_dp )
print *, "ans = ", ans
end program
Results:
$ gfortran test.f90 # gfortran >=5 is recommended
$ ./a.out
ans = 1001.4142135623731
ans = 2003.1415926535899
ans = 12.000000000000000
More specifically, the above code simply invokes the built-in eval() function in Python via system(). But it is not very efficient because the resulting value is once written to an external file (and also the overhead to call Python itself). So if efficiency matters, it may be better to use more specific 3rd-party libraries, or for handiness, work with interpreted languages directly. (I suggest the latter approach if the calculation is not too demanding, because it saves much time for coding...)
Python:
from __future__ import print_function, division
from math import *
str = input( "Input an expression: " )
x = 1.0
y = 2.0
print( eval( str ) ) # if you type "x + 10 * y" in the prompt, you get 21
Julia:
println( "Input an expression: " )
str = readline()
x = 1.0
y = 2.0
println( eval( parse( str ) ) )
[ EDIT ]
If it is OK to use system() and write external files, another option may be to simply write a small Fortran code that contains the expression to be evaluated, compile and run it via system(), get the result via an external file. For example, if we replace the two lines in the above code (write( cmd, "(a)" ) ... and system( trim( cmd ) )) by the following, it gives the same result. This might be useful if we want to keep the code entirely written in Fortran, with minimal effort for modification.
open( newunit=u, file="tmp.f90" )
write( u, "(a)" ) "implicit none"
write( u, "(a)" ) "real :: x, y"
write( u, "(a)" ) trim(sx)
write( u, "(a)" ) trim(sy)
write( u, "(a)" ) "write(*,'(e30.20)') " // trim(expr)
write( u, "(a)" ) "end"
close( u )
call system( "gfortran -fdefault-real-8 -ffree-line-length-none tmp.f90 && ./a.out > tmp.dat" )
! Assuming bash on Linux or Mac (x86_64).
! -fdefault-real-8 is attached to promote 1.0 etc to 8-byte floating-point values.
call system( "rm -f tmp.f90" )
For the record, the library fparser allows you to do precisely what you asked for: evaluate a string as a mathematical expression within Fortran, without requiring any other programming languages.
No, there is nothing like this built in Fortran or any related programming languages. There are specific libraries for similar purposes (not necessarily too many in Fortran).
It is not clear at all to me why do you want that and how do you intend to use such an expression. It would have to be some specific type and you would need specific subroutines to evaluate such an expression.
I am using the app TouchLua.
I need to turn a string from a table into an argument. This is the only way I would like to do the table.
b = {}
b[1] = "010,010,draw.blue"
function drawButtons()
for i = 1,2 do
draw.fillrect(tonumber(string.sub(b[i],1,3)), tonumber(string.sub(b[i],5,7)), tonumber(string.sub(b[i],1,3))+10, tonumber(string.sub(b[i],5,7)),string.sub(b[i],9))
end
end
drawButtons()
Assuming you want a function eval so that print( eval( "draw.blue" ) ) is roughly equivalent to print( draw.blue ), here is a quick and dirty version:
local function eval( s, e )
return assert( load( "return "..s, "=eval", "t", e or _G ) )()
end
-- global variable
draw = { blue = 2 }
print( draw.blue )
print( eval( "draw.blue" ) )
If you are using an older Lua version than 5.2, you will need loadstring instead of load and an additional setfenv call. Of course, instead of using load you can parse the string s and index the table e or _G manually.
The above code assumes that draw is a global variable. If you want the code to work with a local variable you need to use the debug library:
-- same for local variable
local localdraw = { blue = 3 }
print( localdraw.blue )
-- needs debugging information, so won't work with stripped bytecode!
local function locals()
local t, i, n, v = {}, 1, debug.getlocal( 2, 1 )
while n ~= nil do
t[ n ], i = v, i+1
n, v = debug.getlocal( 2, i )
end
return t
end
print( eval( "localdraw.blue", locals() ) )
Does anyone know that is there a compatible function in SQL for Excel FDIST and FINV? If there is no, anyone has any idea how to build that? May be in C#?
Thanks. Your help is greatly appreciated.
I have managed to resolve my problems by using a library from .Net Framework 4.0 and above (System.Windows.Forms.DataVisualization.Charting.StatisticFormula).
I am able to develop a function in C# using the above library for my calculation process. This is a powerful library where you can find mostly common use statistical formula in there (e.g. mean, median, t distribution, f distribution, and inverse of them.)
Below are the code snippet from me:
using System.Windows.Forms.DataVisualization.Charting;
private Chart ch = new Chart(); // You will need to declare an object of Chart type, as Statistic Formula class does not have a public constructor
double fDist = ch.DataManipulator.Statistics.FDistribution(fRatioVariance, degreeFreedom1, degreeFreedom2);
Hope this will help others. Thanks.
Though its too late but below are some statistical function implementation in SQL Server itself.
To get FDist function (equivalent to Excel - FDist), we will be needing Complete and Incomplete beta function as well as gamma function:
--GAMMA Function
CREATE FUNCTION [dbo].[udf_Gamma]
(
#x Float=NULL
)
RETURNS Float
AS
BEGIN
Declare #f Float = 10E99;
Declare #g Float = 1;
if ( #x > 0 )
Begin
while (#x < 3)
Begin
SET #g = #g * #x;
SET #x = #x + 1;
End
SET #f = (1 - (2/(7*power(#x,2))) * (1 - 2/(3*power(#x,2))))/(30*power(#x,2));
SET #f = (1-#f)/(12*#x) + #x*(log(#x)-1);
SET #f = (exp(#f)/#g)*power(2*PI()/#x,0.5);
End
else
Begin
SET #f = 10E99
End
return #f;
END
--BETA Complete Function
CREATE FUNCTION [dbo].[udf_BetaC]
(
#x Float=NULL
,#a Float=NULL
,#b Float=NULL
)
RETURNS Float
AS
BEGIN
--double betacf(double a,double b,double x){
Declare #maxIterations int = 50, #m int =1
Declare #eps Float = 3E-5
Declare #am Float = 1;
Declare #bm Float = 1;
Declare #az Float = 1;
Declare #qab Float = #a+#b;
Declare #qap Float = #a+1;
Declare #qam Float = #a-1;
Declare #bz Float = 1 - #qab*#x/#qap;
Declare #aold Float = 0;
Declare #em Float, #tem Float, #d Float, #ap Float, #bp Float, #app Float, #bpp Float;
while((#m<#maxIterations) AND (abs(#az-#aold)>=#eps*abs(#az)))
Begin
SET #em = #m;
SET #tem = #em+#em;
SET #d = #em*(#b-#m)*#x/((#qam + #tem)*(#a+#tem));
SET #ap = #az+#d*#am;
SET #bp = #bz+#d*#bm;
SET #d = -(#a+#em)*(#qab+#em)*#x/((#a+#tem)*(#qap+#tem));
SET #app = #ap+#d*#az;
SET #bpp = #bp+#d*#bz;
SET #aold = #az;
SET #am = #ap/#bpp;
SET #bm = #bp/#bpp;
SET #az = #app/#bpp;
SET #bz = 1;
SET #m = #m + 1;
End
return #az
END
--BETA INCOMPLETE Function
CREATE FUNCTION [dbo].[udf_BetaI]
(
#x Float=null
,#a Float=null
,#b Float=null
)
RETURNS Float
AS
BEGIN
Declare #bt Float=0.0
Declare #beta Float=0.0
if( #x=0 OR #x=1 )
Begin
SET #bt = 0
End
else if((#x>0) AND (#x<1))
Begin
SET #bt = (Select dbo.UDF_Gamma(#a+#b)* power(#x,#a)* power(1-#x,#b)/(dbo.UDF_Gamma(#a)*dbo.UDF_Gamma(#b)) )
End
if(#x<(#a+1)/(#a+#b+2))
Begin
SET #beta = (Select #bt*dbo.udf_betaC(#x,#a,#b)/#a)
End
else
Begin
SET #beta = (Select 1-#bt*dbo.udf_betaC(1-#x,#b,#a)/#b)
End
Return #beta
END
--FDist Function
CREATE FUNCTION [dbo].[udf_FDist]
(
#x Float=NULL
,#df1 Float=NULL
,#df2 Float=NULL
)
RETURNS Float
AS
BEGIN
Declare #x1 Float=(#x*#df1)/((#x*#df1)+#df2)
return (select 1 - dbo.udf_BetaI(#x1,(#df1/2),(#df2/2)))
END
Check in Excel =FDIST(0.5,1,1)=0.608173448
and in SQL editor = SELECT udf_FDIST(0.5,1,1)=0.608173457369209
Regards,
Avi
FDIST an FINV Don't exists IN Sql Server.
You can write a SQL Sever function to implement two excel feature.
Show here to create function
in MS SQL Server there is standard_deviation
and some more statistical functions including variance.
There is also a million workarounds, for example: http://oreilly.com/catalog/transqlcook/chapter/ch08.html
,you need to dig deep into the math for these, though.
Does anyone know of a truly declarative language? The behavior I'm looking for is kind of what Excel does, where I can define variables and formulas, and have the formula's result change when the input changes (without having set the answer again myself)
The behavior I'm looking for is best shown with this pseudo code:
X = 10 // define and assign two variables
Y = 20;
Z = X + Y // declare a formula that uses these two variables
X = 50 // change one of the input variables
?Z // asking for Z should now give 70 (50 + 20)
I've tried this in a lot of languages like F#, python, matlab etc, but every time I tried this they come up with 30 instead of 70. Which is correct from an imperative point of view, but I'm looking for a more declarative behavior if you know what I mean.
And this is just a very simple calculation. When things get more difficult it should handle stuff like recursion and memoization automagically.
The code below would obviously work in C# but it's just so much code for the job, I'm looking for something a bit more to the point without all that 'technical noise'
class BlaBla{
public int X {get;set;} // this used to be even worse before 3.0
public int Y {get;set;}
public int Z {get{return X + Y;}}
}
static void main(){
BlaBla bla = new BlaBla();
bla.X = 10;
bla.Y = 20;
// can't define anything here
bla.X = 50; // bit pointless here but I'll do it anyway.
Console.Writeline(bla.Z);// 70, hurray!
}
This just seems like so much code, curly braces and semicolons that add nothing.
Is there a language/ application (apart from Excel) that does this? Maybe I'm no doing it right in the mentioned languages, or I've completely missed an app that does just this.
I prototyped a language/ application that does this (along with some other stuff) and am thinking of productizing it. I just can't believe it's not there yet. Don't want to waste my time.
Any Constraint Programming system will do that for you.
Examples of CP systems that have an associated language are ECLiPSe, SICSTUS Prolog / CP package, Comet, MiniZinc, ...
It looks like you just want to make Z store a function instead of a value. In C#:
var X = 10; // define and assign two variables
var Y = 20;
Func<int> Z = () => X + Y; // declare a formula that uses these two variables
Console.WriteLine(Z());
X = 50; // change one of the input variables
Console.WriteLine(Z());
So the equivalent of your ?-prefix syntax is a ()-suffix, but otherwise it's identical. A lambda is a "formula" in your terminology.
Behind the scenes, the C# compiler builds almost exactly what you presented in your C# conceptual example: it makes X into a field in a compiler-generated class, and allocates an instance of that class when the code block is entered. So congratulations, you have re-discovered lambdas! :)
In Mathematica, you can do this:
x = 10; (* # assign 30 to the variable x *)
y = 20; (* # assign 20 to the variable y *)
z := x + y; (* # assign the expression x+y to the variable z *)
Print[z];
(* # prints 30 *)
x = 50;
Print[z];
(* # prints 70 *)
The operator := (SetDelayed) is different from = (Set). The former binds an unevaluated expression to a variable, the latter binds an evaluated expression.
Wanting to have two definitions of X is inherently imperative. In a truly declarative language you have a single definition of a variable in a single scope. The behavior you want from Excel corresponds to editing the program.
Have you seen Resolver One? It's like Excel with a real programming language behind it.
Here is Daniel's example in Python, since I noticed you said you tried it in Python.
x = 10
y = 10
z = lambda: x + y
# Output: 20
print z()
x = 20
# Output: 30
print z()
Two things you can look at are the cells lisp library, and the Modelica dynamic modelling language, both of which have relation/equation capabilities.
There is a Lisp library with this sort of behaviour:
http://common-lisp.net/project/cells/
JavaFX will do that for you if you use bind instead of = for Z
react is an OCaml frp library. Contrary to naive emulations with closures it will recalculate values only when needed
Objective Caml version 3.11.2
# #use "topfind";;
# #require "react";;
# open React;;
# let (x,setx) = S.create 10;;
val x : int React.signal = <abstr>
val setx : int -> unit = <fun>
# let (y,sety) = S.create 20;;
val y : int React.signal = <abstr>
val sety : int -> unit = <fun>
# let z = S.Int.(+) x y;;
val z : int React.signal = <abstr>
# S.value z;;
- : int = 30
# setx 50;;
- : unit = ()
# S.value z;;
- : int = 70
You can do this in Tcl, somewhat. In tcl you can set a trace on a variable such that whenever it is accessed a procedure can be invoked. That procedure can recalculate the value on the fly.
Following is a working example that does more or less what you ask:
proc main {} {
set x 10
set y 20
define z {$x + $y}
puts "z (x=$x): $z"
set x 50
puts "z (x=$x): $z"
}
proc define {name formula} {
global cache
set cache($name) $formula
uplevel trace add variable $name read compute
}
proc compute {name _ op} {
global cache
upvar $name var
if {[info exists cache($name)]} {
set expr $cache($name)
} else {
set expr $var
}
set var [uplevel expr $expr]
}
main
Groovy and the magic of closures.
def (x, y) = [ 10, 20 ]
def z = { x + y }
assert 30 == z()
x = 50
assert 70 == z()
def f = { n -> n + 1 } // define another closure
def g = { x + f(x) } // ref that closure in another
assert 101 == g() // x=50, x + (x + 1)
f = { n -> n + 5 } // redefine f()
assert 105 == g() // x=50, x + (x + 5)
It's possible to add automagic memoization to functions too but it's a lot more complex than just one or two lines. http://blog.dinkla.net/?p=10
In F#, a little verbosily:
let x = ref 10
let y = ref 20
let z () = !x + !y
z();;
y <- 40
z();;
You can mimic it in Ruby:
x = 10
y = 20
z = lambda { x + y }
z.call # => 30
z = 50
z.call # => 70
Not quite the same as what you want, but pretty close.
not sure how well metapost (1) would work for your application, but it is declarative.
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
x = 10
y = 20
z = function() return x + y; end
x = 50
= z()
70
It's not what you're looking for, but Hardware Description Languages are, by definition, "declarative".
This F# code should do the trick. You can use lazy evaluation (System.Lazy object) to ensure your expression will be evaluated when actually needed, not sooner.
let mutable x = 10;
let y = 20;
let z = lazy (x + y);
x <- 30;
printf "%d" z.Value