示例#1
0
def copy_installed_scripts():
    """
    Copy installed executable scripts to the scitools++/bin directory.
    """
    print '********* copy installed executable scripts **************'
    scripts = SCRIPTS  # see top of this file
    print scripts
    for script in scripts:
        system("cp `which %s` %s" % (script, bindir))

    # fix headers (replace user-specific install path):
    for f in scripts:
        system(r'subst.py "#!.+" "#!/usr/bin/env python" %s' % \
                  join(bindir, f))
    for f in glob.glob(join(bindir, '*.old~')):
        os.remove(f)
示例#2
0
def copy_installed_scripts():
    """
    Copy installed executable scripts to the scitools++/bin directory.
    """
    print '********* copy installed executable scripts **************'
    scripts = SCRIPTS  # see top of this file
    print scripts
    for script in scripts:
        system("cp `which %s` %s" % (script, bindir))

    # fix headers (replace user-specific install path):
    for f in scripts:
        system(r'subst.py "#!.+" "#!/usr/bin/env python" %s' % \
                  join(bindir, f))
    for f in glob.glob(join(bindir, '*.old~')):
        os.remove(f)
示例#3
0
def copy_installed_modules():
    """
    Copy installed modules to scitools++.
    An alternative is to copy the source of these modules and
    run multiple setup.py in scitools++ to install each dir in scitools++.
    The set-up now is that scitools++ should just be in PYTHONPATH and
    then everything is correctly installed.
    """
    print '********* copy installed modules to scitools++ **************'
    path = join(sys.prefix, 'lib', 'python' + sys.version[:3], 'site-packages')
    files = MODULES  # see top of this file
    print files
    
    files = [join(path, file) for file in files]
    pmw = join(py_package_src, 'Pmw_1_3', 'Pmw')
    files.append(pmw)
    # copy files to libdir:
    # (shutil.copytree does not work properly for this type of copy)
    cmd = 'cp -r ' + ' '.join(files) + ' ' + libdir
    print cmd
    system(cmd)
示例#4
0
def copy_installed_modules():
    """
    Copy installed modules to scitools++.
    An alternative is to copy the source of these modules and
    run multiple setup.py in scitools++ to install each dir in scitools++.
    The set-up now is that scitools++ should just be in PYTHONPATH and
    then everything is correctly installed.
    """
    print '********* copy installed modules to scitools++ **************'
    path = join(sys.prefix, 'lib', 'python' + sys.version[:3], 'site-packages')
    files = MODULES  # see top of this file
    print files

    files = [join(path, file) for file in files]
    pmw = join(py_package_src, 'Pmw_1_3', 'Pmw')
    files.append(pmw)
    # copy files to libdir:
    # (shutil.copytree does not work properly for this type of copy)
    cmd = 'cp -r ' + ' '.join(files) + ' ' + libdir
    print cmd
    system(cmd)
示例#5
0
def make_f77(f, bc, I):
    code = """
      subroutine scheme_f77(up, u, um, x, y, t, nx, ny, Cx2, Cy2,
     &                      dt2, t_old)
      integer nx, ny
      real*8 up(0:nx, 0:ny), u(0:nx, 0:ny), um(0:nx, 0:ny)
      real*8 x(0:nx), y(0:ny)
      real*8 Cx2, Cy2, dt2, t, t_old
Cf2py intent(in, out) up
      real*8 f
      external f

      do j = 1, ny-1
         do i = 1, nx-1
            up(i,j) = - um(i,j) + 2*u(i,j) + 
     &          Cx2*(u(i-1,j) - 2*u(i,j) + u(i+1,j)) +
     &          Cy2*(u(i,j-1) - 2*u(i,j) + u(i,j+1)) +
     &          dt2*f(x(i),y(j),t_old)
         end do
      end do
      return
      end

      subroutine ic_f77(u, um, x, y, nx, ny, Cx2, Cy2, dt)
      integer nx, ny
      real*8 u(0:nx, 0:ny), um(0:nx, 0:ny)
      real*8 x(0:nx), y(0:ny)
      real*8 Cx2, Cy2, dt, dt2
Cf2py intent(in, out) u, um
      real*8 f, ic
      external f, ic

      dt2 = dt*dt
      do j = 0, ny
         do i = 0, nx
            u(i,j) = ic(x(i),y(j))
         end do
      end do
      do j = 1, ny-1
         do i = 1, nx-1
            um(i,j) = u(i,j) +
     &          0.5*Cx2*(u(i-1,j) - 2*u(i,j) + u(i+1,j)) +
     &          0.5*Cy2*(u(i,j-1) - 2*u(i,j) + u(i,j+1)) +
     &          dt2*f(x(i),y(j),0.0D0)
         end do
      end do
C     boundary values:
      call bc_f77(um, x, y, nx, ny, dt)
      return
      end

      subroutine bc_f77(up, x, y, nx, ny, t)
      integer nx, ny
      real*8 up(0:nx, 0:ny)
      real*8 x(0:nx), y(0:ny)
      real*8 t
Cf2py intent(in, out) up
      real*8 bc
      external bc

      i = 0
      do j = 0, ny
         up(i,j) = bc(x(i),y(j),t)
      end do
      j = 0
      do i = 0, nx
         up(i,j) = bc(x(i),y(j),t)
      end do
      i = nx
      do j = 0, ny
         up(i,j) = bc(x(i),y(j),t)
      end do
      j = ny
      do i = 0, nx
         up(i,j) = bc(x(i),y(j),t)
      end do
      return
      end


%s

%s

%s

%s      
""" % (f.F77_code('f'), bc.F77_code('bc'), I.F77_code('ic'), I.F77_pow())

    f = open('_tmp.f', 'w')
    f.write(code)
    f.close()

    cmd = "f2py -m f77 -c --fcompiler='gfortran' --build-dir tmp2"\
          " -DF2PY_REPORT_ON_ARRAY_COPY=1 _tmp.f"
    print cmd
    os.system('rm -rf tmp2')
    failure, output = system(cmd)
    if failure:
        print 'unsuccessful F77 extension module compilation'
        print output
        sys.exit(1)
