예제 #1
0
파일: _tests.py 프로젝트: mrkwjc/ffnet
 def testExportWithDerivative(self):
     print(os.getcwd())
     exportnet(self.net, 'tmpffnet.f')
     ## THE BELOW IS PLATFORM AND ffnet.f FILE DEPENDENT
     ## SHOULD BE COMMENTED FOR RELEASES ???
     from numpy import f2py, array
     f = open('tmpffnet.f', 'r')
     source = f.read()
     f.close()
     f = open(ffnetpath + 'fortran/ffnet.f', 'r')
     source += f.read()
     f.close()
     import sys
     if sys.platform == 'win32':
         eargs = '--compiler=mingw32'
     else:
         eargs = ''
     if sys.version[0] == '3':
         source = bytes(source, "utf-8")
     f2py.compile(source,
                  modulename='tmpffnet',
                  extra_args=eargs,
                  verbose=0)
     import tmpffnet
     resA1 = tmpffnet.ffnet([1, 2, 3, 4, 5.])
     resB1 = tmpffnet.dffnet([1, 2, 3, 4, 5.])
     del tmpffnet
     resA = self.net([1, 2, 3, 4, 5.])
     resB = self.net.derivative([1, 2, 3, 4, 5.])
     for i in range(5):
         self.assertAlmostEqual(resA[i], resA1[i], 15)
         for j in range(5):
             self.assertAlmostEqual(resB[i][j], resB1[i][j], 15)
예제 #2
0
def compile_fortran_routine(fortran_likelihood_code, modname, template):
    "Used by compile_metropolis_sweep and compile_EP_sweep."

    def fortran_indent(s):
        return '\n'.join([' ' * 6 + l for l in s.splitlines()])

    # Instantiate the template with the likelihood code snippet.
    fortran_likelihood_code = fortran_likelihood_code.replace(
        '{X}', '(xp+M(i))')

    fortran_code = template.replace('{LIKELIHOOD_CODE}',
                                    fortran_indent(fortran_likelihood_code))
    lpf_hash = hashlib.sha1(fortran_code).hexdigest()

    # Compile the generated code and import it.
    try:
        exec('import %s_%s as %s' % (modname, lpf_hash, modname))
    except ImportError:
        for l in fortran_likelihood_code.splitlines():
            if len(l) > 72 - 6:
                raise RuntimeError, 'Line "%s" in your log-likelihood code snippet is too long, Fortran will hurl.' % l

        f2py.compile(fortran_code, modulename='%s_%s' % (modname, lpf_hash))
    exec('import %s_%s as %s' % (modname, lpf_hash, modname))

    # Store the generated code on the function and return it.
    exec('%s.code = fortran_code' % modname)
    exec('mod = %s' % modname)
    return mod
예제 #3
0
파일: _tests.py 프로젝트: mrkwjc/ffnet
 def testExportNoDerivative(self):
     exportnet(self.net, 'tmpffnet.f', derivative=False)
     ## THE BELOW IS PLATFORM AND ffnet.f FILE DEPENDENT
     ## SHOULD BE COMMENTED FOR RELEASES ???
     from numpy import f2py
     f = open('tmpffnet.f', 'r')
     source = f.read()
     f.close()
     f = open(ffnetpath + 'fortran/ffnet.f', 'r')
     source += f.read()
     f.close()
     import sys
     if sys.platform == 'win32':
         eargs = '--compiler=mingw32'
     else:
         eargs = ''
     if sys.version[0] == '3':
         source = bytes(source, "utf-8")
     f2py.compile(source,
                  modulename='tmpffnet2',
                  extra_args=eargs,
                  verbose=0)
     import tmpffnet2
     resA1 = tmpffnet2.ffnet([1, 2, 3, 4, 5.])
     resA = self.net([1, 2, 3, 4, 5.])
     for i in range(5):
         self.assertAlmostEqual(resA[i], resA1[i], 15)
     self.assertRaises(AttributeError,
                       lambda: tmpffnet2.dffnet([1, 2, 3, 4, 5.]))
예제 #4
0
파일: _tests.py 프로젝트: mrkwjc/ffnet
 def testExportWithDerivative(self):
     print os.getcwd()
     exportnet(self.net, 'tmpffnet.f')
     ## THE BELOW IS PLATFORM AND ffnet.f FILE DEPENDENT
     ## SHOULD BE COMMENTED FOR RELEASES ???
     from numpy import f2py, array
     f = open( 'tmpffnet.f', 'r' ); source = f.read(); f.close()
     f = open( ffnetpath + 'fortran/ffnet.f', 'r' ); source += f.read(); f.close()
     import sys
     if sys.platform == 'win32':
         eargs = '--compiler=mingw32'
     else: eargs = ''
     if sys.version[0] == '3':
         source = bytes(source, "utf-8")
     f2py.compile(source, modulename = 'tmpffnet', extra_args = eargs, verbose = 0)
     import tmpffnet
     resA1 = tmpffnet.ffnet( [ 1, 2, 3, 4, 5. ] )
     resB1 = tmpffnet.dffnet( [ 1, 2, 3, 4, 5. ] )
     del tmpffnet
     resA = self.net ( [ 1, 2, 3, 4, 5. ] )
     resB = self.net.derivative( [ 1, 2, 3, 4, 5. ] )
     for i in xrange(5):
         self.assertAlmostEqual(resA[i], resA1[i], 15)
         for j in xrange(5):
             self.assertAlmostEqual(resB[i][j], resB1[i][j], 15)
예제 #5
0
def compile_fortran_routine(fortran_likelihood_code, modname, template):
    "Used by compile_metropolis_sweep and compile_EP_sweep."
    def fortran_indent(s):
        return '\n'.join([' '*6+l for l in s.splitlines()])
    
    # Instantiate the template with the likelihood code snippet.
    fortran_likelihood_code = fortran_likelihood_code.replace('{X}','(xp+M(i))')
    
    fortran_code = template.replace('{LIKELIHOOD_CODE}', fortran_indent(fortran_likelihood_code))
    lpf_hash = hashlib.sha1(fortran_code).hexdigest()
    
    # Compile the generated code and import it.
    try:
        exec('import %s_%s as %s'%(modname, lpf_hash, modname))
    except ImportError:
        for l in fortran_likelihood_code.splitlines():
            if len(l)>72-6:
                raise RuntimeError, 'Line "%s" in your log-likelihood code snippet is too long, Fortran will hurl.'%l
                
        f2py.compile(fortran_code, modulename='%s_%s'%(modname,lpf_hash))
    exec('import %s_%s as %s'%(modname, lpf_hash, modname))

    # Store the generated code on the function and return it.
    exec('%s.code = fortran_code'%modname)
    exec('mod = %s'%modname)
    return mod
예제 #6
0
파일: temp.py 프로젝트: woodscn/Streamer
    def __init__(self,default_bounds,stl_bounds_file=None,num_faces=0):
        '''
        Initialize Bounds object.

        Args:
          default_bounds: Default_bounds is a description of a boundary surface.
            It may be superceded by other boundary conditions such as solid
            walls defined in an STL file. It is an object containing one 
            element for each Face.
          stl_bounds_file: Filename string of an ASCII .stl file describing any
            solid wall geometries present. Will eventually support the results 
            of an stl_read command (a list of arrays of nodes and faces).
          num_faces: Integer number of individual faces in the .stl file. Must
            be present if an STL file is given.
        Returns:
          self.left_face
          self.right_face
          self.top_face
          self.bottom_face
          self.back_face
          self.front_face
        Raises:
          STLError: There was an error reading the .stl file.
        '''
        # Read STL file, returning lists of triangulation vertices, indices of
        # the vertices associated with triangles, and the normal vectors of
        # those triangles.
        if stl_bounds_file:
            print " Warning: STL boundaries are not yet implemented."
            sysexit()
            num_nodes = num_faces*3
            [self.stl_nodes,self.stl_face_nodes,self.stl_face_normal,
             error]=stl.stla_read(stl_bounds_file,num_nodes,num_faces)
            if error:
                try:
                    str="STLError: stla_read failed in BoundaryConditions.__init__"
                    raise STLError(str)
                except STLError as e:
                    print e.msg
                    sysexit()

        # Isolate the parts of the boundary specification pertaining to each
        # Side and pass them on.
        self.left_face = Face('left',default_bounds.left_face)
        self.right_face = Face('right',default_bounds.right_face)
        self.bottom_face = Face('bottom',default_bounds.bottom_face)
        self.top_face = Face('top',default_bounds.top_face)
        self.back_face = Face('back',default_bounds.back_face)
        self.front_face = Face('front',default_bounds.front_face)
        fortran_normal_src = "! -*- f90 -*-\n"
        for face in self:
            for patch in face:
                try:
                    fortran_normal_src += patch.gradsrc
                except AttributeError: # Some patches don't have normal vectors
                    pass
        f2py.compile(fortran_normal_src,modulename='FortranNormalVectors',
                     verbose=False,source_fn='FortranNormalVectors.f90',
                     extra_args='--quiet')
예제 #7
0
파일: pspline.py 프로젝트: ezbc/class_work
def main():

    from scipy.weave import inline
    import numpy.f2py as f2py

    with open('Pspline.f', 'r') as f:
        code = f.read()

    #inline(code)
    f2py.compile(code, modulename='pspline')
예제 #8
0
def compile_f2py():
    """This function compiles the F2PY interface."""
    base_path = os.getcwd()
    os.chdir(PACKAGE_DIR)

    args = '--f90flags="-ffree-line-length-0 -O3"'
    src = open('replacements_f2py.f90', 'rb').read()
    f2py.compile(src, 'replacements_f2py', args, extension='.f90')

    os.chdir(base_path)
예제 #9
0
파일: pspline.py 프로젝트: ezbc/class_work
def main():

    import numpy.f2py as f2py

    with open('Pspline.f', 'r') as f:
        code = f.read()

    f2py.compile(code, modulename='pspline')

    import pspline

    help(pspline.pspline)
예제 #10
0
    def __install_disort(self) -> None:
        folder_name = 'disort4.0.99'
        module_name = 'disort'

        disort_source_dir = os.path.join(self.__project_path, folder_name)
        mods = [
            'BDREF.f', 'DISOBRDF.f', 'ERRPACK.f', 'LAPACK.f', 'LINPAK.f',
            'RDI1MACH.f'
        ]
        paths = [os.path.join(disort_source_dir, m) for m in mods]
        # I'm disgusted to say I'm adding a comment. I want to compile DISORT.f
        #  as a module, and I can do that by adding the other modules it needs
        #  in extra_args (this wasn't clear in f2py documentation).
        with open(os.path.join(disort_source_dir, 'DISORT.f')) as mod:
            f2py.compile(mod.read(), modulename=module_name, extra_args=paths)
