I want to test if a tcl-matrix object exists. How can I do that?
Following code isn't working.
package require struct::matrix
# Test (now we expect 0)
info exists m
# Create the object
struct::matrix m
# Test again, now I expect 1, however it returns 0!!!
info exists m
Use info commands to test for the existence of a matrix object. info exists tests for the (non-)existence of variables.
% package req struct::matrix
2.0.3
% info commands m
% struct::matrix m
::m
% info commands m
m
Background
A matrix object is implemented as a Tcl command (an alias command, to be precise) plus per-matrix Tcl namespace (as storage).
Alternatively, but this depends to much on the current implementation, you may test for the existence of a so-named namespace:
% package req struct::matrix
2.0.3
% namespace exists m
0
% struct::matrix m
::m
% namespace exists m
1
Testing for the command will also keep working when a matrix object becomes re-implemented as a TclOO object, for instance.
With a bit of poking through the struct::matrix source code:
% package req struct::matrix
2.0.3
% set m [struct::matrix]
::matrix1
% expr {$m in [interp aliases]}
1
% string first MatrixProc [interp alias {} $m]
18
% proc is_matrix {name} {
expr {
$name in [interp aliases] &&
[string first MatrixProc [interp alias {} $name]] != -1
}
}
% is_matrix $m
1
If you use the struct::matrix m form, then instead of $m, use the fully qualified ::m
% struct::matrix m
::m
% is_matrix m
0
% is_matrix ::m
1
Related
I am trying to write a constructor for a derived type of an abstract one to solve this other question, but it seems that it's not working, or better, it isn't called at all.
The aim is to have a runtime polymorphism setting the correct number of legs of an animal.
These are the two modules:
animal
module animal_module
implicit none
type, abstract :: animal
private
integer, public :: nlegs = -1
contains
procedure :: legs
end type animal
contains
function legs(this) result(n)
class(animal), intent(in) :: this
integer :: n
n = this%nlegs
end function legs
cat
module cat_module
use animal_module, only : animal
implicit none
type, extends(animal) :: cat
private
contains
procedure :: setlegs => setlegs
end type cat
interface cat
module procedure init_cat
end interface cat
contains
type(cat) function init_cat(this)
class(cat), intent(inout) :: this
print *, "Cat!"
this%nlegs = -4
end function init_cat
main program
program oo
use animal_module
use cat_module
implicit none
type(cat) :: c
type(bee) :: b
character(len = 3) :: what = "cat"
class(animal), allocatable :: q
select case(what)
case("cat")
print *, "you will see a cat"
allocate(cat :: q)
q = cat() ! <----- this line does not change anything
case default
print *, "ohnoes, nothing is prepared!"
stop 1
end select
print *, "this animal has ", q%legs(), " legs."
print *, "cat animal has ", c%legs(), " legs."
end program
The constructor isn't called at all, and the number of legs still remains to -1.
The available non-default constructor for the cat type is given by the module procedure init_cat. This function you have defined like
type(cat) function init_cat(this)
class(cat), intent(inout) :: this
end function init_cat
It is a function with one argument, of class(cat). In your later reference
q = cat()
There is no specific function under the generic cat which matches that reference: the function init_cat does not accept a no-argument reference. The default structure constructor is instead used.
You must reference the generic cat in a way matching your init_cat interface to have that specific function called.
You want to change your init_cat function to look like
type(cat) function init_cat()
! print*, "Making a cat"
init_cat%nlegs = -4
end function init_cat
Then you can reference q=cat() as desired.
Note that in the original, you are attempting to "construct" a cat instance, but you aren't returning this constructed entity as the function result. Instead, you are modifying an argument (already constructed). Structure constructors are intended to be used returning such useful things.
Note also that you don't need to
allocate (cat :: q)
q = cat()
The intrinsic assignment to q already handles q's allocation.
FWIW, here is some sample code comparing three approaches (method = 1: sourced allocation, 2: polymorphic assignment, 3: mixed approach).
module animal_module
implicit none
type, abstract :: animal_t
integer :: nlegs = -1
contains
procedure :: legs !! defines a binding to some procedure
endtype
contains
function legs(this) result(n)
class(animal_t), intent(in) :: this
!! The passed variable needs to be declared as "class"
!! to use this routine as a type-bound procedure (TBP).
integer :: n
n = this % nlegs
end
end
module cat_module
use animal_module, only : animal_t
implicit none
type, extends(animal_t) :: cat_t
endtype
interface cat_t !! overloads the definition of cat_t() (as a procedure)
module procedure make_cat
end interface
contains
function make_cat() result( ret ) !! a usual function
type(cat_t) :: ret !<-- returns a concrete-type object
ret % nlegs = -4
end
end
program main
use cat_module, only: cat_t, animal_t
implicit none
integer :: method
type(cat_t) :: c
class(animal_t), allocatable :: q
print *, "How to create a cat? [method = 1,2,3]"
read *, method
select case ( method )
case ( 1 )
print *, "1: sourced allocation"
allocate( q, source = cat_t() )
!! An object created by a function "cat_t()" is used to
!! allocate "q" with the type and value taken from source=.
!! (Empirically most stable for different compilers/versions.)
case ( 2 )
print *, "2: polymorphic assignment"
q = cat_t()
!! Similar to sourced allocation. "q" is automatically allocated.
!! (Note: Old compilers may have bugs, so tests are recommended...)
case ( 3 )
print *, "3: mixed approach"
allocate( cat_t :: q )
q = cat_t()
!! First allocate "q" with a concrete type "cat_t"
!! and then assign a value obtained from cat_t().
case default ; stop "unknown method"
endselect
c = cat_t()
!! "c" is just a concrete-type variable (not "allocatable")
!! and assigned with a value obtained from cat_t().
print *, "c % legs() = ", c % legs()
print *, "q % legs() = ", q % legs()
end
--------------------------------------------------
Test
$ gfortran test.f90 # using version 8 or 9
$ echo 1 | ./a.out
How to create a cat? [method = 1,2,3]
1: sourced allocation
c % legs() = -4
q % legs() = -4
$ echo 2 | ./a.out
How to create a cat? [method = 1,2,3]
2: polymorphic assignment
c % legs() = -4
q % legs() = -4
$ echo 3 | ./a.out
How to create a cat? [method = 1,2,3]
3: mixed approach
c % legs() = -4
q % legs() = -4
--------------------------------------------------
Side notes
* It is also OK to directly use make_cat() to generate a value of cat_t:
e.g., allocate( q, source = make_cat() ) or q = make_cat().
In this case, we do not need to overload cat_t() via interface.
* Another approach is to write an "initializer" as a type-bound procedure,
and call it explicitly as q % init() (after allocating it via
allocate( cat_t :: q )). If the type contains pointer components,
this approach may be more straightforward by avoiding copy of
components (which can be problematic for pointer components).
Say I have a module to be compiled via f2py:
test.f90
module test
implicit none
integer, parameter :: q = 2
real(8), parameter, dimension(-q:q) :: vec = (/ 1, 2, 3, 4, 5 /)
contains
subroutine writevec()
write(*,*) vec
end subroutine
end module
Upon running f2py -c -m test test.f90, I get the error
/tmp/tmp6X6gsD/src.linux-x86_64-2.7/testmodule.c:176:17: error: expected expression before ‘)’ token
{"vec",1,{{-(-)+1}},NPY_DOUBLE},
On the other hand, if I declare vec with dimension(2*q+1), it works. Sort of. When I import into python:
>>> from test import test
>>> test.writevec()
>>> 1.0000000000000000 2.0000000000000000 3.0000000000000000 4.0000000000000000 5.0000000000000000
>>> test.vec
>>> array([ 1., 2.]) # ???
What is going on here??
You can create a signature file in order to get the array dimensions right. This creates the signature file 'sign.pyf' for the python module 'mymod':
f2py -m mymod -h sign.pyf test.f90
Then, use this to compile:
f2py -c sign.pyf test.f90
The library can be imported and used in Python as:
>>>import mymod
>>>mymod.test.writevec()
Note, that the array bounds are shifted and the first element has the index 0 in Python:
>>>import mymod
>>>mymod.test.vec #output: array([ 1., 2., 3., 4., 5.])
>>>mymod.test.vec[0] #output: 1.0
I'd like to have my code take code written in another document, read it, and then use it as though it was written in the code. Say we have the following:
MODULE samplemod
CONTAINS
FUNCTION sillysum(boudary,function) RESULT(counter)
IMPLICIT NONE
REAL(KIND=8) :: boundary, counter
REAL(KIND=8), DIMENSION(:) :: function
INTEGER :: m
counter = 0.d0
DO m = 1, my_mesh%me
counter = function(m) + externalfunction
END DO
END FUNCTION sillysum
END MODULE samplemod
PROGRAM sampleprogram
USE samplemod
REAL(KIND=8), DIMENSION(:) :: function1
ALLOCATE(function1(100))
DO m=1, 100
function1(i) = i
END DO
WRITE(*,*) sillysum(100,function1)
END PROGRAM sampleprogram
Where in some external file (say 'externfunct.txt') one has written m**2. How can the Fortran code read the external function m**2, SIN(m), or even 0 and have that replace externalfunction. Here's a simpler example:
REAL(KIND=8) :: x = 2
CHARACTER(LEN=*) :: strng = "external"
WRITE(*,*) "Hello world, 2 + ", strng, " = ", 2 + external
Where in a txt file I have written I have written SIN(x).
I think there are two different approaches for this (* in fact, there seems a "third" approach also, see EDIT); one is to use a shared library, and the other is to use a parser for math expressions. The first approach is described in a Rossetastone page (Call a function in a shared library) and an SO page (Fortran dynamic libraries, load at runtime?), for example. For the second approach, you can find 3rd-party libraries by searching with "math parser" or "Fortran math parser" etc. Here, I have tried this one because it seems pretty simple (only one module and no installation). If we write a simple test program like this
program test
use interpreter, only: init, evaluate, dp => realkind
implicit none
integer, parameter :: mxvars = 10 !! consider 10 variables at most here
character(10) :: symbols( mxvars )
real(dp) :: values( mxvars ), answer
character(1000) :: funcstr !! a user-defined math expression
character(5) :: stat
!> Define variable names.
symbols( 1 ) = "x"
symbols( 2 ) = "a"
symbols( 3 ) = "b"
symbols( 4 ) = "c"
symbols( 5 ) = "foo"
!> Get a math expression.
print *, "Please input a math expression:"
read(*, "(a)") funcstr !! e.g., a * x + b
!> Init the evaluator.
call init( funcstr, symbols, stat )
if ( stat /= "ok" ) stop "stat /= ok"
!> Set values for the variables.
values( : ) = 0
values( 1 ) = 2.0_dp ! x
values( 2 ) = 10.0_dp ! a
values( 3 ) = 7.0_dp ! b
!> Evaluate.
answer = evaluate( values )
print *, "function value = ", answer
end program
and compile it as (*1)
$ gfortran -ffree-line-length-none interpreter.f90 mytest.f90
we can test various expressions as follows:
$ ./a.out
Please input a math expression:
a * x + b
function value = 27.000000000000000
$ ./a.out
Please input a math expression:
sin( a * x ) + cos( b ) + foo
function value = 1.6668475050709324
The usage of other libraries also seems very similar. Because the performance of each library may be rather different, it may be useful to try several different libraries for comparison.
(*1) The module has some lines with sind, cosd, and tand, but they are not supported by gfortran. So, to compile, I have commented them out and replaced them by stop, i.e.,
stop "sind not supported..."
! pdata(st) = sind(pdata(st))
(I guess sind(x) means sin( x * pi / 180 ), so it may be OK to define it as such.)
[EDIT]
A "third" approach may be to call the built-in eval() function in interpreted languages like Python or Julia via system(), e.g., this SO page. Although this also has a lot of weak points (and it is probably much easier to use such languages directly), calling eval() from Fortran might be useful for some specific purposes.
As a beginner in Z3, I am wondering if there is a way to make Z3Py work with a predefined Python function. Following is a small example which explains my question.
from z3 import *
def f(x):
if x > 0:
print " > 0"
return 1
else:
print " <= 0"
return 0
a=Int('a')
s=Solver()
s.insert(f(a) == 0)
t = s.check()
print t
print a
m = s.model()
print m
f(x) is a function defined in python. When x <= 0, f(x) returns 0. I add a constraint s.insert(f(a) == 0) and hope that Z3 can find a appropriate value for variable "a" (e.g. -3). But these codes are not working correctly. How should I change it?
(Please note that I need f(x) defined outside Z3, and then is called by Z3. )
What I am trying to do is calling a predefined function provided by a graph library without translating it to Z3. I am using the NetworkX library, and some codes are given as following:
import networkx as nx
G1=nx.Graph()
G1.add_edge(0,1)
G2=nx.Graph()
G2.add_edge(0,1)
G2.add_edge(1,2)
print(nx.is_isomorphic(G1, G2))
#False
I need Z3 to help me find a vertex in G2 such that after removing this vertex, G2 is isomorphic to G1. e.g.
G2.remove_node(0)
print(nx.is_isomorphic(G1, G2))
#True
I think this will be tough if f is a general function (e.g., what if it's recursive?), although if you assume it has some structure (e.g., if then else), you might be able to write a simple translator. The issue is that Z3's functions are mathematical in nature and not directly equivalent to Python functions (see http://en.wikipedia.org/wiki/Uninterpreted_function ). If possible for your purpose, I would propose to go the opposite direction: define your function f in terms of Z3 constructs, then evaluate it within your program (e.g., using this method: Z3/Python getting python values from model ). If that won't work for you, please include some additional details on how you need to use the function. Here's a minimal example (rise4fun link: http://rise4fun.com/Z3Py/pslw ):
def f(x):
return If(x > 0, 1, 0)
a=Int('a')
s=Solver()
P = (f(a) == 0)
s.add(P)
t = s.check()
print t
print a
m = s.model()
print m
res = simplify(f(m[a])) # evaluate f at the assignment to a found by Z3
print "is_int_value(res):", is_int_value(res)
print res.as_long() == 0 # Python 0
print f(1)
print simplify(f(1)) # Z3 value of 1, need to convert as above
Apparently the cconv function is not yet implemented for Octave's signal package. What is a simple way to reproduce its functionality?
The code which would like to execute is:
pkg load signal
n=linspace(0,1,1024);
s=sin(2.*pi.*1.*n)+.3.*sin(2.*pi.*4.*n);
x=s+.1.*randn(size(s));
L=100;
y=cconv(x,ones(1,L)./L,1024);
figure,plot(y);
xlabel('n'),ylabel('y[n]'),title('Output y[n]')
But the following error message is shown after trying to use cconv():
warning: the 'cconv' function belongs to the signal package from Octave Forge but
has not yet been implemented.
The code is an assignment provided by edX' "Discrete Time Signals and Systems" where an integrated Matlab-interface is provided. I would like to use Octave though.
function a = cconv( b, c )
nb = length(b) ;
nc = length(c) ;
##
## Ensure the two vectors are the same length
##
if (nb < nc)
b = [ b zeros(1,nc-nb) ] ;
endif
if (nc < nb)
c = [ c zeros(1,nb-nc) ] ;
endif
a = ifft(fft(b) .* fft(c)) ;
##
## Get rid of any tiny imaginary bits that should be zero
##
if (all(b == real(b)) && all(c == real(c)))
a = real(a) ;
endif
endfunction
(source)
What about this implimentation from File Exchange?
http://www.mathworks.com/matlabcentral/fileexchange/13030-circular-convolution/content/cconv.m
Here's how to do circular convolution that gives identical results to the ifft(fft.*fft) method.
x=[1,2,3,4,3,2,5,0,1,-10,-1,3];
h=[0.5, 0.3, 0.15, 0.05];
Lx=length(x);
Lh=length(h);
y=zeros(1,Lx+Lh-1);
% circular convolution without zero padding and fft
y=conv([x((end-Lh+2):end) x],h);
y1=y(Lh:end-Lh+1)
% fft method for circular convolution (must zero pad to equal size)
y2=ifft(fft(x).*fft([h zeros(1,Lx-Lh)]))