def solver(
        I,
        f,
        c,
        bc,
        Lx,
        Ly,
        nx,
        ny,
        dt,
        tstop,
        user_action=None,
        implementation={
            'ic': 'vectorized',  # or 'scalar'
            'inner': 'vectorized',
            'bc': 'vectorized',
            'storage': 'f77'
        },
        verbose=True):
    """
    Solve the 2D wave equation u_tt = u_xx + u_yy + f(x,t) on (0,L) with
    u = bc(x,y, t) on the boundary and initial condition du/dt = 0.

    nx and ny are the total number of grid cells in the x and y
    directions. The grid points are numbered as (0,0), (1,0), (2,0),
    ..., (nx,0), (0,1), (1,1), ..., (nx, ny).

    dt is the time step. If dt<=0, an optimal time step is used.
    tstop is the stop time for the simulation.

    I, f, bc are functions: I(x,y), f(x,y,t), bc(x,y,t)

    user_action: function of (u, x, y, t) called at each time
    level (x and y are one-dimensional coordinate vectors).
    This function allows the calling code to plot the solution,
    compute errors, etc.

    implementation: a dictionary specifying how the initial
    condition ('ic'), the scheme over inner points ('inner'),
    and the boundary conditions ('bc') are to be implemented.
    Two values are legal: 'scalar' or 'vectorized'.
    'scalar' means straight loops over grid points, while
    'vectorized' means special NumPy vectorized operations.
    If a key in the implementation dictionary is missing, it
    defaults in this function to 'scalar' (the safest strategy).
    Note that if 'vectorized' is specified, the functions I, f,
    and bc must work in vectorized mode. It is always recommended
    to first run the 'scalar' mode and then compare 'vectorized'
    results with the 'scalar' results to check that I, f, and bc
    work.

    verbose: true if a message at each time step is written,
    false implies no output during the simulation.
    """
    dx = Lx / float(nx)
    dy = Ly / float(ny)
    x = linspace(0, Lx, nx + 1)  # grid points in x dir
    y = linspace(0, Ly, ny + 1)  # grid points in y dir
    xv = x[:, newaxis]  # for vectorized function evaluations
    yv = y[newaxis, :]
    if dt <= 0:  # max time step?
        dt = (1 / float(c)) * (1 / sqrt(1 / dx**2 + 1 / dy**2))
    Cx2 = (c * dt / dx)**2
    Cy2 = (c * dt / dy)**2  # help variables
    dt2 = dt**2

    up = zeros((nx + 1, ny + 1))  # solution array
    u = up.copy()  # solution at t-dt
    um = up.copy()  # solution at t-2*dt

    # use scalar implementation mode if no info from user:
    if 'ic' not in implementation:
        implementation['ic'] = 'scalar'
    if 'bc' not in implementation:
        implementation['bc'] = 'scalar'
    if 'inner' not in implementation:
        implementation['inner'] = 'scalar'
    if 'f77' in implementation.itervalues():
        # import F77 extension module, or build it if necessary
        try:
            import wave2D_func1_loop as f77
        except:
            print 'Make the F77 extension module on the fly...'
            cmd = 'f2py -m wave2D_func1_loop -c --build-dir tmp1 '\
                  '-DF2PY_REPORT_ON_ARRAY_COPY=1 wave2D_func1_loop_0.f'
            failure, output = system(cmd)
            try:
                import wave2D_func1_loop as f77
            except:
                print 'Something went wrong with f2py - '\
                      'try manual executition of\n  ', cmd
                print output
                sys.exit(1)
        # turn arrays to column major storage after the init. cond.

    # set initial condition:
    t = 0.0
    if implementation['ic'] == 'scalar':
        for i in iseq(0, nx):
            for j in iseq(0, ny):
                u[i, j] = I(x[i], y[j])
        for i in iseq(1, nx - 1):
            for j in iseq(1, ny - 1):
                um[i,j] = u[i,j] + \
                  0.5*Cx2*(u[i-1,j] - 2*u[i,j] + u[i+1,j]) + \
                  0.5*Cy2*(u[i,j-1] - 2*u[i,j] + u[i,j+1]) + \
                  dt2*f(x[i], y[j], t)
        # boundary values of um (equals t=dt when du/dt=0)
        i = 0
        for j in iseq(0, ny):
            um[i, j] = bc(x[i], y[j], t + dt)
        j = 0
        for i in iseq(0, nx):
            um[i, j] = bc(x[i], y[j], t + dt)
        i = nx
        for j in iseq(0, ny):
            um[i, j] = bc(x[i], y[j], t + dt)
        j = ny
        for i in iseq(0, nx):
            um[i, j] = bc(x[i], y[j], t + dt)
    elif implementation['ic'] == 'vectorized' or \
         implementation['ic'] == 'f77':  # not impl. in F77
        # vectorized version:
        u = I(xv, yv)
        um[1:nx,1:ny] = u[1:nx,1:ny] + \
        0.5*Cx2*(u[0:nx-1,1:ny] - 2*u[1:nx,1:ny] + u[2:nx+1,1:ny]) + \
        0.5*Cy2*(u[1:nx,0:ny-1] - 2*u[1:nx,1:ny] + u[1:nx,2:ny+1]) + \
        dt2*f(xv[1:nx,:], yv[:,1:ny], 0.0)
        # boundary values (t=dt):
        i = 0
        um[i, :] = bc(x[i], y, t + dt)
        j = 0
        um[:, j] = bc(x, y[j], t + dt)
        i = nx
        um[i, :] = bc(x[i], y, t + dt)
        j = ny
        um[:, j] = bc(x, y[j], t + dt)

    if user_action is not None:
        user_action(u, x, y, t)  # allow user to plot etc.

    while t <= tstop:
        t_old = t
        t += dt
        if verbose:
            print 'solving (%s version) at t=%g' % \
                  (implementation['inner'], t)
        # update all inner points:
        if implementation['inner'] == 'scalar':
            for i in iseq(start=1, stop=nx - 1):
                for j in iseq(start=1, stop=ny - 1):
                    up[i,j] = - um[i,j] + 2*u[i,j] + \
                       Cx2*(u[i-1,j] - 2*u[i,j] + u[i+1,j]) + \
                       Cy2*(u[i,j-1] - 2*u[i,j] + u[i,j+1]) + \
                       dt2*f(x[i], y[j], t_old)
        elif implementation['inner'] == 'vectorized':
            up[1:nx,1:ny] = - um[1:nx,1:ny] + 2*u[1:nx,1:ny] + \
           Cx2*(u[0:nx-1,1:ny] - 2*u[1:nx,1:ny] + u[2:nx+1,1:ny]) + \
           Cy2*(u[1:nx,0:ny-1] - 2*u[1:nx,1:ny] + u[1:nx,2:ny+1]) + \
           dt2*f(xv[1:nx,:], yv[:,1:ny], t_old)
        elif implementation['inner'] == 'f77':
            f_array = f(xv, yv, t_old)
            if isinstance(f_array, (float, int)):
                # f was not properly vectorized, turn const into array:
                f_array = zeros((x.size, y.size)) + f_array
            up = f77.loop(u, um, f_array, Cx2, Cy2, dt2)

            #id_u = id(u); id_um = id(um)
            #up,u,um = f77.loop(up, u, um, f_array, Cx2, Cy2, dt2)
            #print 'u changed:', id_u!=id(u),
            #print 'um changed:', id_um!=id(um),
        else:
            raise ValueError, 'version=%s' % implementation['inner']

        # insert boundary conditions:
        if implementation['bc'] == 'scalar':
            i = 0
            for j in iseq(0, ny):
                up[i, j] = bc(x[i], y[j], t)
            j = 0
            for i in iseq(0, nx):
                up[i, j] = bc(x[i], y[j], t)
            i = nx
            for j in iseq(0, ny):
                up[i, j] = bc(x[i], y[j], t)
            j = ny
            for i in iseq(0, nx):
                up[i, j] = bc(x[i], y[j], t)
        elif implementation['bc'] == 'vectorized' or \
             implementation['ic'] == 'f77':  # not impl. in F77
            i = 0
            up[i, :] = bc(x[i], y, t)
            j = 0
            up[:, j] = bc(x, y[j], t)
            i = nx
            up[i, :] = bc(x[i], y, t)
            j = ny
            up[:, j] = bc(x, y[j], t)

        if user_action is not None:
            user_action(up, x, y, t)
        # update data structures for next step:
        um, u, up = u, up, um
        #tmp = um; um = u; u = up; up = tmp
        # safer and slower: um = u.copy(); u = up.copy()

    return dt  # dt might be computed in this function