예제 #11
0
def compile_radex(fcompiler='gfortran',f77exec=None):
    #r1 = os.system('f2py -h pyradex/radex/radex.pyf Radex/src/*.f --overwrite-signature > radex_build.log')
    pwd = os.getcwd()
    os.chdir('Radex/src/')
    files = glob.glob('*.f')
    include_path = '--include-paths {0}'.format(os.getcwd())
    f2py.run_main(' -h radex.pyf --overwrite-signature'.split()+include_path.split()+files)

    if f77exec is None:
        f77exec=''
    else:
        f77exec = '--f77exec=%s' % f77exec
    #cmd = '-m radex -c %s --fcompiler=%s %s' % (" ".join(files), fcompiler, f77exec)
    #f2py.run_main(['-m','radex','-c','--fcompiler={0}'.format(fcompiler), f77exec,] + files)
    source_list = []
    for fn in files:
        with open(fn, 'rb') as f:
            source_list.append(f.read())
    source = b"\n".join(source_list)
    include_path = '-I{0}'.format(os.getcwd())
    r2 = f2py.compile(source=source, modulename='radex',
                      extra_args='--fcompiler={0} {1} {2}'.format(fcompiler,
                                                                  f77exec,
                                                                  include_path),)
    os.chdir(pwd)
    if r2 != 0:
        raise SystemError("f2py failed with error %i" % r2)

    outfile = glob.glob("Radex/src/radex.*so")
    if len(outfile) != 1:
        print("outfile = {0}".format(outfile))
        raise OSError("Did not find the correct .so file(s)!  Compilation has failed.")
    sofile = outfile[0]
    r3 = shutil.move(sofile, 'pyradex/radex/radex.so')
예제 #12
0
    def ext_gridloop2_compile(self, fstr):
        if not isinstance(fstr, str):
            raise TypeError, \
            'fstr must be string expression, not', type(fstr)
        
        # generate Fortran source for gridloop2:
        source = """
      subroutine gridloop2(a, xcoor, ycoor, nx, ny)
      integer nx, ny
      real*8 a(nx,ny), xcoor(nx), ycoor(ny)
Cf2py intent(out) a
Cf2py depend(nx,ny) a

      integer i,j
      real*8 x, y
      do j = 1,ny
         y = ycoor(j)
         do i = 1,nx
            x = xcoor(i)
            a(i,j) = %s
         end do
      end do
      return
      end
""" % fstr        
        f2py_args = "--fcompiler=Gnu --build-dir tmp1"\
                    " -DF2PY_REPORT_ON_ARRAY_COPY=1"
        r = f2py.compile(source, modulename='ext_gridloop2',
                         extra_args=f2py_args, verbose=True,
                         source_fn='_cb.f')
        if r:
            print 'unsuccessful compilation'; sys.exit(1)
        import ext_gridloop2  # see if we can import successfully
예제 #13
0
def compile_radex(fcompiler="gfortran", f77exec=None):
    # r1 = os.system('f2py -h pyradex/radex/radex.pyf Radex/src/*.f --overwrite-signature > radex_build.log')
    pwd = os.getcwd()
    os.chdir("Radex/src/")
    files = glob.glob("*.f")
    include_path = "--include-paths {0}".format(os.getcwd())
    f2py.run_main(" -h radex.pyf --overwrite-signature".split() + include_path.split() + files)

    if f77exec is None:
        f77exec = ""
    else:
        f77exec = "--f77exec=%s" % f77exec
    # cmd = '-m radex -c %s --fcompiler=%s %s' % (" ".join(files), fcompiler, f77exec)
    # f2py.run_main(['-m','radex','-c','--fcompiler={0}'.format(fcompiler), f77exec,] + files)
    source_list = []
    for fn in files:
        with open(fn, "rb") as f:
            source_list.append(f.read())
    source = b"\n".join(source_list)
    include_path = "-I{0}".format(os.getcwd())
    r2 = f2py.compile(
        source=source, modulename="radex", extra_args="--fcompiler={0} {1} {2}".format(fcompiler, f77exec, include_path)
    )
    os.chdir(pwd)
    if r2 != 0:
        raise SystemError("f2py failed with error %i" % r2)

    r3 = shutil.move("Radex/src/radex.so", "pyradex/radex/radex.so")
예제 #14
0
def compile_radex(fcompiler='gfortran', f77exec=None):
    #r1 = os.system('f2py -h pyradex/radex/radex.pyf Radex/src/*.f --overwrite-signature > radex_build.log')
    pwd = os.getcwd()
    os.chdir('Radex/src/')
    files = glob.glob('*.f')
    include_path = '--include-paths {0}'.format(os.getcwd())
    f2py.run_main(' -h radex.pyf --overwrite-signature'.split() +
                  include_path.split() + files)

    if f77exec is None:
        f77exec = ''
    else:
        f77exec = '--f77exec=%s' % f77exec
    #cmd = '-m radex -c %s --fcompiler=%s %s' % (" ".join(files), fcompiler, f77exec)
    #f2py.run_main(['-m','radex','-c','--fcompiler={0}'.format(fcompiler), f77exec,] + files)
    source_list = []
    for fn in files:
        with open(fn, 'rb') as f:
            source_list.append(f.read())
    source = b"\n".join(source_list)
    include_path = '-I{0}'.format(os.getcwd())
    r2 = f2py.compile(
        source=source,
        modulename='radex',
        extra_args='--fcompiler={0} {1} {2}'.format(fcompiler, f77exec,
                                                    include_path),
    )
    os.chdir(pwd)
    if r2 != 0:
        raise SystemError("f2py failed with error %i" % r2)

    r3 = shutil.move('Radex/src/radex.so', 'pyradex/radex/radex.so')
예제 #15
0
def build(f2py_opts):
    try:
        import f77_ext_return_real
    except ImportError:
        assert not f2py2e.compile('''\
       function t0(value)
         real value
         real t0
         t0 = value
       end
       function t4(value)
         real*4 value
         real*4 t4
         t4 = value
       end
       function t8(value)
         real*8 value
         real*8 t8
         t8 = value
       end
       function td(value)
         double precision value
         double precision td
         td = value
       end

       subroutine s0(t0,value)
         real value
         real t0
cf2py    intent(out) t0
         t0 = value
       end
       subroutine s4(t4,value)
         real*4 value
         real*4 t4
cf2py    intent(out) t4
         t4 = value
       end
       subroutine s8(t8,value)
         real*8 value
         real*8 t8
cf2py    intent(out) t8
         t8 = value
       end
       subroutine sd(td,value)
         double precision value
         double precision td
cf2py    intent(out) td
         td = value
       end
''',
                                  'f77_ext_return_real',
                                  f2py_opts,
                                  source_fn='f77_ret_real.f')

    from f77_ext_return_real import t0, t4, t8, td, s0, s4, s8, sd
    test_functions = [t0, t4, t8, td, s0, s4, s8, sd]
    return test_functions
예제 #16
0
파일: _tests.py 프로젝트: cephdon/meta-core
 def testExportNoDerivative(self):
     exportnet(self.net, 'tmpffnet.f', derivative = False)
     ## THE BELOW IS PLATFORM AND ffnet.f FILE DEPENDENT 
     ## SHOULD BE COMMENTED FOR RELEASES ???
     from numpy import f2py
     f = open( 'tmpffnet.f', 'r' ); source = f.read(); f.close()
     f = open( ffnetpath + 'fortran/ffnet.f', 'r' ); source += f.read(); f.close()
     import sys
     if sys.platform == 'win32':
         eargs = '--compiler=mingw32'
     else: eargs = ''
     f2py.compile(source, modulename = 'tmpffnet2', extra_args = eargs, verbose = 0)
     import tmpffnet2
     resA1 = tmpffnet2.ffnet( [ 1, 2, 3, 4, 5. ] )
     resA = self.net ( [ 1, 2, 3, 4, 5. ] )
     for i in xrange(5):
         self.assertAlmostEqual(resA[i], resA1[i], 15)
     self.assertRaises(AttributeError, lambda: tmpffnet2.dffnet([ 1, 2, 3, 4, 5. ]))
예제 #17
0
    def import_selected_kind():
        """Tries to import the module which provides
        processor dependent kind values. If the module
        is not available it is compiled from a here-document
        and imported afterwards.

        Warning: creates both the source file and the
        compiled module in the current directory.

        """
        try:
            import f2py_selected_kind
        except:
            from numpy.f2py import compile
            # quick'n'dirty workaround for windoze
            if os.name == 'nt':
                f = open('f2py_selected_kind.f90', 'w')
                f.write(FCODE)
                f.close()
                from copy import deepcopy
                # save for later
                true_argv = deepcopy(sys.argv)
                sys.argv = (('%s -c --fcompiler=gnu95 --compiler=mingw32'
                             ' -m f2py_selected_kind'
                             ' f2py_selected_kind.f90') %
                            sys.executable).split()
                from numpy import f2py as f2py2e
                f2py2e.main()

                sys.argv = true_argv
            else:
                fcompiler = os.environ.get('F2PY_FCOMPILER', 'gfortran')
                compile(FCODE,
                        source_fn='f2py_selected_kind.f90',
                        modulename='f2py_selected_kind',
                        extra_args='--fcompiler=%s' % fcompiler)
            try:
                import f2py_selected_kind
            except Exception as e:
                raise Exception('Could not create selected_kind module\n' +
                                '%s\n' % os.path.abspath(os.curdir) +
                                '%s\n' % os.listdir('.') + '%s\n' % e)
        return f2py_selected_kind.kind
예제 #18
0
파일: __init__.py 프로젝트: jmlorenzi/kmos
    def import_selected_kind():
        """Tries to import the module which provides
        processor dependent kind values. If the module
        is not available it is compiled from a here-document
        and imported afterwards.

        Warning: creates both the source file and the
        compiled module in the current directory.

        """
        try:
            import f2py_selected_kind
        except:
            from numpy.f2py import compile
            # quick'n'dirty workaround for windoze
            if os.name == 'nt':
                f = open('f2py_selected_kind.f90', 'w')
                f.write(FCODE)
                f.close()
                from copy import deepcopy
                # save for later
                true_argv = deepcopy(sys.argv)
                sys.argv = (('%s -c --fcompiler=gnu95 --compiler=mingw32'
                             ' -m f2py_selected_kind'
                             ' f2py_selected_kind.f90')
                            % sys.executable).split()
                from numpy import f2py as f2py2e
                f2py2e.main()

                sys.argv = true_argv
            else:
                fcompiler = os.environ.get('F2PY_FCOMPILER', 'gfortran')
                compile(FCODE, source_fn='f2py_selected_kind.f90',
                        modulename='f2py_selected_kind',
                        extra_args='--fcompiler=%s' % fcompiler)
            try:
                import f2py_selected_kind
            except Exception as e:
                raise Exception('Could not create selected_kind module\n'
                                + '%s\n' % os.path.abspath(os.curdir)
                                + '%s\n' % os.listdir('.')
                                + '%s\n' % e)
        return f2py_selected_kind.kind
