Coder Social home page Coder Social logo

mgaitan / fortran_magic Goto Github PK

View Code? Open in Web Editor NEW
117.0 12.0 33.0 79 KB

An extension for IPython/Jupyter that helps to use Fortran in your interactive session.

License: BSD 3-Clause "New" or "Revised" License

Python 55.65% Jupyter Notebook 41.76% Fortran 1.40% Shell 1.20%

fortran_magic's Introduction

Fortran magic

PyPI PyPI - Downloads

Compile and import symbols from a cell with Fortran code, using f2py.


Attention!

I am looking for collaborators to maintain this project. If you are interested, please open an issue (or PRs) with your proposals for improvements and volunteer to be a maintainer.


The contents of the cell are written to a .f90 file in the directory IPYTHONDIR/fortran using a filename with the hash of the code. This file is then compiled. The resulting module is imported and all of its symbols are injected into the user's namespace.

homepage:https://github.com/mgaitan/fortran_magic
documentation:see this notebook

Install

You can install or upgrade via pip

pip install -U fortran-magic

Basic usage

Once it's installed, you can load it with %load_ext fortranmagic. Then put your Fortran code in a cell started with the cell magic %%fortran. For example:

In[1]: %load_ext fortranmagic

In[2]: import sys

       if sys.platform.startswith("win"):
           # Depends of system, python builds, and compilers compatibility.
           # See `documentation.ipnb`.
           %fortran_config --fcompiler=gnu95 --compiler=mingw32

In[3]: %%fortran

       subroutine f1(x, y, z)
            real, intent(in) :: x,y
            real, intent(out) :: z

            z = sin(x+y)

       end subroutine f1

Every symbol is automatically imported. So the subroutine f1 is already available in your python session as a function:

In[4]:  f1(1.0, 2.1415)
Out[4]: 9.26574066397734e-05

See the documentation for further details.

fortran_magic's People

Contributors

astrojuanlu avatar bfroehle avatar carreau avatar guihigashi avatar jr3cermak avatar mgaitan avatar qulogic avatar serge3leo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fortran_magic's Issues

fortranmagic should call f2py3 under Python 3

Otherwise it will silently use an f2py that may have a hardcoded #!/usr/bin/python27 at the top, resulting in puzzling errors because the compiled objects look at the wrong Python includes.

ImportError: dlopen

I am getting 'dlopen' import error when I try to use Fortran magic. I am using Anaconda distribution for Python 3.4 in OS X 10.11.1. I installed Fortran magic by shell command 'pip install -U fortran-magic'.

%load_ext fortranmagic
/Users/rakesh/Applications/anaconda/lib/python3.4/site-packages/IPython/utils/path.py:264: UserWarning: get_ipython_cache_dir has moved to the IPython.paths module
warn("get_ipython_cache_dir has moved to the IPython.paths module")

%%fortran
subroutine f1(x, y, z)
real, intent(in) :: x,y
real, intent(out) :: z
z = sin(x+y)
end subroutine f1


ImportError Traceback (most recent call last)
in ()
----> 1 get_ipython().run_cell_magic('fortran', '', '\n subroutine f1(x, y, z)\n real, intent(in) :: x,y\n real, intent(out) :: z\n\n z = sin(x+y)\n\n end subroutine f1')

/Users/rakesh/Applications/anaconda/lib/python3.4/site-packages/IPython/core/interactiveshell.py in run_cell_magic(self, magic_name, line, cell)
2291 magic_arg_s = self.var_expand(line, stack_depth)
2292 with self.builtin_trap:
-> 2293 result = fn(magic_arg_s, cell)
2294 return result
2295

/Users/rakesh/.ipython/extensions/fortranmagic.py in fortran(self, line, cell)

/Users/rakesh/Applications/anaconda/lib/python3.4/site-packages/IPython/core/magic.py in (f, _a, *_k)
191 # but it's overkill for just that one bit of state.
192 def magic_deco(arg):
--> 193 call = lambda f, _a, *_k: f(_a, *_k)
194
195 if callable(arg):

/Users/rakesh/.ipython/extensions/fortranmagic.py in fortran(self, line, cell)
365
366 self._code_cache[key] = module_name
--> 367 module = imp.load_dynamic(module_name, module_path)
368 self._import_all(module, verbosity=args.verbosity)
369