示例#7
0
def solver(I, f, c, bc, Lx, Ly, nx, ny, dt, tstop,
           user_action=None, 
           implementation={'ic': 'vectorized',  # or 'scalar'
                           'inner': 'vectorized',
                           'bc': 'vectorized',
                           'storage': 'f77'},
           verbose=True):
    """
    Solve the 2D wave equation u_tt = u_xx + u_yy + f(x,t) on (0,L) with
    u = bc(x,y, t) on the boundary and initial condition du/dt = 0.

    nx and ny are the total number of grid cells in the x and y
    directions. The grid points are numbered as (0,0), (1,0), (2,0),
    ..., (nx,0), (0,1), (1,1), ..., (nx, ny).

    dt is the time step. If dt<=0, an optimal time step is used.
    tstop is the stop time for the simulation.

    I, f, bc are functions: I(x,y), f(x,y,t), bc(x,y,t)

    user_action: function of (u, x, y, t) called at each time
    level (x and y are one-dimensional coordinate vectors).
    This function allows the calling code to plot the solution,
    compute errors, etc.

    implementation: a dictionary specifying how the initial
    condition ('ic'), the scheme over inner points ('inner'),
    and the boundary conditions ('bc') are to be implemented.
    Two values are legal: 'scalar' or 'vectorized'.
    'scalar' means straight loops over grid points, while
    'vectorized' means special NumPy vectorized operations.
    If a key in the implementation dictionary is missing, it
    defaults in this function to 'scalar' (the safest strategy).
    Note that if 'vectorized' is specified, the functions I, f,
    and bc must work in vectorized mode. It is always recommended
    to first run the 'scalar' mode and then compare 'vectorized'
    results with the 'scalar' results to check that I, f, and bc
    work.

    verbose: true if a message at each time step is written,
    false implies no output during the simulation.
    """
    dx = Lx/float(nx)
    dy = Ly/float(ny)
    x = linspace(0, Lx, nx+1)  # grid points in x dir
    y = linspace(0, Ly, ny+1)  # grid points in y dir
    xv = x[:,newaxis]          # for vectorized function evaluations
    yv = y[newaxis,:]
    if dt <= 0:                # max time step?
        dt = (1/float(c))*(1/sqrt(1/dx**2 + 1/dy**2))
    Cx2 = (c*dt/dx)**2;  Cy2 = (c*dt/dy)**2    # help variables
    dt2 = dt**2

    up = zeros((nx+1,ny+1))    # solution array
    u  = up.copy()             # solution at t-dt
    um = up.copy()             # solution at t-2*dt

    # use scalar implementation mode if no info from user:
    if 'ic' not in implementation:
        implementation['ic'] = 'scalar'
    if 'bc' not in implementation:
        implementation['bc'] = 'scalar'
    if 'inner' not in implementation:
        implementation['inner'] = 'scalar'
    if 'f77' in implementation.itervalues():
        # import F77 extension module, or build it if necessary
        try:
            import wave2D_func1_loop as f77
        except:
            print 'Make the F77 extension module on the fly...'
            cmd = 'f2py -m wave2D_func1_loop -c --build-dir tmp1 '\
                  '-DF2PY_REPORT_ON_ARRAY_COPY=1 wave2D_func1_loop_0.f'
            failure, output = system(cmd)
            try:
                import wave2D_func1_loop as f77
            except:
                print 'Something went wrong with f2py - '\
                      'try manual executition of\n  ', cmd
                print output
                sys.exit(1)
        # turn arrays to column major storage after the init. cond.
                        
    # set initial condition:
    t = 0.0
    if implementation['ic'] == 'scalar':
        for i in iseq(0,nx):
            for j in iseq(0,ny):
                u[i,j] = I(x[i], y[j])
        for i in iseq(1,nx-1):
            for j in iseq(1,ny-1):
                um[i,j] = u[i,j] + \
                  0.5*Cx2*(u[i-1,j] - 2*u[i,j] + u[i+1,j]) + \
                  0.5*Cy2*(u[i,j-1] - 2*u[i,j] + u[i,j+1]) + \
                  dt2*f(x[i], y[j], t) 
        # boundary values of um (equals t=dt when du/dt=0)
        i = 0
        for j in iseq(0,ny): um[i,j] = bc(x[i], y[j], t+dt)
        j = 0
        for i in iseq(0,nx): um[i,j] = bc(x[i], y[j], t+dt)
        i = nx
        for j in iseq(0,ny): um[i,j] = bc(x[i], y[j], t+dt)
        j = ny
        for i in iseq(0,nx): um[i,j] = bc(x[i], y[j], t+dt)
    elif implementation['ic'] == 'vectorized' or \
         implementation['ic'] == 'f77':  # not impl. in F77
        # vectorized version:
        u = I(xv,yv)
        um[1:nx,1:ny] = u[1:nx,1:ny] + \
        0.5*Cx2*(u[0:nx-1,1:ny] - 2*u[1:nx,1:ny] + u[2:nx+1,1:ny]) + \
        0.5*Cy2*(u[1:nx,0:ny-1] - 2*u[1:nx,1:ny] + u[1:nx,2:ny+1]) + \
        dt2*f(xv[1:nx,:], yv[:,1:ny], 0.0)
        # boundary values (t=dt):
        i = 0;  um[i,:] = bc(x[i], y, t+dt)
        j = 0;  um[:,j] = bc(x, y[j], t+dt)
        i = nx; um[i,:] = bc(x[i], y, t+dt)
        j = ny; um[:,j] = bc(x, y[j], t+dt)

    if user_action is not None:
        user_action(u, x, y, t)  # allow user to plot etc.
    
    while t <= tstop:
        t_old = t;  t += dt
        if verbose:
            print 'solving (%s version) at t=%g' % \
                  (implementation['inner'], t)
        # update all inner points:
        if implementation['inner'] == 'scalar':
            for i in iseq(start=1, stop=nx-1):
                for j in iseq(start=1, stop=ny-1):
                    up[i,j] = - um[i,j] + 2*u[i,j] + \
                       Cx2*(u[i-1,j] - 2*u[i,j] + u[i+1,j]) + \
                       Cy2*(u[i,j-1] - 2*u[i,j] + u[i,j+1]) + \
                       dt2*f(x[i], y[j], t_old)
        elif implementation['inner'] == 'vectorized':
            up[1:nx,1:ny] = - um[1:nx,1:ny] + 2*u[1:nx,1:ny] + \
           Cx2*(u[0:nx-1,1:ny] - 2*u[1:nx,1:ny] + u[2:nx+1,1:ny]) + \
           Cy2*(u[1:nx,0:ny-1] - 2*u[1:nx,1:ny] + u[1:nx,2:ny+1]) + \
           dt2*f(xv[1:nx,:], yv[:,1:ny], t_old)
        elif implementation['inner'] == 'f77':
            f_array = f(xv, yv, t_old)
            if isinstance(f_array, (float,int)):
                # f was not properly vectorized, turn const into array:
                f_array = zeros((x.size,y.size)) + f_array
            up = f77.loop(u, um, f_array, Cx2, Cy2, dt2)

            #id_u = id(u); id_um = id(um)
            #up,u,um = f77.loop(up, u, um, f_array, Cx2, Cy2, dt2)
            #print 'u changed:', id_u!=id(u),
            #print 'um changed:', id_um!=id(um),
        else:
            raise ValueError, 'version=%s' % implementation['inner']

        # insert boundary conditions:
        if implementation['bc'] == 'scalar':
            i = 0
            for j in iseq(0,ny): up[i,j] = bc(x[i], y[j], t)
            j = 0
            for i in iseq(0,nx): up[i,j] = bc(x[i], y[j], t)
            i = nx
            for j in iseq(0,ny): up[i,j] = bc(x[i], y[j], t)
            j = ny
            for i in iseq(0,nx): up[i,j] = bc(x[i], y[j], t)
        elif implementation['bc'] == 'vectorized' or \
             implementation['ic'] == 'f77':  # not impl. in F77
            i = 0;  up[i,:] = bc(x[i], y, t)
            j = 0;  up[:,j] = bc(x, y[j], t)
            i = nx; up[i,:] = bc(x[i], y, t)
            j = ny; up[:,j] = bc(x, y[j], t)

        if user_action is not None:
            user_action(up, x, y, t)
        # update data structures for next step:
        um, u, up = u, up, um
        #tmp = um; um = u; u = up; up = tmp
        # safer and slower: um = u.copy(); u = up.copy()

    return dt  # dt might be computed in this function