예제 #19
0
def build(f2py_opts):
    try:
        import f77_ext_return_real
    except ImportError:
        assert not f2py2e.compile('''\
       function t0(value)
         real value
         real t0
         t0 = value
       end
       function t4(value)
         real*4 value
         real*4 t4
         t4 = value
       end
       function t8(value)
         real*8 value
         real*8 t8
         t8 = value
       end
       function td(value)
         double precision value
         double precision td
         td = value
       end

       subroutine s0(t0,value)
         real value
         real t0
cf2py    intent(out) t0
         t0 = value
       end
       subroutine s4(t4,value)
         real*4 value
         real*4 t4
cf2py    intent(out) t4
         t4 = value
       end
       subroutine s8(t8,value)
         real*8 value
         real*8 t8
cf2py    intent(out) t8
         t8 = value
       end
       subroutine sd(td,value)
         double precision value
         double precision td
cf2py    intent(out) td
         td = value
       end
''','f77_ext_return_real',f2py_opts,source_fn='f77_ret_real.f')

    from f77_ext_return_real import t0,t4,t8,td,s0,s4,s8,sd
    test_functions = [t0,t4,t8,td,s0,s4,s8,sd]
    return test_functions
예제 #20
0
def generate_func(self, return_key='f', omit_assign=False, return_dim=None, return_intent='out'):
    """Generates a function from operator value and arguments"""

    global module_counter

    # function head
    func_dict = {}
    func = FortranGen()
    func.add_linebreak()
    func.add_indent()
    fname = self.short_name.lower()
    func.add_code_line(f"subroutine {fname}({return_key}")
    for arg in self._op_dict['arg_names']:
        if arg != return_key:
            func.add_code_line(f",{arg}")
    func.add_code_line(")")
    func.add_linebreak()

    # argument type definition
    for arg, name in zip(self._op_dict['args'], self._op_dict['arg_names']):
        if name != return_key:
            dtype = "integer" if "int" in str(arg.vtype) else "double precision"
            dim = f"dimension({','.join([str(s) for s in arg.shape])}), " if arg.shape else ""
            func.add_code_line(f"{dtype}, {dim}intent(in) :: {name}")
            func.add_linebreak()
    out_dim = f"({','.join([str(s) for s in return_dim])})" if return_dim else ""
    func.add_code_line(f"double precision, intent({return_intent}) :: {return_key}{out_dim}")
    func.add_linebreak()

    func.add_code_line(f"{self._op_dict['value']}" if omit_assign else f"{return_key} = {self._op_dict['value']}")
    func.add_linebreak()
    func.add_code_line("end")
    func.add_linebreak()
    func.remove_indent()
    module_counter += 1
    fn = f"pyrates_func_{module_counter}"
    f2py.compile(func.generate(), modulename=fn, extension=".f", verbose=False,
                 source_fn=f"{self.build_dir}/{fn}.f" if self.build_dir else f"{fn}.f")
    exec(f"from pyrates_func_{module_counter} import {fname}", globals())
    func_dict[self.short_name] = globals().pop(fname)
    return func_dict
예제 #21
0
    def ext_gridloop2_fcb_ptr_compile(self, fstr):
        if not isinstance(fstr, StringFunction):
            raise TypeError, \
            'fstr must be StringFunction, not %s', type(fstr)

        source = fstr.F77_code('fcb')
        f2py_args = "--fcompiler=Gnu --build-dir=tmp2"
        r = f2py.compile(source, modulename='callback',
                         extra_args=f2py_args, verbose=True,
                         source_fn='_cb.f')
        if r:
            print 'unsuccessful compilation'; sys.exit(1)
        import callback  # see if we can import successfully
예제 #22
0
    def ext_gridloop2_fcb_ptr_compile(self, fstr):
        if not isinstance(fstr, StringFunction):
            raise TypeError, \
            'fstr must be StringFunction, not %s', type(fstr)

        source = fstr.F77_code('fcb')
        f2py_args = "--fcompiler=Gnu --build-dir=tmp2"
        r = f2py.compile(source,
                         modulename='callback',
                         extra_args=f2py_args,
                         verbose=True,
                         source_fn='_cb.f')
        if r:
            print 'unsuccessful compilation'
            sys.exit(1)
        import callback  # see if we can import successfully
예제 #23
0
    def ext_gridloop2_fcb_compile(self, fstr):
        if not isinstance(fstr, str):
            raise TypeError, \
            'fstr must be string expression, not %s', type(fstr)

        # generate Fortran source
        source = """
      real*8 function fcb(x, y)
      real*8 x, y
      fcb = %s
      return
      end

      subroutine gridloop2_fcb(a, xcoor, ycoor, nx, ny)
      integer nx, ny
      real*8 a(nx,ny), xcoor(nx), ycoor(ny)
Cf2py intent(out) a
Cf2py intent(in) xcoor
Cf2py intent(in) ycoor
Cf2py depend(nx,ny) a
      real*8 fcb
      external fcb

      call gridloop2(a, xcoor, ycoor, nx, ny, fcb)
      return
      end
""" % fstr
        # compile callback code and link with ext_gridloop.so:
        f2py_args = "--fcompiler=Gnu --build-dir=tmp2"\
                    " -DF2PY_REPORT_ON_ARRAY_COPY=1 "\
                    " ./ext_gridloop.so"
        r = f2py.compile(source,
                         modulename='callback',
                         extra_args=f2py_args,
                         verbose=True,
                         source_fn='_cb.f')
        if r:
            print 'unsuccessful compilation'
            sys.exit(1)
        import callback  # see if we can import successfully
예제 #24
0
 def _compile(self):
     modulename = self._source_path.stem
     dir_path = str(Path(self._source_path).parent)
     suffix = self._source_path.suffix
     complie_result = f2py.compile(self.source,
                                   modulename=modulename,
                                   verbose=False,
                                   extra_args="--quiet",
                                   extension=suffix)
     if complie_result != 0:
         raise ImportError("complie failed")
     else:
         root = Path(dir_path).resolve()
         find_files = [
             i for i in root.iterdir() if i.match(f"{modulename}*.pyd")
             or i.match(f"{modulename}*.so")
         ]
         if len(find_files) != 1:
             raise ImportError(
                 f"find {len(find_files)} Dynamic Link Library")
         file = find_files[0]
         target_path = self._source_path.with_name(file.name)
         if file != target_path:
             try:
                 shutil.move(str(file), str(target_path))
             except shutil.SameFileError as sfe:
                 pass
             except Exception as e:
                 raise e
         del_target = [
             i for i in root.iterdir() if i.match(str(file) + ".*")
         ]
         for i in del_target:
             try:
                 i.chmod(0o777)
                 i.unlink()
             except Exception as e:
                 warnings.warn(f'can not delete file {i}:{type(e)}--{e}',
                               UserWarning)
         return target_path
예제 #25
0
    def ext_gridloop2_fcb_compile(self, fstr):
        if not isinstance(fstr, str):
            raise TypeError, \
            'fstr must be string expression, not %s', type(fstr)
        
        # generate Fortran source
        source = """
      real*8 function fcb(x, y)
      real*8 x, y
      fcb = %s
      return
      end

      subroutine gridloop2_fcb(a, xcoor, ycoor, nx, ny)
      integer nx, ny
      real*8 a(nx,ny), xcoor(nx), ycoor(ny)
Cf2py intent(out) a
Cf2py intent(in) xcoor
Cf2py intent(in) ycoor
Cf2py depend(nx,ny) a
      real*8 fcb
      external fcb

      call gridloop2(a, xcoor, ycoor, nx, ny, fcb)
      return
      end
""" % fstr
        # compile callback code and link with ext_gridloop.so:
        f2py_args = "--fcompiler=Gnu --build-dir=tmp2"\
                    " -DF2PY_REPORT_ON_ARRAY_COPY=1 "\
                    " ./ext_gridloop.so"
        r = f2py.compile(source, modulename='callback',
                         extra_args=f2py_args, verbose=True,
                         source_fn='_cb.f')
        if r:
            print 'unsuccessful compilation'; sys.exit(1)
        import callback  # see if we can import successfully
예제 #26
0
    def compileSourceCode(self):
        source = self.buildSourceCode()
        if source is None:
            return None

        if self.currentPreset in ["", None]:
            title = f"No preset defined. Create new preset by clicking add!"
            QMessageBox.critical(self, "No preset", f"<p>{title}</p>")
            return None

        print(">> SOURCE")
        print(source)
        modulename = f"module_{uuid.uuid4().hex}"

        result = f2py.compile(
            source,
            modulename=modulename,
            verbose=True,
            extension=".f90",
            source_fn=f"mod_{self.currentPreset}.f90",
        )
        if result != 0:
            title = f"Cannot compile Fortran code! Check console for output!"
            raise ValueError(title)

        m = importlib.import_module(modulename)

        def maskFn(x, y, z=0):
            mask = getattr(m, self.currentPreset).mask(float(x), float(y), float(z))
            return mask

        for p in glob.glob(f"{modulename}*.so"):
            os.remove(p)

        self.maskFunction = maskFn
        return True
예제 #27
0
    def ext_gridloop2_compile(self, fstr):
        if not isinstance(fstr, str):
            raise TypeError, \
            'fstr must be string expression, not', type(fstr)

        # generate Fortran source for gridloop2:
        source = """
      subroutine gridloop2(a, xcoor, ycoor, nx, ny)
      integer nx, ny
      real*8 a(nx,ny), xcoor(nx), ycoor(ny)
Cf2py intent(out) a
Cf2py depend(nx,ny) a

      integer i,j
      real*8 x, y
      do j = 1,ny
         y = ycoor(j)
         do i = 1,nx
            x = xcoor(i)
            a(i,j) = %s
         end do
      end do
      return
      end
""" % fstr
        f2py_args = "--fcompiler=Gnu --build-dir tmp1"\
                    " -DF2PY_REPORT_ON_ARRAY_COPY=1"
        r = f2py.compile(source,
                         modulename='ext_gridloop2',
                         extra_args=f2py_args,
                         verbose=True,
                         source_fn='_cb.f')
        if r:
            print 'unsuccessful compilation'
            sys.exit(1)
        import ext_gridloop2  # see if we can import successfully
예제 #28
0
          a2 = (-x + 0.5d0) * 0.25d0 / eps
          a3 = (-x + 0.375d0) * 0.5 / eps
          expa1 = 0.d0
          expa2 = 0.d0
          expa3 = 0.d0
          temp = max(a1, a2, a3)
          if ((a1-temp) .ge. -35.d0) expa1 = exp(a1-temp)
          if ((a2-temp) .ge. -35.d0) expa2 = exp(a2-temp)
          if ((a3-temp) .ge. -35.d0) expa3 = exp(a3-temp)

          u(1) = (0.1d0*expa1+0.5d0*expa2+expa3) / (expa1+expa2+expa3)
      return
      end
"""

f2py.compile(prob_def_f, modulename='problemdef', verbose=0)
"""
Part 2