ImportError: dlopen(/Users/rakesh/.ipython/fortran/_fortran_magic_487194676cadd3691bcc8cb535c0d6dd.so, 2): image not found

version 0.7?

I noticed, on PyPI this is version 0.7, while here it's only 0.6. Did development move somewhere else?

Problem running on Windows

Hi,

I have trouble running this IPython extension, while f2py seem to run just fine on command line.

I use 64bit Python on Windows 8, with 64bit Mingw packages and running f2py example on command line looks like this: https://gist.github.com/vdivljak/9142692

Trying to run same test snippet with IPython Fortran magic fails like in this notebook: http://nbviewer.ipython.org/gist/vdivljak/9142634

Command issued by your extension seem to be just right, and I can't figure where may the problem be.
Do you perhaps, or anyone else, have an idea how to resolve this?

Thanks,
Vladan

failed to load fortranmagic

Hi I have installed fortran magic via conda successfully. See the message below:

(test) C:\Users\xxx>conda search fortran-magic --channel conda-forge
Loading channels: done

Name Version Build Channel

fortran-magic 0.7 py27_0 conda-forge
fortran-magic 0.7 py27_1 conda-forge
fortran-magic 0.7 py34_0 conda-forge
fortran-magic 0.7 py34_1 conda-forge
fortran-magic 0.7 py35_0 conda-forge
fortran-magic 0.7 py35_1 conda-forge
fortran-magic 0.7 py36_1 conda-forge
fortran-magic 0.7 py_1001 conda-forge

Howeve, when I use jupyter lab I failed to load it. I tried

%load_ext fortranmagic
or
import fortranmagic

but only have the error

"ModuleNotFoundError: No module named 'fortranmagic'"

Can you help me out? Thank you very much.

NameError with Python 3.3

Hi,
I have installed fortran-magic-0.4.2 on a system with IPython 1.1.0 and Python 3.3.2.
When I run the example in the python notebook I get the error:

/home/ramon/.config/ipython/extensions/fortranmagic.py in <listcomp>(.0)
    304 
    305         kw = ['--%s=%s' % (k, v) for k, v in vars(args).items()
--> 306               if isinstance(v, basestring)]
    307         f2py_args.extend(kw)
    308 

NameError: global name 'basestring' is not defined

I guess this is because basestring is no longer defined in python3. Here is a possible solution:
http://www.rfk.id.au/blog/entry/preparing-pyenchant-for-python-3/

Bytes/string error on Python 3.5 and IPython 4.0

I just tried the extension on Python 3.5 and IPython 4.0 and failed with this error (Linux):

In [6]: %%fortran
   ...: subroutine f1(x, y, z)
   ...: real, intent(in) :: x,y   
   ...: real, intent(out) :: z
   ...: z = sin(x + y)
   ...: end subroutine f1
   ...: 
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-177c9a1250d1> in <module>()
----> 1 get_ipython().run_cell_magic('fortran', '', 'subroutine f1(x, y, z)\nreal, intent(in) :: x,y\nreal, intent(out) :: z\nz = sin(x + y)\nend subroutine f1\n')

/home/s3fdf/anaconda3/envs/py35-pypi/lib/python3.5/site-packages/IPython/core/interactiveshell.py in run_cell_magic(self, magic_name, line, cell)
   2291             magic_arg_s = self.var_expand(line, stack_depth)
   2292             with self.builtin_trap:
-> 2293                 result = fn(magic_arg_s, cell)
   2294             return result
   2295 

/home/s3fdf/anaconda3/envs/py35-pypi/lib/python3.5/site-packages/fortranmagic.py in fortran(self, line, cell)

/home/s3fdf/anaconda3/envs/py35-pypi/lib/python3.5/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
    191     # but it's overkill for just that one bit of state.
    192     def magic_deco(arg):
--> 193         call = lambda f, *a, **k: f(*a, **k)
    194 
    195         if callable(arg):

/home/s3fdf/anaconda3/envs/py35-pypi/lib/python3.5/site-packages/fortranmagic.py in fortran(self, line, cell)
    360 
    361         self._run_f2py(f2py_args + ['-m', module_name, '-c', f90_file],
--> 362                        verbosity=args.verbosity)
    363 
    364         self._code_cache[key] = module_name

/home/s3fdf/anaconda3/envs/py35-pypi/lib/python3.5/site-packages/fortranmagic.py in _run_f2py(self, argv, show_captured, verbosity)
    185                       pass
    186                     if err:
--> 187                       sys.stderr.write(err)
    188                       sys.stderr.flush()
    189                 if show_captured or verbosity > 2:

TypeError: string argument expected, got 'bytes'

fortran_magic on windows

Hi Martin,

Just tried out fortran_magic in the ipython notebook on windows. Currently doesn't work on windows because the extension for a windows module is '.pyd', not '.so'. Therefore get an error about not being able to find the module. I have modified it on my system as follows to get it working:

    if 'win' in lower(sys.platform): 
        mod_ext = '.pyd'
    else: 
        mod_ext = '.so'
    module_path = os.path.join(lib_dir, module_name + mod_ext)

A similar mod in the master would be appreciated.

Cheers,
Mike

intent(hide)

Hi. First of all, thanks for this magic.
I'm new to fortran, so it is an awesome ability for me to try using fortran from IPython.

Unfortunately, I'm not able to use intent(hide) variables for sizes, while it seems important. It is code from official f2py guide:

subroutine zadd(a,b,c,n) ! in :add:add.f
   double complex dimension(n) :: a
   double complex dimension(n) :: b
   double complex intent(out),dimension(n) :: c
   integer intent(hide),depend(a) :: n=len(a)
   c = a + b    ! I want to use vector operations, so fortran 90 or later.
end subroutine zadd

And it fails compiling with very long log, important part is

    double complex dimension(n) :: a
                              1
Error: Syntax error in data declaration at (1)
/Users/axelr/.ipython/fortran/_fortran_magic_d1fc3ba820eff5c66eb0e6000c364ed6.f90:4:30:

    double complex dimension(n) :: b
                              1
Error: Syntax error in data declaration at (1)
/Users/axelr/.ipython/fortran/_fortran_magic_d1fc3ba820eff5c66eb0e6000c364ed6.f90:5:42:

    double complex intent(out),dimension(n) :: c
                                          1
Error: Syntax error in data declaration at (1)
/Users/axelr/.ipython/fortran/_fortran_magic_d1fc3ba820eff5c66eb0e6000c364ed6.f90:6:33:

    integer intent(hide),depend(a) :: n=len(a)
                                 1
Error: Syntax error in data declaration at (1)
/Users/axelr/.ipython/fortran/_fortran_magic_d1fc3ba820eff5c66eb0e6000c364ed6.f90:3:30:

    double complex dimension(n) :: a
                              1
Error: Syntax error in data declaration at (1)
/Users/axelr/.ipython/fortran/_fortran_magic_d1fc3ba820eff5c66eb0e6000c364ed6.f90:4:30:

    double complex dimension(n) :: b
                              1
Error: Syntax error in data declaration at (1)
/Users/axelr/.ipython/fortran/_fortran_magic_d1fc3ba820eff5c66eb0e6000c364ed6.f90:5:42:

Do you know a convenient way to work with arrays of dynamic size? Or there are some flags I should add?

Thanks in advance.

Getting gfortran compiler error when running example

Attempting to run an example for fortranmagic on a Mac Pro (2019) running Mac OSX ver. 13.3.1 (a) Ventura. I'm running

[Clang 14.0.6 ] :: Anaconda, Inc. on darwin

When running the example hosted on https://github.com/mgaitan/fortran_magic:

In[2]: %load_ext fortranmagic

In[3]: %%fortran

       subroutine f1(x, y, z)
            real, intent(in) :: x,y
            real, intent(out) :: z
            z = sin(x+y)
       end subroutine f1

The message I get is

   /Users/user/opt/anaconda3/bin/python -m numpy.f2py --noarch --fcompiler=gnu95 --compiler=unix --f90flags="-d" -m _fortran_magic_553c13c268582acb90e6b36e15d4b416 -c /Users/user/.cache/ipython/fortran/_fortran_magic_553c13c268582acb90e6b36e15d4b416.f90
running build
running config_cc
INFO: unifing config_cc, config, build_clib, build_ext, build commands --compiler options
running config_fc
INFO: unifing config_fc, config, build_clib, build_ext, build commands --fcompiler options
running build_src
INFO: build_src
INFO: building extension "_fortran_magic_553c13c268582acb90e6b36e15d4b416" sources
INFO: f2py options: []
INFO: f2py:> /var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/src.macosx-10.9-x86_64-3.9/_fortran_magic_553c13c268582acb90e6b36e15d4b416module.c
creating /var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/src.macosx-10.9-x86_64-3.9
Reading fortran codes...
	Reading file '/Users/user/.cache/ipython/fortran/_fortran_magic_553c13c268582acb90e6b36e15d4b416.f90' (format:free)