示例#8
0
def solver(I, f, c, bc, Lx, Ly, nx, ny, dt, tstop,
           user_action=None, 
           implementation={'ic': 'vectorized',  # or 'scalar' or 'weave'
                           'inner': 'vectorized',
                           'bc': 'vectorized',
                           'storage': 'f77'},
           verbose=True):
    """
    Solve the 2D wave equation u_tt = u_xx + u_yy + f(x,t) on (0,L) with
    u = bc(x,y, t) on the boundary and initial condition du/dt = 0.

    nx and ny are the total number of grid cells in the x and y
    directions. The grid points are numbered as (0,0), (1,0), (2,0),
    ..., (nx,0), (0,1), (1,1), ..., (nx, ny).

    dt is the time step. If dt<=0, an optimal time step is used.
    tstop is the stop time for the simulation.

    I, f, bc are functions: I(x,y), f(x,y,t), bc(x,y,t)

    user_action: function of (u, x, y, t) called at each time
    level (x and y are one-dimensional coordinate vectors).
    This function allows the calling code to plot the solution,
    compute errors, etc.

    implementation: a dictionary specifying how the initial
    condition ('ic'), the scheme over inner points ('inner'),
    and the boundary conditions ('bc') are to be implemented.
    Two values are legal: 'scalar' or 'vectorized'.
    'scalar' means straight loops over grid points, while
    'vectorized' means special NumPy vectorized operations.
    If a key in the implementation dictionary is missing, it
    defaults in this function to 'scalar' (the safest strategy).
    Note that if 'vectorized' is specified, the functions I, f,
    and bc must work in vectorized mode. It is always recommended
    to first run the 'scalar' mode and then compare 'vectorized'
    results with the 'scalar' results to check that I, f, and bc
    work.

    verbose: true if a message at each time step is written,
    false implies no output during the simulation.
    """
    dx = Lx/float(nx)
    dy = Ly/float(ny)
    x = linspace(0, Lx, nx+1)  # grid points in x dir
    y = linspace(0, Ly, ny+1)  # grid points in y dir
    xv = x[:,newaxis]          # for vectorized function evaluations
    yv = y[newaxis,:]
    if dt <= 0:              # max time step?
        dt = (1/float(c))*(1/sqrt(1/dx**2 + 1/dy**2))
    Cx2 = (c*dt/dx)**2;  Cy2 = (c*dt/dy)**2    # help variables
    dt2 = dt**2

    up = zeros((nx+1,ny+1))    # solution array
    u  = up.copy()             # solution at t-dt
    um = up.copy()             # solution at t-2*dt

    # use scalar implementation mode if no info from user:
    if 'ic' not in implementation:
        implementation['ic'] = 'scalar'
    if 'bc' not in implementation:
        implementation['bc'] = 'scalar'
    if 'inner' not in implementation:
        implementation['inner'] = 'scalar'

    if 'weave' in implementation.itervalues() or \
       'f77' in implementation.itervalues():
        # we avoid callback to Python and require f, bc, and I to be
        # string formulas:
        if not isinstance(f,  StringFunction) or \
           not isinstance(bc, StringFunction) or \
           not isinstance(I,  StringFunction):
            raise TypeError, \
                  'with Weave or F77, f, bc, and I must be StringFunction'

    if 'f77' in implementation.itervalues():
        # build F77 module:
        code = """
      subroutine scheme(up, u, um, x, y, nx, ny, Cx2, Cy2, dt2,
     &                  t_old)
      integer nx, ny
      real*8 up(0:nx, 0:ny), u(0:nx, 0:ny), um(0:nx, 0:ny)
      real*8 x(0:nx), y(0:ny)
      real*8 Cx2, Cy2, dt2, t_old
Cf2py intent(in, out) up
      real*8 f
      external f

      do j = 1, ny-1
         do i = 1, nx-1
            up(i,j) = - um(i,j) + 2*u(i,j) + 
     &          Cx2*(u(i-1,j) - 2*u(i,j) + u(i+1,j)) +
     &          Cy2*(u(i,j-1) - 2*u(i,j) + u(i,j+1)) +
     &          dt2*f(x(i),y(j),t_old)
         end do
      end do
      return
      end

      subroutine initcond(u, um, x, y, nx, ny, Cx2, Cy2, dt2)
      integer nx, ny
      real*8 u(0:nx, 0:ny), um(0:nx, 0:ny)
      real*8 x(0:nx), y(0:ny)
      real*8 Cx2, Cy2, dt2, dt
Cf2py intent(in, out) u, um
      real*8 f, bc, ic
      external f, bc, ic

      do j = 0, ny
         do i = 0, nx
            u(i,j) = ic(x(i),y(j))
         end do
      end do
      do j = 1, ny-1
         do i = 1, nx-1
            um(i,j) = u(i,j) +
     &          0.5*Cx2*(u(i-1,j) - 2*u(i,j) + u(i+1,j)) +
     &          0.5*Cy2*(u(i,j-1) - 2*u(i,j) + u(i,j+1)) +
     &          dt2*f(x(i),y(j),0.0D0)
         end do
      end do
C     boundary values:
      dt = sqrt(dt2)
      i = 0
      do j = 0, ny
         um(i,j) = bc(x(i),y(j),dt)
      end do
      j = 0
      do i = 0, nx
         um(i,j) = bc(x(i),y(j),dt)
      end do
      i = nx
      do j = 0, ny
         um(i,j) = bc(x(i),y(j),dt)
      end do
      j = ny
      do i = 0, nx
         um(i,j) = bc(x(i),y(j),dt)
      end do
      return
      end

      subroutine bcond(up, x, y, nx, ny, t)
      integer nx, ny
      real*8 up(0:nx, 0:ny)
      real*8 x(0:nx), y(0:ny)
      real*8 t
Cf2py intent(in, out) up
      real*8 bc
      external bc

      i = 0
      do j = 0, ny
         up(i,j) = bc(x(i),y(j),t)
      end do
      j = 0
      do i = 0, nx
         up(i,j) = bc(x(i),y(j),t)
      end do
      i = nx
      do j = 0, ny
         up(i,j) = bc(x(i),y(j),t)
      end do
      j = ny
      do i = 0, nx
         up(i,j) = bc(x(i),y(j),t)
      end do
      return
      end



%s

%s

%s

%s      
""" % (f.F77_code('f'), bc.F77_code('bc'), I.F77_code('ic'), I.F77_pow())

        f = open('_tmp.f', 'w')
        f.write(code)
        f.close()

        # use old F2PY,  installed as F2PY by hpl:
        cmd = "F2PY -m f77 -c --fcompiler='Gnu' --build-dir tmp2"\
              " -DF2PY_REPORT_ON_ARRAY_COPY=1 _tmp.f"
        print cmd
        shutil.rmtree('tmp2')
        failure, output = system(cmd)
        if failure:
            print 'unsuccessful F77 extension module compilation'
            print output
            sys.exit(1)

        import f77
        
        # turn arrays to column major storage after the init. cond.

    if 'weave' in implementation.itervalues():
        # additional code with f, bc, and I functions:
        extra_code = f.C_code('_f', inline=True) + \
                     bc.C_code('_bc', inline=True) + \
                     I.C_code('_I', inline=True)


                        
    # set initial condition:
    t0 = time.clock()
    t = 0.0
    if implementation['ic'] == 'scalar':
        for i in iseq(0,nx):
            for j in iseq(0,ny):
                u[i,j] = I(x[i], y[j])
        for i in iseq(1,nx-1):
            for j in iseq(1,ny-1):
                um[i,j] = u[i,j] + \
                  0.5*Cx2*(u[i-1,j] - 2*u[i,j] + u[i+1,j]) + \
                  0.5*Cy2*(u[i,j-1] - 2*u[i,j] + u[i,j+1]) + \
                  dt2*f(x[i], y[j], t) 
        # boundary values of um (equals t=dt when du/dt=0)
        i = 0
        for j in iseq(0,ny): um[i,j] = bc(x[i], y[j], t+dt)
        j = 0
        for i in iseq(0,nx): um[i,j] = bc(x[i], y[j], t+dt)
        i = nx
        for j in iseq(0,ny): um[i,j] = bc(x[i], y[j], t+dt)
        j = ny
        for i in iseq(0,nx): um[i,j] = bc(x[i], y[j], t+dt)
    elif implementation['ic'] == 'vectorized':
        # vectorized version:

        # not sure why we need f.vectorize when globals() is
        # supplied in the constructor:
        if isinstance(f, StringFunction):
            f.vectorize(globals())

        u[:,:] = I(xv,yv)  # works for scalar I too...

        um[1:nx,1:ny] = u[1:nx,1:ny] + \
        0.5*Cx2*(u[0:nx-1,1:ny] - 2*u[1:nx,1:ny] + u[2:nx+1,1:ny]) + \
        0.5*Cy2*(u[1:nx,0:ny-1] - 2*u[1:nx,1:ny] + u[1:nx,2:ny+1]) + \
        dt2*f(xv[1:nx,:], yv[:,1:ny], 0.0)
        # scalar f should be ok in all vectorized expressions
        # boundary values (evaluate at t=dt since du/dt=0 at t=0):
        i = 0;  um[i,:] = bc(x[i], y, t+dt)  # works for scalar bc too...
        j = 0;  um[:,j] = bc(x, y[j], t+dt)
        i = nx; um[i,:] = bc(x[i], y, t+dt)
        j = ny; um[:,j] = bc(x, y[j], t+dt)
    elif implementation['ic'] == 'f77':
        u, um = f77.initcond(u, um, x, y, Cx2, Cy2, dt2)
    elif implementation['ic'] == 'weave':
        code = """
int i,j;
for (i=0; i<=nx; i++) {
  for (j=0; j<=ny; j++) {
    u(i,j) = _I(x(i), y(j));
  }
}
for (i=1; i<=nx-1; i++) {
  for (j=1; j<=ny-1; j++) {
    um(i,j) = u(i,j) + \
      0.5*Cx2*(u(i-1,j) - 2*u(i,j) + u(i+1,j)) + \
      0.5*Cy2*(u(i,j-1) - 2*u(i,j) + u(i,j+1)) + \
      dt2*_f(x(i), y(j), t);
  }
}
// boundary values of um (equals t=dt when du/dt=0)
double xv, yv;
i = 0; xv = x(i);
for (j=0; j<=ny; j++) { um(i,j) = _bc(xv, y(j), t+dt); }
j = 0; yv = y(j);
for (i=0; i<=nx; i++) { um(i,j) = _bc(x(i), yv, t+dt); }
i = nx; xv = x(i);
for (j=0; j<=ny; j++) { um(i,j) = _bc(xv, y(j), t+dt); }
j = ny; yv = y(j);
for (i=0; i<=nx; i++) { um(i,j) = _bc(x(i), yv, t+dt); }
"""
        args = ['u', 'um', 'nx', 'ny', 'x', 'y',
                    'Cx2', 'Cy2', 'dt2', 'dt', 't']
        err = weave.inline(code, args,
              type_converters=weave.converters.blitz,
              support_code=extra_code, compiler='gcc')

    t_ic = time.clock() - t0

    if implementation['inner'] == 'f77':
        # turn input arrays to Fortran storage for all arrays
        # that are input arrays in loop subroutine
        # (actually not necessary as up, u, and um are all fed
        # through the f77.loop routine and brought to column
        # major storage in turn - recall um=u, u=up, up=um)
        if implementation.get('storage', 'f77') == 'f77':
            up = asarray(up, order='Fortran')
            u  = asarray(u,  order='Fortran')
            um = asarray(um, order='Fortran')

    if user_action is not None:
        user_action(u, xv, yv, t)  # allow user to plot etc.

    t_inner = 0                    # CPU time inner loops
    t_bc = 0                       # CPU time boundary update
    
    while t <= tstop:
        t_old = t;  t += dt
        if verbose:
            print 'solving (%s version) at t=%g' % \
                  (implementation['inner'], t)

        t0 = time.clock()
        # update all inner points:
        if implementation['inner'] == 'scalar':
            for i in iseq(start=1, stop=nx-1):
                for j in iseq(start=1, stop=ny-1):
                    up[i,j] = - um[i,j] + 2*u[i,j] + \
                       Cx2*(u[i-1,j] - 2*u[i,j] + u[i+1,j]) + \
                       Cy2*(u[i,j-1] - 2*u[i,j] + u[i,j+1]) + \
                       dt2*f(x[i], y[j], t_old)
        elif implementation['inner'] == 'vectorized':
            up[1:nx,1:ny] = - um[1:nx,1:ny] + 2*u[1:nx,1:ny] + \
           Cx2*(u[0:nx-1,1:ny] - 2*u[1:nx,1:ny] + u[2:nx+1,1:ny]) + \
           Cy2*(u[1:nx,0:ny-1] - 2*u[1:nx,1:ny] + u[1:nx,2:ny+1]) + \
           dt2*f(xv[1:nx,:], yv[:,1:ny], t_old)
        elif implementation['inner'] == 'f77':
            up = f77.scheme(up, u, um, x, y, Cx2, Cy2, dt2, t_old)
        elif implementation['inner'] == 'weave':
            code = """
int i,j;
for (i=1; i<=nx-1; i++) {
  for (j=1; j<=ny-1; j++) {
    up(i,j) = -um(i,j) + 2*u(i,j) + \
      Cx2*(u(i-1,j) - 2*u(i,j) + u(i+1,j)) + \
      Cy2*(u(i,j-1) - 2*u(i,j) + u(i,j+1)) + \
      dt2*_f(x(i), y(j), t_old);
  }
}
"""
            args = ['up', 'u', 'um', 'nx', 'ny', 'x', 'y',
                    'Cx2', 'Cy2', 'dt2', 't_old']
            err = weave.inline(code, args,
                  type_converters=weave.converters.blitz,
                  support_code=extra_code, compiler='gcc')


            #id_u = id(u); id_um = id(um)
            #up,u,um = f77.loop(up, u, um, f_array, Cx2, Cy2, dt2)
            #print 'u changed:', id_u!=id(u),
            #print 'um changed:', id_um!=id(um),
        else:
            raise ValueError, 'version=%s' % implementation['inner']
        t_inner += time.clock() - t0

        t0 = time.clock()
        # insert boundary conditions:
        if implementation['bc'] == 'scalar':
            i = 0
            for j in iseq(0,ny): up[i,j] = bc(x[i], y[j], t)
            j = 0
            for i in iseq(0,nx): up[i,j] = bc(x[i], y[j], t)
            i = nx
            for j in iseq(0,ny): up[i,j] = bc(x[i], y[j], t)
            j = ny
            for i in iseq(0,nx): up[i,j] = bc(x[i], y[j], t)
        elif implementation['bc'] == 'vectorized':
            i = 0;  up[i,:] = bc(x[i], y, t)
            j = 0;  up[:,j] = bc(x, y[j], t)
            i = nx; up[i,:] = bc(x[i], y, t)
            j = ny; up[:,j] = bc(x, y[j], t)
        elif implementation['ic'] == 'f77':
            up = f77.bcond(up, x, y, t)
        elif implementation['bc'] == 'weave':
            code = """
// boundary values of u
double xv, yv; int i, j;
i = 0; xv = x(i);
for (j=0; j<=ny; j++) { up(i,j) = _bc(xv, y(j), t); }
j = 0; yv = y(j);
for (i=0; i<=nx; i++) { up(i,j) = _bc(x(i), yv, t); }
i = nx; xv = x(i);
for (j=0; j<=ny; j++) { up(i,j) = _bc(xv, y(j), t); }
j = ny; yv = y(j);
for (i=0; i<=nx; i++) { up(i,j) = _bc(x(i), yv, t); }
"""
            args = ['up', 'nx', 'ny', 'x', 'y', 't']
            err = weave.inline(code, args,
                type_converters=weave.converters.blitz,
                support_code=extra_code, compiler='gcc')
        t_bc += time.clock() - t0
        
        if user_action is not None:
            user_action(up, xv, yv, t)
        # update data structures for next step:
        um, u, up = u, up, um
        #tmp = um; um = u; u = up; up = tmp
        # safer and slower: um = u.copy(); u = up.copy()

    # dt might be computed in this function
    return dt, t_ic, t_inner, t_bc