Using the compiled callback routines to solve the problem.
"""

import bacoli_py
import numpy
import time
from problemdef import f, bndxa, bndxb, uinit

# Initialize the Solver object.
solver = bacoli_py.Solver()

# Specify the number of PDE's in this system.
예제 #29
0
from numpy import f2py

with open("wspro88.f") as sourcefile:
    sourcecode = sourcefile.read()
    
f2py.compile(sourcecode)
# import wspro
예제 #30
0
from numpy import f2py
with open("rungeadd.f") as sourcefile:
	sourcecode=sourcefile.read()
	f2py.compile(sourcecode,modulename='coefs')

예제 #31
0
파일: utils.py 프로젝트: lulzzz/kmos
    def import_selected_kind():
        """Tries to import the module which provides
        processor dependent kind values. If the module
        is not available it is compiled from a here-document
        and imported afterwards.

        Warning: creates both the source file and the
        compiled module in the current directory.

        """
        try:
            import f2py_selected_kind
        except:
            from numpy.f2py import compile
            fcode = """module kind
    implicit none
    contains
    subroutine real_kind(p, r, kind_value)
      integer, intent(in), optional :: p, r
      integer, intent(out) :: kind_value

      if(present(p).and.present(r)) then
        kind_value = selected_real_kind(p=p, r=r)
      else
        if (present(r)) then
          kind_value = selected_real_kind(r=r)
        else
          if (present(p)) then
            kind_value = selected_real_kind(p)
          endif
        endif
      endif
    end subroutine real_kind

    subroutine int_kind(p, r, kind_value)
      integer, intent(in), optional :: p, r
      integer, intent(out) :: kind_value

      if(present(p).and.present(r)) then
        kind_value = selected_int_kind(p)
      else
        if (present(r)) then
          kind_value = selected_int_kind(r=r)
        else
          if (present(p)) then
            kind_value = selected_int_kind(p)
          endif
        endif
      endif
    end subroutine int_kind

    end module kind
            """
            # quick'n'dirty workaround for windoze
            if os.name == 'nt':
                with open('f2py_selected_kind.f90', 'w') as f:
                    f.write(fcode)
                from copy import deepcopy
                # save for later
                true_argv = deepcopy(sys.argv)
                sys.argv = ('%s -c --fcompiler=gnu95 --compiler=mingw32 -m f2py_selected_kind f2py_selected_kind.f90' % sys.executable).split()
                from numpy import f2py as f2py2e
                f2py2e.main()

                sys.argv = true_argv
            else:
                compile(fcode, source_fn='f2py_selected_kind.f90',
                        modulename='f2py_selected_kind')
            try:
                import f2py_selected_kind
            except:
                print(os.path.abspath(os.curdir))
                print(os.listdir('.'))
                raise
        return f2py_selected_kind.kind
예제 #32
0
    def eval(self, x, globals=None, locals=None):
        """
        EXAMPLES::

            sage: from sage.misc.inline_fortran import InlineFortran, _example
            sage: fortran = InlineFortran(globals())
            sage: fortran(_example)
            sage: import numpy
            sage: n = numpy.array(range(10),dtype=float)
            sage: fib(n,int(10))
            sage: n
            array([  0.,   1.,   1.,   2.,   3.,   5.,   8.,  13.,  21.,  34.])

        TESTS::

            sage: os.chdir(SAGE_ROOT)
            sage: fortran.eval("SYNTAX ERROR !@#$")
            Traceback (most recent call last):
            ...
            RuntimeError: failed to compile Fortran code:...
            sage: os.getcwd() == SAGE_ROOT
            True
        """
        if len(x.splitlines()) == 1 and os.path.exists(x):
            filename = x
            x = open(x).read()
            if filename.lower().endswith('.f90'):
                x = '!f90\n' + x

        from numpy import f2py

        # Create everything in a temporary directory
        mytmpdir = tmp_dir()

        try:
            old_cwd = os.getcwd()
            os.chdir(mytmpdir)

            old_import_path = os.sys.path
            os.sys.path.append(mytmpdir)

            name = "fortran_module"  # Python module name
            # if the first line has !f90 as a comment, gfortran will
            # treat it as Fortran 90 code
            if x.startswith('!f90'):
                fortran_file = name + '.f90'
            else:
                fortran_file = name + '.f'

            s_lib_path = ""
            s_lib = ""
            for s in self.library_paths:
                s_lib_path = s_lib_path + "-L%s "

            for s in self.libraries:
                s_lib = s_lib + "-l%s " % s

            log = name + ".log"
            extra_args = '--quiet --f77exec=sage-inline-fortran --f90exec=sage-inline-fortran %s %s >"%s" 2>&1' % (
                s_lib_path, s_lib, log)

            f2py.compile(x,
                         name,
                         extra_args=extra_args,
                         source_fn=fortran_file)
            log_string = open(log).read()

            # f2py.compile() doesn't raise any exception if it fails.
            # So we manually check whether the compiled file exists.
            # NOTE: the .so extension is used expect on Cygwin,
            # that is even on OS X where .dylib might be expected.
            soname = name
            uname = os.uname()[0].lower()
            if uname[:6] == "cygwin":
                soname += '.dll'
            else:
                soname += '.so'
            if not os.path.isfile(soname):
                raise RuntimeError("failed to compile Fortran code:\n" +
                                   log_string)

            if self.verbose:
                print(log_string)

            m = __builtin__.__import__(name)
        finally:
            os.sys.path = old_import_path
            os.chdir(old_cwd)
            try:
                import shutil
                shutil.rmtree(mytmpdir)
            except OSError:
                # This can fail for example over NFS
                pass

        for k, x in m.__dict__.iteritems():
            if k[0] != '_':
                self.globals[k] = x
예제 #33
0
def build(f2py_opts):
    try:
        import f77_ext_return_integer
    except ImportError:
        assert not f2py2e.compile('''\
       function t0(value)
         integer value
         integer t0
         t0 = value
       end
       function t1(value)
         integer*1 value
         integer*1 t1
         t1 = value
       end
       function t2(value)
         integer*2 value
         integer*2 t2
         t2 = value
       end
       function t4(value)
         integer*4 value
         integer*4 t4
         t4 = value
       end
       function t8(value)
         integer*8 value
         integer*8 t8
         t8 = value
       end

       subroutine s0(t0,value)
         integer value
         integer t0
cf2py    intent(out) t0
         t0 = value
       end
       subroutine s1(t1,value)
         integer*1 value
         integer*1 t1
cf2py    intent(out) t1
         t1 = value
       end
       subroutine s2(t2,value)
         integer*2 value
         integer*2 t2
cf2py    intent(out) t2
         t2 = value
       end
       subroutine s4(t4,value)
         integer*4 value
         integer*4 t4
cf2py    intent(out) t4
         t4 = value
       end
       subroutine s8(t8,value)
         integer*8 value
         integer*8 t8
cf2py    intent(out) t8
         t8 = value
       end

''','f77_ext_return_integer',f2py_opts,source_fn='f77_ret_int.f')

    from f77_ext_return_integer import t0,t1,t2,t4,t8,s0,s1,s2,s4,s8
    test_functions = [t0,t1,t2,t4,t8,s0,s1,s2,s4,s8]
    return test_functions
예제 #34
0
    def __init__(self, varlist, grid, outDim='xy',
                 suffix='xy', path='.',
                 output=False):
        """

        :type varlist: list
        :param varlist:
        :type grid: planetHydro.parseData.gridReader.gridReader
        :param grid:
        :type outDim: int
        :param outDim:
        :type suffix: str
        :param suffix:
        :type path: str
        :param path:
        :type output: bool
        :param output:
        """
        self.grid = grid
        if (outDim == 'xy'):
            self.ndims = 2
            self.gridsig = (['x', 'y'], 'nxtot, nytot')
            self.nztot = 1
            self.shape = self.nxtot, self.nytot = grid.nxtot, grid.nytot + 1
        elif (outDim == 'rphi'):
            self.ndims = 2
            self.gridsig = (['x', 'y'], 'nxtot, nytot')
            self.nztot = 1
            self.shape = self.nxtot, self.nytot = grid.nxtot, grid.nytot
        elif (outDim == 'xz') | (outDim == 'rz'):
            self.ndims = 2
            self.gridsig = (['x', 'y'], 'nxtot, nytot')
            self.nztot = 1
            self.shape = self.nxtot, self.nytot = grid.nxtot, grid.nztot
        elif (outDim == 'xyz') | (outDim == '3D'):
            self.ndims = 3
            self.gridsig = (['x', 'y', 'z'], 'nxtot, nytot, nztot')
            self.shape = self.nxtot, self.nytot, self.nztot = grid.nxtot, grid.nytot + 1, grid.nztot
        else:
            assert False, "Error: {0} is not a valid output dimension".format(outDim)

        self.varlist = varlist
        self.suffix = suffix + '.dat'
        self.varstring = ','.join(varlist)
        self.fortranvarlist = (',\n' + self.nxt + ' ').join(self.gridsig[0] + varlist)
        self.path = path

        self.source = self.genSource()
        if output:
            with open(path + "/tecout" + suffix + ".f", "w") as txt_file:
                txt_file.write(self.source)

        try:
            import os

            os.remove(path + '/tecout' + suffix + '.so')
        except OSError:
            print "No previous output lib detected."
            pass

        # paths set for M10
        self.modulename = 'tecout' + suffix
        f2py.compile(self.source, modulename=self.modulename,
                     extra_args='-I/data/programs/local/src/tecio-wrap/ ' + \
                                '--f90exec=/opt/intel/composer_xe_2011_sp1.8.273/bin/intel64/ifort ' + \
                                '-L/data/programs/local/lib/ -ltecio -lstdc++')
예제 #35
0
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Mar  6 10:32:17 2019
Modified by Rohit Goswami (HaoZeke) <*****@*****.**>

@author: mhumbert
"""

from numpy import f2py
import os, glob

os.chdir('src')

f = open('calcdistances.f90', 'r').read()
f2py.compile(f,
             modulename='calcdistances',
             source_fn='calcdistances.f90',
             verbose=False)
f = open('calcCOM.f90', 'r').read()
f2py.compile(f, modulename='calccomf', source_fn='calcCOM.f90', verbose=False)
f = open('ipcorr.f90', 'r').read()
f2py.compile(f, modulename='ipcorr', source_fn='ipcorr.f90', verbose=False)

os.symlink(glob.glob('ipcorr.*.so')[0], 'ipcorr.so')
os.symlink(glob.glob('calcdistances.*.so')[0], 'calcdistances.so')
os.symlink(glob.glob('calccomf.*.so')[0], 'calccomf.so')