Post-processing...
	Block: _fortran_magic_553c13c268582acb90e6b36e15d4b416
			Block: f1
Post-processing (stage 2)...
Building modules...
    Building module "_fortran_magic_553c13c268582acb90e6b36e15d4b416"...
    Generating possibly empty wrappers"
    Maybe empty "_fortran_magic_553c13c268582acb90e6b36e15d4b416-f2pywrappers.f"
        Constructing wrapper function "f1"...
          z = f1(x,y)
    Wrote C/API module "_fortran_magic_553c13c268582acb90e6b36e15d4b416" to file "/var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/src.macosx-10.9-x86_64-3.9/_fortran_magic_553c13c268582acb90e6b36e15d4b416module.c"
INFO:   adding '/var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/src.macosx-10.9-x86_64-3.9/fortranobject.c' to sources.
INFO:   adding '/var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/src.macosx-10.9-x86_64-3.9' to include_dirs.
copying /Users/user/opt/anaconda3/lib/python3.9/site-packages/numpy/f2py/src/fortranobject.c -> /var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/src.macosx-10.9-x86_64-3.9
copying /Users/user/opt/anaconda3/lib/python3.9/site-packages/numpy/f2py/src/fortranobject.h -> /var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/src.macosx-10.9-x86_64-3.9
INFO:   adding '/var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/src.macosx-10.9-x86_64-3.9/_fortran_magic_553c13c268582acb90e6b36e15d4b416-f2pywrappers.f' to sources.
INFO: build_src: building npy-pkg config files
running build_ext
INFO: customize UnixCCompiler
INFO: customize UnixCCompiler using build_ext
INFO: customize Gnu95FCompiler
INFO: Found executable /usr/local/bin/gfortran
INFO: customize Gnu95FCompiler using build_ext
INFO: building '_fortran_magic_553c13c268582acb90e6b36e15d4b416' extension
INFO: compiling C sources
INFO: C compiler: clang -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -fwrapv -O2 -Wall -fPIC -O2 -isystem /Users/user/opt/anaconda3/include -arch x86_64 -I/Users/user/opt/anaconda3/include -fPIC -O2 -isystem /Users/user/opt/anaconda3/include -arch x86_64 -ftrapping-math

creating /var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/var
creating /var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/var/folders
creating /var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/var/folders/2r
creating /var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq
creating /var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T
creating /var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3
creating /var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/src.macosx-10.9-x86_64-3.9
INFO: compile options: '-DNPY_DISABLE_OPTIMIZATION=1 -I/var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/src.macosx-10.9-x86_64-3.9 -I/Users/user/opt/anaconda3/lib/python3.9/site-packages/numpy/core/include -I/Users/user/opt/anaconda3/include/python3.9 -c'
INFO: clang: /var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/src.macosx-10.9-x86_64-3.9/_fortran_magic_553c13c268582acb90e6b36e15d4b416module.c
INFO: clang: /var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/src.macosx-10.9-x86_64-3.9/fortranobject.c
INFO: compiling Fortran sources
INFO: Fortran f77 compiler: /usr/local/bin/gfortran -Wall -g -ffixed-form -fno-second-underscore -arch x86_64 -fPIC -O3 -funroll-loops
Fortran f90 compiler: /usr/local/bin/gfortran -d -arch x86_64 -fPIC -O3 -funroll-loops
Fortran fix compiler: /usr/local/bin/gfortran -Wall -g -ffixed-form -fno-second-underscore -d -arch x86_64 -fPIC -O3 -funroll-loops
creating /var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/Users
creating /var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/Users/user
creating /var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/Users/user/.cache
creating /var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/Users/user/.cache/ipython
creating /var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/Users/user/.cache/ipython/fortran
INFO: compile options: '-I/var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/src.macosx-10.9-x86_64-3.9 -I/Users/user/opt/anaconda3/lib/python3.9/site-packages/numpy/core/include -I/Users/user/opt/anaconda3/include/python3.9 -c'
INFO: gfortran:f90: /Users/user/.cache/ipython/fortran/_fortran_magic_553c13c268582acb90e6b36e15d4b416.f90