示例#9
0
def make_f77(f, bc, I):
    code = """
      subroutine scheme_f77(up, u, um, x, y, t, nx, ny, Cx2, Cy2,
     &                      dt2, t_old)
      integer nx, ny
      real*8 up(0:nx, 0:ny), u(0:nx, 0:ny), um(0:nx, 0:ny)
      real*8 x(0:nx), y(0:ny)
      real*8 Cx2, Cy2, dt2, t, t_old
Cf2py intent(in, out) up
      real*8 f
      external f

      do j = 1, ny-1
         do i = 1, nx-1
            up(i,j) = - um(i,j) + 2*u(i,j) + 
     &          Cx2*(u(i-1,j) - 2*u(i,j) + u(i+1,j)) +
     &          Cy2*(u(i,j-1) - 2*u(i,j) + u(i,j+1)) +
     &          dt2*f(x(i),y(j),t_old)
         end do
      end do
      return
      end

      subroutine ic_f77(u, um, x, y, nx, ny, Cx2, Cy2, dt)
      integer nx, ny
      real*8 u(0:nx, 0:ny), um(0:nx, 0:ny)
      real*8 x(0:nx), y(0:ny)
      real*8 Cx2, Cy2, dt, dt2
Cf2py intent(in, out) u, um
      real*8 f, ic
      external f, ic

      dt2 = dt*dt
      do j = 0, ny
         do i = 0, nx
            u(i,j) = ic(x(i),y(j))
         end do
      end do
      do j = 1, ny-1
         do i = 1, nx-1
            um(i,j) = u(i,j) +
     &          0.5*Cx2*(u(i-1,j) - 2*u(i,j) + u(i+1,j)) +
     &          0.5*Cy2*(u(i,j-1) - 2*u(i,j) + u(i,j+1)) +
     &          dt2*f(x(i),y(j),0.0D0)
         end do
      end do
C     boundary values:
      call bc_f77(um, x, y, nx, ny, dt)
      return
      end

      subroutine bc_f77(up, x, y, nx, ny, t)
      integer nx, ny
      real*8 up(0:nx, 0:ny)
      real*8 x(0:nx), y(0:ny)
      real*8 t
Cf2py intent(in, out) up
      real*8 bc
      external bc

      i = 0
      do j = 0, ny
         up(i,j) = bc(x(i),y(j),t)
      end do
      j = 0
      do i = 0, nx
         up(i,j) = bc(x(i),y(j),t)
      end do
      i = nx
      do j = 0, ny
         up(i,j) = bc(x(i),y(j),t)
      end do
      j = ny
      do i = 0, nx
         up(i,j) = bc(x(i),y(j),t)
      end do
      return
      end


%s

%s

%s

%s      
""" % (f.F77_code('f'), bc.F77_code('bc'), I.F77_code('ic'), I.F77_pow())

    f = open('_tmp.f', 'w')
    f.write(code)
    f.close()

    cmd = "f2py -m f77 -c --fcompiler='gfortran' --build-dir tmp2"\
          " -DF2PY_REPORT_ON_ARRAY_COPY=1 _tmp.f"
    print cmd
    os.system('rm -rf tmp2')
    failure, output = system(cmd)
    if failure:
        print 'unsuccessful F77 extension module compilation'
        print output
        sys.exit(1)
示例#10
0
os.mkdir('tmp')
filelist = glob.glob('*.py')
for file in filelist: shutil.copy(file,'tmp')
shutil.rmtree('tmp')

# redirect output from a command into a variable:
cmd = "perl -pe '' hw.py"
resfile = os.popen(cmd)
res = resfile.readlines()
print "Output of the command " + cmd + " was\n"
for line in res:
    print line,   # the comma prevents extra newline
import commands
from scitools.misc import system
failure, res = system(cmd)
print res
    
    

#----------------------------------------------------------------------------

name = "/usr/home/hpl/scripting/perl/intro/hw.pl"
[head,tail] = os.path.split(name)
print "file=",name
print "head=",head
print "tail=",tail
basename = os.path.basename(name)
dirname  = os.path.dirname(name)
print "dirname =",dirname
print "basename=",basename