os.chdir('..')
예제 #36
0
"""

import sys
try:
    n_points = int(sys.argv[1])    # Read from input 
except:
    n_points = 200   # default number of time-steps    

t0, tn, u0 = 1., 6.,  1.0
time_points = np.linspace(t0, tn, n_points)
atol, rtol, ng = 1e-8, 1e-8, 2
ng = 2     # number of constraint functions in g

# Compile these Fortran subroutines
from numpy import f2py
f2py.compile(f_str+'\n'+g_str, modulename='callback', verbose=False)   
import callback
f_f77, g_f77 = callback.f_f77, callback.g_f77

st.figure()
method = Lsodar
# Test case: Lsodar, with f & g 
m = method(None, f_f77=f_f77, rtol=rtol, atol=atol, g_f77=g_f77, ng=ng)
m.set_initial_condition(u0)
u,t = m.solve(time_points)
st.plot(t, u, 'o', 
        title="Lsodar with Fortran subroutines",
        legend="with f & g", hold="on")

# Exact solution:  u(t) = exp(-t**2+5*t-4)
st.plot(t, u_solution(time_points), '-', 
예제 #37
0
    def compile(self, build_dir: Optional[str] = None, decorator: Optional[Callable] = None, **kwargs) -> tuple:
        """Compile the graph layers/operations. Creates python files containing the functions in each layer.

        Parameters
        ----------
        build_dir
            Directory in which to create the file structure for the simulation.
        decorator
            Decorator function that should be applied to the right-hand side evaluation function.
        kwargs
            decorator keyword arguments

        Returns
        -------
        tuple
            Contains tuples of layer run functions and their respective arguments.

        """

        # preparations
        ##############

        # remove empty layers and operators
        new_layer_idx = 0
        for layer_idx, layer in enumerate(self.layers.copy()):
            for op in layer.copy():
                if op is None:
                    layer.pop(layer.index(op))
            if len(layer) == 0:
                self.layers.pop(new_layer_idx)
            else:
                new_layer_idx += 1

        # remove previously imported rhs_funcs from system
        if 'rhs_func' in sys.modules:
            del sys.modules['rhs_func']

        # collect state variable and parameter vectors
        state_vars, params, var_map = self._process_vars()

        # update state variable getter operations to include the full state variable vector as first argument
        y = self.get_var('y')
        for key, (vtype, idx) in var_map.items():
            var = self.get_var(key)
            if vtype == 'state_var' and var.short_name != 'y':
                var.args[0] = y
                var.build_op(var.args)

        # create rhs evaluation function
        ################################

        # set up file header
        func_gen = FortranGen()
        for import_line in self._imports:
            func_gen.add_code_line(import_line)
            func_gen.add_linebreak()
        func_gen.add_linebreak()

        # define function head
        func_gen.add_indent()
        if self.pyauto_compat:
            func_gen.add_code_line("subroutine func(ndim,y,icp,args,ijac,y_delta,dfdu,dfdp)")
            func_gen.add_linebreak()
            func_gen.add_code_line("implicit none")
            func_gen.add_linebreak()
            func_gen.add_code_line("integer, intent(in) :: ndim, icp(*), ijac")
            func_gen.add_linebreak()
            func_gen.add_code_line("double precision, intent(in) :: y(ndim), args(*)")
            func_gen.add_linebreak()
            func_gen.add_code_line("double precision, intent(out) :: y_delta(ndim)")
            func_gen.add_linebreak()
            func_gen.add_code_line("double precision, intent(inout) :: dfdu(ndim,ndim), dfdp(ndim,*)")
            func_gen.add_linebreak()
        else:
            func_gen.add_code_line("subroutine func(ndim,t,y,args,y_delta)")
            func_gen.add_linebreak()
            func_gen.add_code_line("implicit none")
            func_gen.add_linebreak()
            func_gen.add_code_line("integer, intent(in) :: ndim")
            func_gen.add_linebreak()
            func_gen.add_code_line("double precision, intent(in) :: t, y(ndim)")
            func_gen.add_linebreak()
            func_gen.add_code_line("double precision, intent(in) :: args(*)")
            func_gen.add_linebreak()
            func_gen.add_code_line("double precision, intent(out) :: y_delta(ndim)")
            func_gen.add_linebreak()

        # declare variable types
        func_gen.add_code_line("double precision ")
        for key in var_map:
            var = self.get_var(key)
            if "float" in str(var.dtype) and var.short_name != 'y_delta':
                func_gen.add_code_line(f"{var.short_name},")
        if "," in func_gen.code[-1]:
            func_gen.code[-1] = func_gen.code[-1][:-1]
        else:
            func_gen.code.pop(-1)
        func_gen.add_linebreak()
        func_gen.add_code_line("integer ")
        for key in var_map:
            var = self.get_var(key)
            if "int" in str(var.dtype):
                func_gen.add_code_line(f"{var.short_name},")
        if "," in func_gen.code[-1]:
            func_gen.code[-1] = func_gen.code[-1][:-1]
        else:
            func_gen.code.pop(-1)
        func_gen.add_linebreak()

        # declare constants
        args = [None for _ in range(len(params))]
        func_gen.add_code_line("! declare constants")
        func_gen.add_linebreak()
        updates, indices = [], []
        i = 0
        for key, (vtype, idx) in var_map.items():
            if vtype == 'constant':
                var = params[idx-self.idx_start][1]
                if var.short_name != 'y_delta':
                    func_gen.add_code_line(f"{var.short_name} = args({idx})")
                    func_gen.add_linebreak()
                    args[idx-1] = var
                    updates.append(f"{var.short_name}")
                    indices.append(i)
                    i += 1
        func_gen.add_linebreak()

        # extract state variables from input vector y
        func_gen.add_code_line("! extract state variables from input vector")
        func_gen.add_linebreak()
        for key, (vtype, idx) in var_map.items():
            var = self.get_var(key)
            if vtype == 'state_var':
                func_gen.add_code_line(f"{var.short_name} = {var.value}")
                func_gen.add_linebreak()
        func_gen.add_linebreak()

        # add equations
        func_gen.add_code_line("! calculate right-hand side update of equation system")
        func_gen.add_linebreak()
        arg_updates = []
        for i, layer in enumerate(self.layers):
            for j, op in enumerate(layer):
                lhs = op.value.split("=")[0]
                lhs = lhs.replace(" ", "")
                find_arg = [arg == lhs for arg in updates]
                if any(find_arg):
                    idx = find_arg.index(True)
                    arg_updates.append((updates[idx], indices[idx]))
                func_gen.add_code_line(op.value)
                func_gen.add_linebreak()
        func_gen.add_linebreak()

        # update parameters where necessary
        # func_gen.add_code_line("! update system parameters")
        # func_gen.add_linebreak()
        # for upd, idx in arg_updates:
        #     update_str = f"args{self.idx_l}{idx}{self.idx_r} = {upd}"
        #     if f"    {update_str}" not in func_gen.code:
        #         func_gen.add_code_line(update_str)
        #         func_gen.add_linebreak()

        # end function
        func_gen.add_code_line(f"end subroutine func")
        func_gen.add_linebreak()
        func_gen.remove_indent()

        # save rhs function to file
        fname = f'{self._build_dir}/rhs_func'
        f2py.compile(func_gen.generate(), modulename='rhs_func', extension='.f', source_fn=f'{fname}.f', verbose=False)

        # create additional subroutines in pyauto compatibility mode
        gen_def = kwargs.pop('generate_auto_def', True)
        if self.pyauto_compat and gen_def:
            self.generate_auto_def(self._build_dir)

        # import function from file
        fname_import = fname.replace('/', '.')
        exec(f"from rhs_func import rhs_eval", globals())
        rhs_eval = globals().pop('func')

        # apply function decorator
        if decorator:
            rhs_eval = decorator(rhs_eval, **kwargs)

        return rhs_eval, args, state_vars, var_map
예제 #38
0
import os
# os.environ["CC"] = "/usr/bin/gfortran"
# os.environ["CXX"] = "/usr/bin/gfortran"

# Using post-0.2.2 scipy_distutils to display fortran compilers
from numpy.distutils.fcompiler import new_fcompiler
compiler = new_fcompiler() # or new_fcompiler(compiler='intel')
compiler.dump_properties()

#Generate add.f wrapper
from numpy import f2py
with open("add.f90") as sourcefile:
    sourcecode = sourcefile.read()
    print 'Fortran code'
    print sourcecode

f2py.compile(sourcecode, modulename='add')
# f2py.compile(sourcecode, modulename='add', extra_args = '--fcompiler=/usr/bin/gfortran')
# f2py.compile(sourcecode, modulename='add')
# f2py -c --help-fcompiler
import add
print 'eso'
예제 #39
0
from numpy import f2py
fsource = '''
       subroutine sumarray(A, N)
       REAL, DIMENSION(N) :: A
       INTEGER :: N
       RES = 0.1 * SUM(A, MASK = A .GT. 0)
       RES2 = -0.025 * SUM(A, MASK = A .LT. 0)
       print*, RES + RES2
       end 
 '''
f2py.compile(fsource,modulename='fort_sum',verbose=0)
예제 #40
0
파일: compile.py 프로젝트: mrkwjc/ffnet
from numpy import f2py
import os

files = os.listdir('.')
for file in files:
    name, ext = os.path.splitext(file)
    if ext == '.f':
        print "Compiling file %s." %file
        f2py.compile(open(file, 'r').read(), '_' + name)
예제 #41
0
파일: model.py 프로젝트: ehermes/micki
    def setup_execs(self):
        from micki.fortran import f90_template, pyf_template
        from numpy import f2py

        # y_vec is an array symbol that will represent the species
        # concentrations provided by the differential equation solver inside
        # the Fortran code (that is, y_vec is an INPUT to the functions that
        # calculate the residual, Jacobian, and rate)
        y_vec = sym.IndexedBase('yin', shape=(self.nvariables,))
        # Map y_vec elements (1-indexed, of course) onto 'modelparam' symbols
        trans = {self.symbols[i]: y_vec[i + 1] for i in range(self.nvariables)}
        # Map string represntation of 'modelparam' symbols onto string
        # representation of y-vec elements
        str_trans = {}
        for i in range(self.nvariables):
            str_trans[sym.fcode(self.symbols[i], source_format='free')] = \
                    sym.fcode(y_vec[i + 1], source_format='free')
        
        str_list = [key for key in str_trans]
        str_list.sort(key=len, reverse=True)

        # these will contain lists of strings, with each element being one
        # Fortran assignment for the master equation, Jacobian, and
        # rate expressions
        rescode = []
        jaccode = []
        ratecode = []

        # Convert symbolic master equation into a valid Fortran string
        for i in range(self.nvariables):
            fcode = sym.fcode(self.f_sym[i], source_format='free')
            # Replace modelparam symbols with their y_vec counterpart
            for key in str_list:
                fcode = fcode.replace(key, str_trans[key])
            # Create actual line of code for calculating residual
            rescode.append('   res({}) = '.format(i + 1) + fcode)

        # Effectively the same as above, except on the two-dimensional Jacobian
        # matrix.
        for i in range(self.nvariables):
            for j in range(self.nvariables):
                expr = self.jac_sym[j, i]
                # Unlike the residual, some elements of the Jacobian can be 0.
                # We don't need to bother writing 'jac(x,y) = 0' a hundred
                # times in Fortran, so we omit those.
                if expr != 0:
                    fcode = sym.fcode(expr, source_format='free')
                    for key in str_list:
                        fcode = fcode.replace(key, str_trans[key])
                    jaccode.append('   jac({}, {}) = '.format(j + 1, i + 1) +
                                   fcode)

        # See residual above
        for i, rate in enumerate(self.rates):
            fcode = sym.fcode(rate, source_format='free')
            for key in str_list:
                fcode = fcode.replace(key, str_trans[key])
            ratecode.append('   rates({}) = '.format(i + 1) + fcode)

        # We insert all of the parameters of this differential equation into
        # the prewritten Fortran template, including the residual, Jacobian,
        # and rate expressions we just calculated.
        program = f90_template.format(neq=self.nvariables, nx=1,
                                      nrates=len(self.rates),
                                      rescalc='\n'.join(rescode),
                                      jaccalc='\n'.join(jaccode),
                                      ratecalc='\n'.join(ratecode))

        # Generate a randomly-named temp directory for compiling the module.
        # We will name the actual module file after the directory.
        dname = tempfile.mkdtemp()
        modname = os.path.split(dname)[1]
        fname = modname + '.f90'
        pyfname = modname + '.pyf'

        # For debugging purposes, write out the generated module
        with open('solve_ida.f90', 'w') as f:
            f.write(program)

        # Write the pertinent data into the temp directory
        with open(os.path.join(dname, pyfname), 'w') as f:
            f.write(pyf_template.format(modname=modname, neq=self.nvariables,
                    nrates=len(self.rates)))

        # Compile the module with f2py
        f2py.compile(program, modulename=modname,
                     extra_args='--quiet '
                                '--f90flags="-Wno-unused-dummy-argument '
                                '-Wno-unused-variable -w -fopenmp" ' 
                                '-lsundials_fcvode '
                                '-lsundials_cvode -lsundials_fnvecopenmp '
                                '-lsundials_nvecopenmp -lopenblas_openmp -lgomp ' +
                                os.path.join(dname, pyfname),
                     source_fn=os.path.join(dname, fname), verbose=0)

        # Delete the temporary directory
        shutil.rmtree(dname)

        # Import the module on-the-fly with __import__. This is kind of a hack.
        solve_ida = __import__(modname)

        # The Fortran module's initialize, solve, and finalize routines
        # are mapped onto finitialize, fsolve, and ffinalize inside the Model
        # object. We don't want users touching these manually
        self.finitialize = solve_ida.initialize
        self.ffind_steady_state = solve_ida.find_steady_state
        self.fsolve = solve_ida.solve
        self.ffinalize = solve_ida.finalize

        # Delete the module file. We've already imported it, so it's in memory.
        os.remove(modname + '.so')
예제 #42
0
    def eval(self, x, globals=None, locals=None):
        """
        EXAMPLES::
        
            sage: from sage.misc.inline_fortran import InlineFortran, _example
            sage: fortran = InlineFortran(globals())
            sage: fortran(_example)
            sage: import numpy
            sage: n = numpy.array(range(10),dtype=float)
            sage: fib(n,int(10))
            sage: n
            array([  0.,   1.,   1.,   2.,   3.,   5.,   8.,  13.,  21.,  34.])

        TESTS::

            sage: os.chdir(SAGE_ROOT)
            sage: fortran.eval("SYNTAX ERROR !@#$")
            Traceback (most recent call last):
            ...
            RuntimeError: failed to compile Fortran code:...
            sage: os.getcwd() == SAGE_ROOT
            True
        """
        if len(x.splitlines()) == 1 and os.path.exists(x):
            filename = x
            x = open(x).read()
            if filename.lower().endswith('.f90'):
                x = '!f90\n' + x

        from numpy import f2py

        # Create everything in a temporary directory
        mytmpdir = tmp_dir()

        try:
            old_cwd = os.getcwd()
            os.chdir(mytmpdir)

            old_import_path = os.sys.path
            os.sys.path.append(mytmpdir)
    
            name = "fortran_module"  # Python module name
            # if the first line has !f90 as a comment, gfortran will
            # treat it as Fortran 90 code
            if x.startswith('!f90'):
                fortran_file = name + '.f90'
            else:
                fortran_file = name + '.f'
    
            s_lib_path = ""
            s_lib = ""
            for s in self.library_paths:
                s_lib_path = s_lib_path + "-L%s "
    
            for s in self.libraries:
                s_lib = s_lib + "-l%s "%s
    
            log = name + ".log"
            extra_args = '--quiet --f77exec=sage-inline-fortran --f90exec=sage-inline-fortran %s %s >"%s" 2>&1'%(
                s_lib_path, s_lib, log)
    
            f2py.compile(x, name, extra_args = extra_args, source_fn=fortran_file)
            log_string = open(log).read()
    
            # f2py.compile() doesn't raise any exception if it fails.
            # So we manually check whether the compiled file exists.
            # NOTE: the .so extension is used, even on OS X where .dylib
            # might be expected.
            soname = name + '.so'
            if not os.path.isfile(soname):
                raise RuntimeError("failed to compile Fortran code:\n" + log_string)
    
            if self.verbose:
                print log_string
            
            m = __builtin__.__import__(name)
        finally:
            os.sys.path = old_import_path
            os.chdir(old_cwd)
            try:
                import shutil
                shutil.rmtree(mytmpdir)
            except OSError:
                # This can fail for example over NFS
                pass
        
        for k, x in m.__dict__.iteritems():
            if k[0] != '_':
                self.globals[k] = x
예제 #43
0
def compile_fortran_module(filename, module, source=None):
    if source is None:
        source = open(filename, 'r').read()
    if f2py.compile(source=source, modulename=module,
                    source_fn=filename):
        raise RuntimeError('compile failed, see console')
예제 #44
0
"""