/Users/user/opt/anaconda3/lib/python3.9/site-packages/setuptools/command/install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
  warnings.warn(
In file included from /var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/src.macosx-10.9-x86_64-3.9/_fortran_magic_553c13c268582acb90e6b36e15d4b416module.c:22:
In file included from /var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/src.macosx-10.9-x86_64-3.9/fortranobject.h:13:
In file included from /Users/user/opt/anaconda3/lib/python3.9/site-packages/numpy/core/include/numpy/arrayobject.h:5:
In file included from /Users/user/opt/anaconda3/lib/python3.9/site-packages/numpy/core/include/numpy/ndarrayobject.hIn file included from /var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/src.macosx-10.9-x86_64-3.9/fortranobject.c::2:
12In file included from :
/var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/src.macosx-10.9-x86_64-3.9/fortranobject.hIn file included from :/Users/user/opt/anaconda3/lib/python3.9/site-packages/numpy/core/include/numpy/ndarraytypes.h13::
1948In file included from :
/Users/user/opt/anaconda3/lib/python3.9/site-packages/numpy/core/include/numpy/arrayobject.h:5:
In file included from /Users/user/opt/anaconda3/lib/python3.9/site-packages/numpy/core/include/numpy/ndarrayobject.h:12:
In file included from /Users/user/opt/anaconda3/lib/python3.9/site-packages/numpy/core/include/numpy/ndarraytypes.h:1948:
/Users/user/opt/anaconda3/lib/python3.9/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h/Users/user/opt/anaconda3/lib/python3.9/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h::1717::22::  warning: warning: "Using deprecated NumPy API, disable it with "          "#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" [-W#warnings]"Using deprecated NumPy API, disable it with "          "#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" [-W#warnings]

#warning "Using deprecated NumPy API, disable it with " \#warning "Using deprecated NumPy API, disable it with " \

 ^
 ^
1 warning generated.
1 warning generated.
gfortran: error: missing argument to '-d'
error: Command "/usr/local/bin/gfortran -d -arch x86_64 -fPIC -O3 -funroll-loops -I/var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/src.macosx-10.9-x86_64-3.9 -I/Users/user/opt/anaconda3/lib/python3.9/site-packages/numpy/core/include -I/Users/user/opt/anaconda3/include/python3.9 -c -c /Users/user/.cache/ipython/fortran/_fortran_magic_553c13c268582acb90e6b36e15d4b416.f90 -o /var/folders/2r/4bw6nw0x58z0_ybx632_h14m0000gq/T/tmpbtg3sti3/Users/user/.cache/ipython/fortran/_fortran_magic_553c13c268582acb90e6b36e15d4b416.o" failed with exit status 1

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[2], line 1
----> 1 get_ipython().run_cell_magic('fortran', '-vvv --fcompiler gnu95 --compiler unix --f90flags "-d" --noarch', '\nsubroutine f1(x, y, z)\n    real, intent(in) :: x,y\n    real, intent(out) :: z\n\n    z = sin(x+y)\n\nend subroutine f1\n')

File ~/opt/anaconda3/lib/python3.9/site-packages/IPython/core/interactiveshell.py:2475, in InteractiveShell.run_cell_magic(self, magic_name, line, cell)
   2473 with self.builtin_trap:
   2474     args = (magic_arg_s, cell)
-> 2475     result = fn(*args, **kwargs)
   2477 # The code below prevents the output from being displayed
   2478 # when using magics with decodator @output_can_be_silenced
   2479 # when the last Python token in the expression is a ';'.
   2480 if getattr(fn, magic.MAGIC_OUTPUT_CAN_BE_SILENCED, False):

File ~/opt/anaconda3/lib/python3.9/site-packages/fortranmagic.py:368, in FortranMagics.fortran(self, line, cell)
    365 res = self._run_f2py(f2py_args + ['-m', module_name, '-c', f90_file],
    366                      verbosity=args.verbosity)
    367 if res != 0:
--> 368    raise RuntimeError("f2py failed, see output")
    370 self._code_cache[key] = module_name
    371 module = imp.load_dynamic(module_name, module_path)

RuntimeError: f2py failed, see output

Any suggestions?

Retrieve fortran source code

@mgaitan Hi, very nice piece of work.

One question: is there any easy way to retrieve the original fortran code, e.g. as a mere string, from the generated function ? Something like

In[2]: %load_ext fortranmagic

In[3]: %%fortran

       subroutine f1(x, y, z)
            real, intent(in) :: x,y
            real, intent(out) :: z

            z = sin(x+y)

       end subroutine f1

In[4]: print(f1.__source__)

       subroutine f1(x, y, z)
            real, intent(in) :: x,y
            real, intent(out) :: z

            z = sin(x+y)

       end subroutine f1

The motivation can be to reuse the source code for further transformations, such as automatic differentiation (e.g. with Tapenade online tool).

Running the Example notebook fails

I'm on MacOS X, Jupyter 4.3.0, python 3.6.1 and am getting the following on execution of the fortran cell. I can't figure out what this means or how to fix it.

Things were working on my machine some time ago, but thousands of minor upgrades since I last tried and used it so it's infeasible to figure out what might have broke it.


ImportError Traceback (most recent call last)
in ()
----> 1 get_ipython().run_cell_magic('fortran', '', '\nsubroutine f1(x, y, z)\n real, intent(in) :: x,y\n real, intent(out) :: z\n\n z = sin(x+y)\n\nend subroutine f1')

~/anaconda/lib/python3.6/site-packages/IPython/core/interactiveshell.py in run_cell_magic(self, magic_name, line, cell)
2101 magic_arg_s = self.var_expand(line, stack_depth)
2102 with self.builtin_trap:
-> 2103 result = fn(magic_arg_s, cell)
2104 return result
2105

in fortran(self, line, cell)

~/anaconda/lib/python3.6/site-packages/IPython/core/magic.py in (f, *a, **k)
185 # but it's overkill for just that one bit of state.
186 def magic_deco(arg):
--> 187 call = lambda f, *a, **k: f(*a, **k)
188
189 if callable(arg):

~/Documents/python-dev/fortran_magic/fortranmagic.py in fortran(self, line, cell)
368
369 self._code_cache[key] = module_name
--> 370 module = imp.load_dynamic(module_name, module_path)
371 self._import_all(module, verbosity=args.verbosity)
372

~/anaconda/lib/python3.6/imp.py in load_dynamic(name, path, file)
340 spec = importlib.machinery.ModuleSpec(
341 name=name, loader=loader, origin=path)
--> 342 return _load(spec)
343
344 else:

~/anaconda/lib/python3.6/importlib/_bootstrap.py in _load(spec)

~/anaconda/lib/python3.6/importlib/_bootstrap.py in _load_unlocked(spec)

~/anaconda/lib/python3.6/importlib/_bootstrap.py in module_from_spec(spec)

~/anaconda/lib/python3.6/importlib/_bootstrap_external.py in create_module(self, spec)

~/anaconda/lib/python3.6/importlib/_bootstrap.py in _call_with_frames_removed(f, *args, **kwds)

ImportError: dlopen(/Users/jslater/.ipython/fortran/_fortran_magic_c5e7e14a004b240d5916d25afb069a7a.cpython-36m-darwin.so, 2): Symbol not found: ___addtf3
Referenced from: /Users/jslater/anaconda/lib/./libquadmath.0.dylib
Expected in: /usr/local/lib/libgcc_s.1.dylib
in /Users/jslater/anaconda/lib/./libquadmath.0.dylib

UnicodeDecodeError when debugging fortran code

When I debugged the fortran code in IPython notebook, the following error occurred:

UnicodeDecodeError Traceback (most recent call last)
in ()
----> 1 get_ipython().run_cell_magic(u'fortran', u'-vvv', u'my fortran module')

/Users/xxx/anaconda/lib/python2.7/site-packages/IPython/core/interactiveshell.pyc in run_cell_magic(self, magic_name, line, cell)
2291 magic_arg_s = self.var_expand(line, stack_depth)
2292 with self.builtin_trap:
-> 2293 result = fn(magic_arg_s, cell)
2294 return result
2295

in fortran(self, line, cell)

/Users/xxx/anaconda/lib/python2.7/site-packages/IPython/core/magic.pyc in (f, *a, **k)
191 # but it's overkill for just that one bit of state.
192 def magic_deco(arg):
--> 193 call = lambda f, *a, **k: f(*a, **k)
194
195 if callable(arg):

/Users/xxx/anaconda/lib/python2.7/site-packages/fortranmagic.pyc in fortran(self, line, cell)
375
376 res = self._run_f2py(f2py_args + ['-m', module_name, '-c', f90_file],
--> 377 verbosity=args.verbosity)
378 if res != 0:
379 raise RuntimeError("f2py failed, see output")

/Users/xxx/anaconda/lib/python2.7/site-packages/fortranmagic.pyc in _run_f2py(self, argv, show_captured, verbosity)
202 if show_captured or verbosity > 2:
203 if out:
--> 204 sys.stdout.write(out.decode())
205 sys.stdout.flush()
206 captured()

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 6133: ordinal not in range(128)

If I use option -v or -vv, it says the fortran objects are ready to use. But when I call the subroutine, it says 'name xxx not defined', which suggests the fortran module is not compile correctly? I'm not sure what's going on??

how to pass intel64 ifort compiler option from jupyter notebook?

%%fortran --fcompiler intelvem - this does not work.

Right now I have to first setup ifort in the shell and start jupyter notebook from the same shell:

C:\Program Files (x86)\IntelSWTools\compilers_and_libraries\windows\bin>ifortvars.bat intel64 vs2015

Intel(R) MPI Library 5.1 Update 3 for Windows* Target Build Environment for Intel(R) 64 applications
Copyright (C) 2007-2015 Intel Corporation. All rights reserved.

Copyright (C) 1985-2016 Intel Corporation. All rights reserved.
Intel(R) Compiler 16.0 Update 2 (package 180)



C:\Program Files (x86)\IntelSWTools\compilers_and_libraries\windows\bin>cd c:\Users

c:\Users>jupyter notebook

Does not work on python3

This implementation is not correctly working with python3. Is there any plan to make it work for python3? In any case it might be useful to explicitly state that the current implementation works for python2 only.

Number bugs

  1. Python 3.12b2 remove imp
$ pip install fortran-magic
...
Successfully installed fortran-magic-0.7.1
$ python
Python 3.12.0b2+ (remotes/origin/3.12:2b6f475db8, Jun  8 2023, 13:18:24) [Clang 14.0.3 (clang-1403.0.22.14.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import fortranmagic
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/leo/opt/anaconda3/envs/tfm312/lib/python3.12/site-packages/fortranmagic.py", line 17, in <module>
    import imp
ModuleNotFoundError: No module named 'imp'
  1. If set verbosity level by %fortran_config -v, then the first magic block %fortran will have a level - 1, the second - 2, the third - 4. Similarly, the --extra and --link flags will also exponentially duplicates;
  2. When changing %fortran_config flags, the changed module has the same name and, therefore, it does not reload (macOS/Linux) or is not rebuild (Windows locks DLLs). See example: test/test_zload_ext.py;
  3. The "enable fortran highlight" part of load_ipython_extension() doesn't work because it's designed for IPython 3.x. In addition, some browsers (or antiviruses) block loading "https://raw.github.com/marijnh/CodeMirror/master/mode/fortran/fortran.js "

Ipython and Javascript error

LS,

I am getting the following error when trying to run this package with a jupyter notebook with python 2.7.12 and ipython==5.8.0 jupyter==1.0.0. Seems like a conflict due to a newer version of ipython.

/user/HS128/dh00601/.pyenv/versions/2.7.8/envs/testvenv/local/lib/python2.7/site-packages/fortranmagic.py:147: UserWarning: get_ipython_cache_dir has moved to the IPython.paths module since IPython 4.0.
  self._lib_dir = os.path.join(get_ipython_cache_dir(), 'fortran')

Javascript Error: $ is not defined

fortranmagic sometimes works, sometimes doesn't

I find that fortranmagic worked initially, but if I closed out of a file and reopened it, then it gave me this error upon running the code:

fortranmagic_error1

fortranmagic_error2

I'm running it in Python 3.5.4 in Jupyter Notebook 5.0.0 in Anaconda.

IPython warning

I get the following warning from up-to-date IPython:

[...]/lib/python3.6/site-packages/fortranmagic.py:147: UserWarning: get_ipython_cache_dir has moved to the IPython.paths module since IPython 4.0.
  self._lib_dir = os.path.join(get_ipython_cache_dir(), 'fortran')

External library and optimisation flags

I cannot give an external library link to the fortran magic.

%%fortran -L/path_to_lib/lib -lopenblas

UsageError: unrecognized arguments:

Also it would be nice to pass -03 to f2py

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.