import sys
try:
    n_points = int(sys.argv[1])    # Read from input 
except:
    n_points = 10   # default number of time-steps    

t0, tn, u0 = 0., 10.,  [2.,0.]
time_points = np.linspace(t0, tn, n_points)
atol, rtol = 1e-4, 1e-4

# Compile these Fortran subroutines
string_to_compile = '\n'.join([f_str, jac_full_str])
from numpy import f2py
f2py.compile(string_to_compile, modulename='callback', verbose=False)   
import callback
f_f77, jac_f77 = callback.f_f77, callback.jac_f77


st.figure()
method = Lsode

# Test case 1: Lsode, with f & jac
m = method(None, f_f77=f_f77, rtol=rtol, atol=atol, jac_f77=jac_f77)
m.set_initial_condition(u0)
u,t = m.solve(time_points)
st.plot(t, u[:,0], '-', title="Lsode with Fortran subroutines", 
        legend="with f & jac_full", hold="on")

# Test case 2: Lsode, with f
예제 #45
0
      integer i
      do 10 i = 1,9
        mas(1,i) = 1./6.
        mas(2,i) = 4./6.
   10   mas(3,i) = 1./6.
      mas(1,1) = 0.
      mas(3,9) = 0.
      return
      end
"""

# compile these Fortran subroutines

string_to_compile = '\n'.join([f_str, jac_str, mas_str])
from numpy import f2py
f2py.compile(string_to_compile, modulename = "tmp_callback", verbose=False)
import tmp_callback
f_f77, mas_f77, jac_f77_radau5 = \
    tmp_callback.f_f77, tmp_callback.mas_f77, tmp_callback.jac_f77_radau5

u0 = np.zeros(9, float)
u0[1], u0[2:5], u0[5] = .5, 1., .5

t0, tn, n_points, ml, mu, mlmas, mumas = 0., .4, 50, 1, 1, 1, 1
time_points = np.linspace(t0, tn, n_points)
atol, rtol = 1e-3, 1e-3

exact_final = [1.07001457e-1, 2.77432492e-1, 5.02444616e-1, 7.21037157e-1,
               9.01670441e-1, 8.88832048e-1, 4.96572850e-1, 9.46924362e-2,
               -6.90855199e-3]
st.figure()
예제 #46
0
      spcrad_f77 = 4d0*((nx+1)**2 + (ny+1)**2 + (nz+1)**2)
      return
      end

"""

import sys
try:
    n_points = int(sys.argv[1])  # Read from input
except:
    n_points = 20  # default number of time-steps

# Compile these Fortran subroutines
string_to_compile = '\n'.join([f_str, spcrad_str])
from numpy import f2py
f2py.compile(string_to_compile, modulename='callback', verbose=False)
import callback
f_f77, spcrad_f77 = callback.f_f77, callback.spcrad_f77

t0, tn = 0., .7
u0 = np.zeros(6859, float)
for i in range(19):
    for j in range(19):
        for k in range(19):
            index = i + j * 19 + k * 19 * 19
            u0[index] = np.tanh(5.0*((i+1)*.05 + (j+1)*.1 + \
                                (k+1)*.075 - .5))
time_points = np.linspace(t0, tn, n_points)
atol, rtol = 1e-4, 1e-4
jac_constant = 1
예제 #47
0
    def generate_auto_def(self, directory):
        """

        Parameters
        ----------
        directory

        Returns
        -------

        """

        if not self.pyauto_compat:
            raise ValueError('This method can only be called in pyauto compatible mode. Please set `pyauto_compat` to '
                             'True upon calling the `CircuitIR.compile` method.')

        # read file
        ###########

        try:

            # read file from excisting system compilation
            if not directory:
                directory = self._build_dir
            fn = f"{directory}/rhs_func.f" if "rhs_func.f" not in directory else directory
            with open(fn, 'rt') as f:
                func_str = f.read()

        except FileNotFoundError:

            # compile system and then read the build files
            self.compile(build_dir=directory, generate_auto_def=False)
            fn = f"{self._build_dir}/rhs_func.f"
            with open(fn, 'r') as f:
                func_str = f.read()

        end_str = "end subroutine func\n"
        idx = func_str.index(end_str)
        func_str = func_str[:idx+len(end_str)]

        # generate additional subroutines
        #################################

        func_gen = FortranGen()

        # generate subroutine header
        func_gen.add_linebreak()
        func_gen.add_indent()
        func_gen.add_code_line("subroutine stpnt(ndim, y, args, t)")
        func_gen.add_linebreak()
        func_gen.add_code_line("implicit None")
        func_gen.add_linebreak()
        func_gen.add_code_line("integer, intent(in) :: ndim")
        func_gen.add_linebreak()
        func_gen.add_code_line("double precision, intent(inout) :: y(ndim), args(*)")
        func_gen.add_linebreak()
        func_gen.add_code_line("double precision, intent(in) :: T")
        func_gen.add_linebreak()

        # declare variable types
        func_gen.add_code_line("double precision ")
        for key in self.vars:
            var = self.get_var(key)
            name = var.short_name
            if "float" in str(var.dtype) and name != 'y_delta' and name != 'y' and name != 't':
                func_gen.add_code_line(f"{var.short_name},")
        if "," in func_gen.code[-1]:
            func_gen.code[-1] = func_gen.code[-1][:-1]
        else:
            func_gen.code.pop(-1)
        func_gen.add_linebreak()
        func_gen.add_code_line("integer ")
        for key in self.vars:
            var = self.get_var(key)
            if "int" in str(var.dtype):
                func_gen.add_code_line(f"{var.short_name},")
        if "," in func_gen.code[-1]:
            func_gen.code[-1] = func_gen.code[-1][:-1]
        else:
            func_gen.code.pop(-1)
        func_gen.add_linebreak()

        _, params, var_map = self._process_vars()

        # define parameter values
        func_gen.add_linebreak()
        for key, (vtype, idx) in var_map.items():
            if vtype == 'constant':
                var = params[idx-self.idx_start][1]
                if var.short_name != 'y_delta' and var.short_name != 'y':
                    func_gen.add_code_line(f"{var.short_name} = {var}")
                    func_gen.add_linebreak()
        func_gen.add_linebreak()

        # define initial state
        func_gen.add_linebreak()
        npar = 0
        for key, (vtype, idx) in var_map.items():
            if vtype == 'constant':
                var = params[idx-self.idx_start][1]
                if var.short_name != 'y_delta' and var.short_name != 'y':
                    func_gen.add_code_line(f"args({idx}) = {var.short_name}")
                    func_gen.add_linebreak()
                    if idx > npar:
                        npar = idx
        func_gen.add_linebreak()

        func_gen.add_linebreak()
        for key, (vtype, idx) in var_map.items():
            var = self.get_var(key)
            if vtype == 'state_var':
                func_gen.add_code_line(f"{var.value} = {var.numpy()}")
                func_gen.add_linebreak()
        func_gen.add_linebreak()

        # end subroutine
        func_gen.add_linebreak()
        func_gen.add_code_line("end subroutine stpnt")
        func_gen.add_linebreak()

        # add dummy subroutines
        for routine in ['bcnd', 'icnd', 'fopt', 'pvls']:
            func_gen.add_linebreak()
            func_gen.add_code_line(f"subroutine {routine}")
            func_gen.add_linebreak()
            func_gen.add_code_line(f"end subroutine {routine}")
            func_gen.add_linebreak()
        func_gen.add_linebreak()
        func_gen.remove_indent()

        func_combined = f"{func_str} \n {func_gen.generate()}"
        f2py.compile(func_combined, source_fn=fn, modulename='rhs_func', extension='.f', verbose=False)

        self.npar = npar
        self.ndim = self.get_var('y').shape[0]

        # generate constants file
        #########################

        # declare auto constants and their values
        auto_constants = {'NDIM': self.ndim, 'NPAR': self.npar, 'IPS': -2, 'ILP': 0, 'ICP': [14], 'NTST': 1, 'NCOL': 4,
                          'IAD': 3, 'ISP': 0, 'ISW': 1, 'IPLT': 0, 'NBC': 0, 'NINT': 0, 'NMX': 10000, 'NPR': 100,
                          'MXBF': 10, 'IID': 2, 'ITMX': 8, 'ITNW': 5, 'NWTN': 3, 'JAC': 0, 'EPSL': 1e-7, 'EPSU': 1e-7,
                          'EPSS': 1e-5, 'IRS': 0, 'DS': 1e-4, 'DSMIN': 1e-8, 'DSMAX': 1e-2, 'IADS': 1, 'THL': {},
                          'THU': {}, 'UZR': {}, 'STOP': {}}

        # write auto constants to string
        cgen = FortranGen()
        for key, val in auto_constants.items():
            cgen.add_code_line(f"{key} = {val}")
            cgen.add_linebreak()

        # write auto constants to file
        try:
            with open(f'{directory}/c.ivp', 'wt') as cfile:
                cfile.write(cgen.generate())
        except FileNotFoundError:
            with open(f'{directory}/c.ivp', 'xt') as cfile:
                cfile.write(cgen.generate())

        self._auto_files_generated = True

        return fn
예제 #48
0
import sys
from os import path
sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
from util import IO_util, util_tp
import matplotlib.pyplot as plt
import numpy as np
from numpy import f2py
with open("/usr/local/home/yl8bc/Nic/PH/post/grid_generation/gridgen.f90") as sourcefile:
    sourcecode = sourcefile.read()
f2py.compile(sourcecode, modulename='gridgen', extension='.f90', extra_args='--f90flags=''-fopenmp'' -lgomp')
import gridgen

def normalized_flipped(u, nx):
    uscale = u[-1] - u[0]
    u -= u[0]
    u /= uscale
    u = np.flip(u, axis=0)
    u = 1. - u
    nx0 = u.shape[0]
    u = np.interp( np.linspace(0.,nx0-1.,nx), np.linspace(0.,nx0-1.,nx0), u)

    return u

def Billig_wedge_shock(M, R, beta, y):
    delta = R*0.386*np.exp(4.67/M**2)
    Rc = R*1.386*np.exp(1.8/np.power(M-1.,0.75))
    tan_beta = np.tan(beta)
    x = R + delta - Rc/tan_beta**2*(np.sqrt(1+y**2*tan_beta**2/Rc**2) - 1.)
    return x

def Billig_wedge_shock_inverse(M, R, beta, x):
예제 #49
0
    def setup_execs(self):
        from micki.fortran import f90_template, pyf_template
        from numpy import f2py

        # y_vec is an array symbol that will represent the species
        # concentrations provided by the differential equation solver inside
        # the Fortran code (that is, y_vec is an INPUT to the functions that
        # calculate the residual, Jacobian, and rate)
        y_vec = sym.IndexedBase('yin', shape=(self.nvariables, ))
        # Map y_vec elements (1-indexed, of course) onto 'modelparam' symbols
        trans = {self.symbols[i]: y_vec[i + 1] for i in range(self.nvariables)}
        # Map string represntation of 'modelparam' symbols onto string
        # representation of y-vec elements
        str_trans = {}
        for i in range(self.nvariables):
            str_trans[sym.fcode(self.symbols[i], source_format='free')] = \
                    sym.fcode(y_vec[i + 1], source_format='free')

        str_list = [key for key in str_trans]
        str_list.sort(key=len, reverse=True)

        # these will contain lists of strings, with each element being one
        # Fortran assignment for the master equation, Jacobian, and
        # rate expressions
        rescode = []
        jaccode = []
        ratecode = []

        # Convert symbolic master equation into a valid Fortran string
        for i in range(self.nvariables):
            fcode = sym.fcode(self.f_sym[i], source_format='free')
            # Replace modelparam symbols with their y_vec counterpart
            for key in str_list:
                fcode = fcode.replace(key, str_trans[key])
            # Create actual line of code for calculating residual
            rescode.append('   res({}) = '.format(i + 1) + fcode)

        # Effectively the same as above, except on the two-dimensional Jacobian
        # matrix.
        for i in range(self.nvariables):
            for j in range(self.nvariables):
                expr = self.jac_sym[j, i]
                # Unlike the residual, some elements of the Jacobian can be 0.
                # We don't need to bother writing 'jac(x,y) = 0' a hundred
                # times in Fortran, so we omit those.
                if expr != 0:
                    fcode = sym.fcode(expr, source_format='free')
                    for key in str_list:
                        fcode = fcode.replace(key, str_trans[key])
                    jaccode.append('   jac({}, {}) = '.format(j + 1, i + 1) +
                                   fcode)

        # See residual above
        for i, rate in enumerate(self.rates):
            fcode = sym.fcode(rate, source_format='free')
            for key in str_list:
                fcode = fcode.replace(key, str_trans[key])
            ratecode.append('   rates({}) = '.format(i + 1) + fcode)

        # We insert all of the parameters of this differential equation into
        # the prewritten Fortran template, including the residual, Jacobian,
        # and rate expressions we just calculated.
        program = f90_template.format(neq=self.nvariables,
                                      nx=1,
                                      nrates=len(self.rates),
                                      rescalc='\n'.join(rescode),
                                      jaccalc='\n'.join(jaccode),
                                      ratecalc='\n'.join(ratecode))

        # Generate a randomly-named temp directory for compiling the module.
        # We will name the actual module file after the directory.
        dname = tempfile.mkdtemp()
        modname = os.path.split(dname)[1]
        fname = modname + '.f90'
        pyfname = modname + '.pyf'

        # For debugging purposes, write out the generated module
        with open('solve_ida.f90', 'w') as f:
            f.write(program)

        # Write the pertinent data into the temp directory
        with open(os.path.join(dname, pyfname), 'w') as f:
            f.write(
                pyf_template.format(modname=modname,
                                    neq=self.nvariables,
                                    nrates=len(self.rates)))

        # Compile the module with f2py
        f2py.compile(program,
                     modulename=modname,
                     extra_args='--quiet '
                     '--f90flags="-Wno-unused-dummy-argument '
                     '-Wno-unused-variable -w -fopenmp" '
                     '-lsundials_fcvode '
                     '-lsundials_cvode -lsundials_fnvecopenmp '
                     '-lsundials_nvecopenmp -lopenblas_openmp -lgomp ' +
                     os.path.join(dname, pyfname),
                     source_fn=os.path.join(dname, fname),
                     verbose=0)

        # Delete the temporary directory
        shutil.rmtree(dname)

        # Import the module on-the-fly with __import__. This is kind of a hack.
        solve_ida = __import__(modname)

        # The Fortran module's initialize, solve, and finalize routines
        # are mapped onto finitialize, fsolve, and ffinalize inside the Model
        # object. We don't want users touching these manually
        self.finitialize = solve_ida.initialize
        self.ffind_steady_state = solve_ida.find_steady_state
        self.fsolve = solve_ida.solve
        self.ffinalize = solve_ida.finalize

        # Delete the module file. We've already imported it, so it's in memory.
        os.remove(modname + '.so')
예제 #50
0
import os

from numpy import f2py

FLAGS_DEBUG = []
FLAGS_DEBUG += [
    '-O', '-Wall', '-Wline-truncation', '-Wsurprising', '-Waliasing'
]
FLAGS_DEBUG += ['-Wunused-parameter', '-fwhole-file', '-fcheck=all']
FLAGS_DEBUG += ['-fbacktrace', '-g', '-fmax-errors=1', '-ffree-line-length-0']
FLAGS_DEBUG += ['-cpp', '-Wcharacter-truncation', '-Wimplicit-interface']

FLAGS_PRODUCTION = ['-O3', '-ffree-line-length-0']

args = ' '.join(FLAGS_PRODUCTION)

os.chdir('src')

cmd = ''
cmd += 'gfortran -c ' + args + ' -fpic shared_constants.f90 slsqp_interface.f90 slsqp.f '
cmd += ' replacements.f90 blackbox.f90'
os.system(cmd)

cmd = 'ar cr libblackbox.a *.o'
os.system(cmd)
os.chdir('../')

args = '--f90flags="' + args + '" -Isrc -Lsrc -lblackbox '
src = open('replacements_f2py.f90', 'rb').read()
f2py.compile(src, 'replacements_f2py', args, extension='.f90')
예제 #51
0
    def setup_execs(self):
        from micki.fortran2 import f90_template, pyf_template
        from numpy import f2py

        # y_vec is an array symbol that will represent the species
        # concentrations provided by the differential equation solver inside
        # the Fortran code (that is, y_vec is an INPUT to the functions that
        # calculate the residual, Jacobian, and rate)
        y_vec = sym.IndexedBase('y', shape=(self.nvariables, ))
        vac_vec = sym.IndexedBase('vac', shape=(len(self.vacancy), ))
        # Map y_vec elements (1-indexed, of course) onto 'modelparam' symbols
        trans = {self.symbols[i]: y_vec[i + 1] for i in range(self.nvariables)}
        trans.update(
            {vac.symbol: y_vec[i + 1]
             for i, vac in enumerate(self.vacancy)})
        # Map string represntation of 'modelparam' symbols onto string
        # representation of y-vec elements
        str_trans = {}
        for i, symbol in enumerate(self.symbols):
            str_trans[sym.fcode(symbol, source_format='free')] = \
                    sym.fcode(y_vec[i + 1], source_format='free')
        for i, vac in enumerate(self.vacancy):
            str_trans[sym.fcode(vac.symbol, source_format='free')] = \
                    sym.fcode(vac_vec[i + 1], source_format='free')

        str_list = [key for key in str_trans]
        str_list.sort(key=len, reverse=True)

        # these will contain lists of strings, with each element being one
        # Fortran assignment for the master equation, Jacobian, and
        # rate expressions
        dypdrcode = []
        drdycode = []
        vaccode = []
        drdvaccode = []
        dvacdycode = []

        for i, expr in enumerate(self.vac_sym):
            fcode = sym.fcode(expr, source_format='free')
            for key in str_list:
                fcode = fcode.replace(key, str_trans[key])
            vaccode.append('   vac({}) = '.format(i + 1) + fcode)

        for i, row in enumerate(self.drdvac):
            for j, elem in enumerate(row):
                if elem != 0:
                    fcode = sym.fcode(elem, source_format='free')
                    for key in str_list:
                        fcode = fcode.replace(key, str_trans[key])
                    drdvaccode.append(
                        '   drdvac({}, {}) = '.format(i + 1, j + 1) + fcode)

        for i, row in enumerate(self.dvacdy):
            for j, elem in enumerate(row):
                if elem != 0:
                    dvacdycode.append(
                        '   dvacdy({}, {}) = '.format(i + 1, j + 1) +
                        sym.fcode(elem, source_format='free'))

        for i, row in enumerate(self.dypdr):
            for j, elem in enumerate(row):
                if elem != 0:
                    dypdrcode.append(
                        '   dypdr({}, {}) = '.format(i + 1, j + 1) +
                        sym.fcode(elem, source_format='free'))

        # Effectively the same as above, except on the two-dimensional Jacobian
        # matrix.
        for i, row in enumerate(self.drdy):
            for j, elem in enumerate(row):
                if elem != 0:
                    fcode = sym.fcode(elem, source_format='free')
                    for key in str_list:
                        fcode = fcode.replace(key, str_trans[key])
                    drdycode.append('   drdy({}, {}) = '.format(i + 1, j + 1) +
                                    fcode)

        ratecode = self._get_rate_code(str_list, str_trans)
        #flowratecode = self._get_flowrate_code(str_list, str_trans)

        is_gas = ['   isgas = 0']
        for idx, species in enumerate(self._variable_species):
            if isinstance(species, _Fluid):
                is_gas.append(f'   isgas({idx+1}) = 1')
            else:
                is_gas.append(f'   isgas({idx+1}) = 0')

        # We insert all of the parameters of this differential equation into
        # the prewritten Fortran template, including the residual, Jacobian,
        # and rate expressions we just calculated.
        program = f90_template.format(
            neq=self.nvariables,
            nx=1,
            nrates=len(self.rates),
            nvac=len(self.vacancy),
            dypdrcalc='\n'.join(dypdrcode),
            drdycalc='\n'.join(drdycode),
            ratecalc='\n'.join(ratecode),
            vaccalc='\n'.join(vaccode),
            drdvaccalc='\n'.join(drdvaccode),
            dvacdycalc='\n'.join(dvacdycode),
            isgas='\n'.join(is_gas),
        )

        # Generate a randomly-named temp directory for compiling the module.
        # We will name the actual module file after the directory.
        dname = tempfile.mkdtemp()
        modname = os.path.split(dname)[1]
        fname = modname + '.f90'
        pyfname = modname + '.pyf'

        # For debugging purposes, write out the generated module
        with open('solve_ida.f90', 'w') as f:
            f.write(program)

        # Write the pertinent data into the temp directory
        with open(os.path.join(dname, pyfname), 'w') as f:
            f.write(
                pyf_template.format(modname=modname,
                                    neq=self.nvariables,
                                    nrates=len(self.rates),
                                    nvac=len(self.vacancy)))

        # Compile the module with f2py
        lapack = "-lmkl_rt"
        if "MICKI_LAPACK" in os.environ:
            lapack = os.environ["MICKI_LAPACK"]
        os.environ["CFLAGS"] = "-w"

        f2py.compile(program,
                     modulename=modname,
                     extra_args='--quiet '
                     '--f90flags="-Wno-unused-dummy-argument '
                     '-Wno-unused-variable -Wno-unused-func -w" '
                     '-lsundials_fida '
                     '-lsundials_fnvecserial '
                     '-lsundials_ida '
                     '-lsundials_fsunlinsollapackdense '
                     '-lsundials_sunlinsollapackdense '
                     '-lsundials_nvecserial ' + lapack + ' ' +
                     os.path.join(dname, pyfname),
                     source_fn=os.path.join(dname, fname),
                     verbose=0)
        # Delete the temporary directory
        shutil.rmtree(dname)

        # Import the module on-the-fly with __import__. This is kind of a hack.
        solve_ida = __import__(modname)
        self._solve_ida = solve_ida

        # The Fortran module's initialize, solve, and finalize routines
        # are mapped onto finitialize, fsolve, and ffinalize inside the Model
        # object. We don't want users touching these manually
        self.finitialize = solve_ida.initialize
        self.ffind_steady_state = solve_ida.find_steady_state
        self.fsolve = solve_ida.solve
        self.ffinalize = solve_ida.finalize

        # Delete the module file. We've already imported it, so it's in memory.
        modulefile = glob.glob(f'{modname}*.so')[0]
        os.remove(modulefile)
예제 #52
0
from numpy import f2py

fsource = b'''
       subroutine sumarray(A, N)
       REAL, DIMENSION(N) :: A
       INTEGER :: N
       RES = 0.1 * SUM(A, MASK = A .GT. 0)
       RES2 = -0.025 * SUM(A, MASK = A .LT. 0)
       print*, RES + RES2
       end 
 '''
f2py.compile(fsource, modulename='fort_sum', verbose=0)
예제 #53
0
from numpy import f2py
from numpy.distutils.fcompiler import new_fcompiler

compiler = new_fcompiler(compiler='intel')
compiler.dump_properties()

with open(
        "C:/Users/ahmed.kotb/PycharmProjects/AGPS/resources/Formating_SH_files.f"
) as sourcefile:
    sourcecode = sourcefile.read()
    print 'Fortran code'
    print sourcecode

f2py.compile(sourcecode, modulename='add', extra_args='--fcompiler=gfortran')
예제 #54
0
          a2 = (-x + 0.5d0) * 0.25d0 / eps
          a3 = (-x + 0.375d0) * 0.5 / eps
          expa1 = 0.d0
          expa2 = 0.d0
          expa3 = 0.d0
          temp = max(a1, a2, a3)
          if ((a1-temp) .ge. -35.d0) expa1 = exp(a1-temp)
          if ((a2-temp) .ge. -35.d0) expa2 = exp(a2-temp)
          if ((a3-temp) .ge. -35.d0) expa3 = exp(a3-temp)

          u(1) = (0.1d0*expa1+0.5d0*expa2+expa3) / (expa1+expa2+expa3)
      return
      end
"""

f2py.compile(prob_def_f.encode('ascii'), modulename='problemdef', verbose=0)
"""
Part 2

Using the compiled callback routines to solve the problem.
"""

import bacoli_py
import numpy
import time
from problemdef import f, bndxa, bndxb, uinit

# Initialize the Solver object.
solver = bacoli_py.Solver()

# Specify the number of PDE's in this system.
예제 #55
0
# python -m numpy.f2py -c mPitzer_w_NaCl.f90 -m Pitzer

f = open('mPitzer_w_NaCl.f90', mode='r')
from numpy import f2py

source = "".join(f.readlines())

f2py.compile(source=source, modulename='Pitzer', extension='.f90')

import Pitzer

a = Pitzer.mpitzer_w_nacl(mnacl=1, t_k=300)

print("a = ", a)
예제 #56
0
    def eval(self,x,globals=None, locals=None):
        """
        EXAMPLES::
        
            sage: from sage.misc.inline_fortran import InlineFortran, _example
            sage: test_fortran = InlineFortran(globals())   # optional -- fortran
            sage: test_fortran(_example)                    # optional -- fortran
            sage: import numpy
            sage: n = numpy.array(range(10),dtype=float)
            sage: fib(n,int(10))                            # optional -- fortran
            sage: n                                         # optional -- fortran
            array([  0.,   1.,   1.,   2.,   3.,   5.,   8.,  13.,  21.,  34.])
        """
        if len(x.splitlines()) == 1 and os.path.exists(x):
            filename = x
            x = open(x).read()
            if filename.lower().endswith('.f90'):
                x = '!f90\n' + x
        global count
        # On linux g77_shared should be a script that runs sage_fortran -shared
        # On OS X it should be a script that runs gfortran -bundle -undefined dynamic_lookup
        path = os.environ['SAGE_LOCAL']+'/bin/sage-g77_shared'
        from numpy import f2py
        old_import_path=os.sys.path
        cwd=os.getcwd()
        os.sys.path.append(cwd)

        #name = tmp_dir() + '/fortran_module_%d'%count
        name = 'fortran_module_%d'%count
        if os.path.exists(name):
            os.unlink(name)
        s_lib_path=""
        s_lib=""
        for s in self.library_paths:
            s_lib_path=s_lib_path+"-L"+s+" "

        for s in self.libraries:
            s_lib=s_lib +"-l"+s + " "

        # if the first line has !f90 as a comment gfortran will treat it as
        # fortran 90 code
        if x.startswith('!f90'):        
            fname = os.path.join(tmp_filename() +'.f90')
        else:
            fname = os.path.join(tmp_filename() +'.f')

        log = tmp_filename()
        extra_args = '--quiet --f77exec=%s --f90exec=%s %s %s  1>&2 >"%s"'%(
                    path, path, s_lib_path, s_lib, log)

        f2py.compile(x, name, extra_args = extra_args, source_fn=fname)

        log_string = open(log).read()

        os.unlink(log)
        os.unlink(fname)

        if self.verbose:
            print log_string
        
        count += 1
        try:
            m=__builtin__.__import__(name)
        except ImportError:
            if not self.verbose:
                print log_string
            return
        finally:
            os.sys.path=old_import_path
            os.unlink(name + '.so')
        
        for k, x in m.__dict__.iteritems():
            if k[0] != '_':
                self.globals[k] = x
예제 #57
0
#import add
#print add.zadd([1,2,3],[4,5,6])


from numpy import f2py
with open("addd.f") as sourcefile:
	sourcecode=sourcefile.read()
	f2py.compile(sourcecode,modulename='hello')

import hello
print hello.zadd([1,2,3],[4,5,6])
#changessss
예제 #58
0
      double precision t,u,dfu,rpar
      dimension u(neq),dfu(ldfu,neq),rpar(*),ipar(*)
      integer i,j
      do 10 j = 1,neq
        dfu(1,j) = -2.0d0
        dfu(2,j) = 1.0d0
 10     dfu(6,j) = 1.0d0
      do 20 j = 5,neq,5
 20     dfu(2,j) = 0.0d0
      return
      end
"""

# Compile these Fortran subroutines
from numpy import f2py
f2py.compile(f_str+'\n'+jac_banded_str, modulename='tmp_callback', verbose=False)
import tmp_callback
f_f77, jac_banded_f77 = tmp_callback.f_f77, tmp_callback.jac_f77_radau5

import sys
try:
    n_points = int(sys.argv[1])    # Read from input
except:
    n_points = 10   # default number of time-steps


t0, tn, u0 = 0., 4.,  [1]+24*[0]
ml, mu = 5, 0
time_points = np.linspace(t0, tn, n_points)
atol, rtol = 1e-2, 1e-2