Пример #1
0
    def jacobi_weaver(self):
        iter_n = 0
        print "Doing Jacobi Weaver"
        field = self.flow.scalar_field

        while (iter_n < self.max_time_steps):
            expr = "field[1:-1, 1:-1] = (field[2:, 1:-1] "\
                                                          "+ field[:-2, 1:-1]+"\
                                                          "field[1:-1, 2:] +"\
                                                          "field[1:-1, :-2] )/4."

            weave.blitz(expr, check_size=0)
            #Toroidal conditions
            if self.toroidal:
                field[:, 0] = field[:, self.flow.n_x - 2]
                field[:, self.flow.n_x - 1] = field[:, 1]

            iter_n = iter_n + 1
            self.flow.scalar_field = field
            if iter_n % 10 == 0:
                print "iteration ", iter_n, "error ", self.error
                if self.check_convergence():

                    print "total iterations: ", iter_n
                    break

        if iter_n == self.max_time_steps:
            print "Not converged, error ", self.error
Пример #2
0
 def jacobi_weaver(self): 
     iter_n = 0
     print "Doing Jacobi Weaver"
     field = self.flow.scalar_field
     
     while (iter_n < self.max_time_steps):
         expr = "field[1:-1, 1:-1] = (field[2:, 1:-1] "\
                                                       "+ field[:-2, 1:-1]+"\
                                                       "field[1:-1, 2:] +"\
                                                       "field[1:-1, :-2] )/4."                                       
         
         weave.blitz(expr, check_size=0)
         #Toroidal conditions
         if self.toroidal:
             field[:,0] = field[:,self.flow.n_x - 2]
             field[:,self.flow.n_x -1] = field[:,1]
         
         iter_n = iter_n + 1
         self.flow.scalar_field = field
         if iter_n % 10 == 0:
             print "iteration ", iter_n, "error ", self.error
             if self.check_convergence():
                 
                 print "total iterations: ", iter_n
                 break
             
     if iter_n == self.max_time_steps:
         print "Not converged, error ", self.error   
def solve(t0, t1, dt, n, m, u_initial, f, nu, verbose=False):
    """
    Function which, using weave.blitz, solves the heat equation for a substance 
    with a specific viscosity across a 2D domain with a time-independent heat 
    source and the boundary condition u=0 at all boundaries.

    Parameters
    ----------
    t0 : float
        Start time for simulation.
    t1 : float
        End time for simulation. (If t1-t0 isn't a multiple of dt, 
        the end time is set to t0 + the nearest multiple of dt)
    dt : float
        The size of the time step
    n : int
        The spatial resolution in the y-dimension (x-dimension in plot)
    m : int
        The spatial resolution in the x-dimension (y-dimension in plot)
    u_initial : 2D-array
        The initial temperature distribution of the domain
    f : 2D-array
        The time-independent heat source
    nu : float
        The viscosity ("floatiness") of the substance, which determines 
        how fast heat spreads in the system.

    Returns
    -------
    u : 2D-array
        The temperature distribution of the domain at the end time.
    t : float
        The end time of the simulation. (If t1-t0 isn't a multiple of dt, 
        this is set to t0 + the nearest multiple of dt)
    """
    u = u_initial
    u_new = u_initial.copy()    
    Nt = int(round((t1 - t0) / float(dt)))      #number of time points
    t = t0 + Nt*dt                              #end time
    for it in xrange(1, Nt+1):
        formula="u_new[1:m-1,1:n-1] = u[1:m-1,1:n-1] + dt*(nu*(u[0:m-2,1:n-1]" \
                                    "+ u[1:m-1,0:n-2] - 4*u[1:m-1,1:n-1]" \
                                    "+ u[1:m-1,2:n] + u[2:m,1:n-1])" \
                                    "+ f[1:m-1,1:n-1])"
        weave.blitz(formula, 
                    check_size=0,    #improves speed significantly
                    extra_compile_args=['-O3',             #optimize loops
                                        '-w',              #surpress warnings
                                        '-march=native'    #optimize for processor
                                       ]
                    )

        #swap pointers
        u_new, u = u, u_new
        if verbose and it % (Nt/100) == 0: 
            sys.stdout.write("\rt = %6.0f (%3.0f%%)" % (t0 + it*dt, it*1E2/Nt))
            sys.stdout.flush()
    if verbose:
        print
    return u, t
Пример #4
0
def f_gauss2db(p, X, Y):
    """2D Gaussian model function with linear background - parameter vector [A, x0, y0, sigma, background, lin_x, lin_y]"""
    A, x0, y0, s, b, b_x, b_y = p
    ret = X
    expr = 'ret = A*numpy.exp(-((X-x0)**2 + (Y - y0)**2)/(2*s**2)) + b + b_x*X + b_y*Y'
    weave.blitz(expr, check_size=0)
    return ret
Пример #5
0
    def blitzAdvance(self, dt=0.0, user_action = None):        
 	"""Takes a time step using a numeric expression that is converted to 
        Blitz using weave."""        
	u = self.grid.u
	u_1 = self.grid.u_1
	u_2 = self.grid.u_2
	V_a = self.grid.V_a
	qpx = self.grid.qpx
	qmx = self.grid.qmx
	qpy = self.grid.qpy
	qmy = self.grid.qmy        
	f_a = self.grid.f_a
	f_a[:,:] = self.f(self.grid.xv, self.grid.yv, self.t)
	
	# Define help variables
    	Cx2 = float(self.Cx2)
    	Cy2 = float(self.Cy2)
    	dt2 = float(self.dt2)
    	B1 = float(self.B1)
    	B2 = float(self.B2)
	
	# Boundary condition du/dn=0
    	u_1[:,0]   = u_1[:,1]
    	u_1[:,-1] = u_1[:,-2]
    	u_1[0,:]   = u_1[1,:]
    	u_1[-1,:] = u_1[-2,:]
	
        # The actual iteration
	expr = "u[1:-1,1:-1] = B1*(2*u_1[1:-1,1:-1] - B2*u_2[1:-1,1:-1] + Cx2*(qpx*(u_1[2:,1:-1] - u_1[1:-1,1:-1]) - qmx*(u_1[1:-1,1:-1] - u_1[:-2,1:-1])) + Cy2*(qpy*(u_1[1:-1,2:] - u_1[1:-1,1:-1]) - qmy*(u_1[1:-1,1:-1] - u_1[1:-1,:-2])) + dt2*f_a)"
        weave.blitz(expr, check_size=0)
Пример #6
0
 def blitzStepper(self, nx, ny, u, uo, nu):
     """ time-steps implemented using numpy expression dispatched via blitz"""
     from scipy import weave
     # define expression (same one as for numpyStepper)
     expr = "u[1:-1, 1:-1] = uo[1:-1, 1:-1] + ( nu * ( uo [0:-2, 1:-1] + uo [2:, 1:-1] + " \
            "                                   uo [1:-1, 0:-2] + uo [1:-1, 2:]" \
            "                                   - 4.0 * uo [1:-1, 1:-1] ) )"
     weave.blitz(expr, check_size=0)
Пример #7
0
 def convert_arr_to_corners(cls, arr):
     """Take an arr in x1,y1,w,h format, and return arr in x1,y1,x2,y2 format."""
     ret_arr = np.copy(arr)
     if arr.ndim > 1:
         expr = "ret_arr[:,2] = arr[:,2]+arr[:,0]-1;"+\
                "ret_arr[:,3] = arr[:,3]+arr[:,1]-1"
         blitz(expr)
     else:
         ret_arr[2] = arr[0] + arr[2] - 1
         ret_arr[3] = arr[1] + arr[3] - 1
     return ret_arr
Пример #8
0
 def convert_arr_from_corners(cls, arr):
   """Take an arr in x1,y1,x2,y2 format, and return arr in x,y,w,h format."""
   ret_arr = np.copy(arr)
   if arr.ndim>1:
     expr = "ret_arr[:,2] = arr[:,2]-arr[:,0]+1;"+\
            "ret_arr[:,3] = arr[:,3]-arr[:,1]+1"
     blitz(expr)
   else:
     ret_arr[2] = -arr[0]+arr[2]+1
     ret_arr[3] = -arr[1]+arr[3]+1
   return ret_arr
Пример #9
0
 def convert_arr_to_corners(cls, arr):
     """Take an arr in x1,y1,w,h format, and return arr in x1,y1,x2,y2 format."""
     ret_arr = np.copy(arr)
     if arr.ndim > 1:
         expr = "ret_arr[:,2] = arr[:,2]+arr[:,0]-1;" +\
             "ret_arr[:,3] = arr[:,3]+arr[:,1]-1"
         blitz(expr, check_size=0)
     else:
         ret_arr[2] = arr[0] + arr[2] - 1
         ret_arr[3] = arr[1] + arr[3] - 1
     return ret_arr
    def blitzTimeStep(self, dt=0.0):
        """Takes a time step using a numeric expression that has been
        blitzed using weave."""
        g = self.grid
        dx2, dy2 = g.dx ** 2, g.dy ** 2
        dnr_inv = 0.5 / (dx2 + dy2)
        u = g.u
        g.old_u = u.copy()

        # The actual iteration
        expr = "u[1:-1, 1:-1] = ((u[0:-2, 1:-1] + u[2:, 1:-1])*dy2 + " "(u[1:-1,0:-2] + u[1:-1, 2:])*dx2)*dnr_inv"
        weave.blitz(expr, check_size=0)

        return g.computeError()
Пример #11
0
    def blitzTimeStep(self, dt=0.0):
        """Takes a time step using a numeric expression that has been
        blitzed using weave."""
        g = self.grid
        dx2, dy2 = g.dx**2, g.dy**2
        dnr_inv = 0.5 / (dx2 + dy2)
        u = g.u
        g.old_u = u.copy()

        # The actual iteration
        expr = "u[1:-1, 1:-1] = ((u[0:-2, 1:-1] + u[2:, 1:-1])*dy2 + " "(u[1:-1,0:-2] + u[1:-1, 2:])*dx2)*dnr_inv"
        weave.blitz(expr, check_size=0)

        return g.computeError()
Пример #12
0
def test_blitz_bug():
    """Assignment to arr[i:] used to fail inside blitz expressions."""
    N = 4
    expr_buggy = 'arr_blitz_buggy[{0}:] = arr[{0}:]'
    expr_not_buggy = 'arr_blitz_not_buggy[{0}:{1}] = arr[{0}:]'
    random.seed(7)
    arr = random.randn(N)
    sh = arr.shape[0]
    for lim in [0, 1, 2]:
        arr_blitz_buggy, arr_blitz_not_buggy, arr_np = zeros(N), zeros(N), zeros(N)
        blitz(expr_buggy.format(lim))
        blitz(expr_not_buggy.format(lim, 'sh'))
        arr_np[lim:] = arr[lim:]
        assert_allclose(arr_blitz_buggy, arr_np)
        assert_allclose(arr_blitz_not_buggy, arr_np)
def test_blitz_bug():
    """Assignment to arr[i:] used to fail inside blitz expressions."""
    N = 4
    expr_buggy = 'arr_blitz_buggy[{0}:] = arr[{0}:]'
    expr_not_buggy = 'arr_blitz_not_buggy[{0}:{1}] = arr[{0}:]'
    random.seed(7)
    arr = random.randn(N)
    sh = arr.shape[0]
    for lim in [0, 1, 2]:
        arr_blitz_buggy, arr_blitz_not_buggy, arr_np = zeros(N), zeros(
            N), zeros(N)
        blitz(expr_buggy.format(lim))
        blitz(expr_not_buggy.format(lim, 'sh'))
        arr_np[lim:] = arr[lim:]
        assert_allclose(arr_blitz_buggy, arr_np)
        assert_allclose(arr_blitz_not_buggy, arr_np)
Пример #14
0
    def simulateBlitz(self, indata):
        """ Standard Simulation, with weave.blitz.
        """
        simsteps = indata.shape[1]
        outdata = np.zeros(indata.shape)

        x = self.x
        W = self.W
        Win = self.Win
        Wout = self.Wout

        expr = """
for n in range(simsteps):
    x = np.dot(W, x)
    x += np.dot(Win, indata[:, n])
    x = np.tanh(x)
    outdata[:,n] = np.dot(Wout, np.r_[x,indata[:,n]] )
"""
        weave.blitz(expr, check_size=0)

        return outdata
def heat_equation_cpass(t0,t1,dt,n,m,u,f,nu):
    
    global uList
    global uNew
    global fList
   
    
    shape=(n,m)
    uVal=u
    fVal=f
    dty=float
    
    uList=np.empty(shape,dtype=dty)
    uList.fill(uVal)
   # print uList
   
    uNew=uList
   
    
    fList=np.empty(shape,dtype=dty)
    fList.fill(fVal)
  #  print fList
    temp= uList
    
 
    tstart= time.time()
    for temp in range(t0,int(t1/dt)):
        
        expr = "uNew[1:-1, 1:-1] = uList[1:-1, 1:-1] +dt*(nu* uList[:-2, 1:-1]+ nu*uList[1:-1, :-2]-4*nu*uList[1:-1, 1:-1]+nu*uList[1:-1, 2:]+ nu*uList[2:, 1:-1]+fList[1:-1, 1:-1])"   
        weave.blitz(expr)
    
    
    
    tfinish = time.time()   
   
    print "Value at u[25][50] :", uNew[25][50]
    print "max with numpy array uNew" , np.nanmax(uNew)
    print "Total time using numpy and weave: ", tfinish-tstart, "s"
    return uNew
Пример #16
0
#!/usr/bin/env python
"""Simple weave.blitz examples."""

import numpy as N
import scipy as S
from scipy import weave

a = N.arange(10)
x = N.empty_like(a)
weave.blitz("x=a+2*a*a")
print x
print x - (a + 2 * a * a)
Пример #17
0
def minc_test(input, method, output):
   # create a new mihandle and open a volume
   starttime = time.clock()
   test = mihandle()
   libminc.miopen_volume(input, 1, test)
   print "Opening volume took %.5f seconds" % (time.clock() - starttime)
   
   # define a location, a voxel, and get that location from the mihandle
   l = location(0,0,0)
   v = voxel()
   libminc.miget_real_value(test, l, 3, v)
   print "Voxel: %f" % v.value
   
   # get volume dimensions and their sizes
   d = dimensions(0,0,0)
   s = int_sizes(0,0,0)
   libminc.miget_volume_dimensions(test, MI_DIMCLASS_SPATIAL, MI_DIMATTR_ALL,
				MI_DIMORDER_FILE, 3, d)
   libminc.miget_dimension_sizes(d, 3, s)
   print "sizes: %d %d %d " % (s[0], s[1], s[2])
   
   # get a hyperslab of the whole volume as numpy array
   start = long_sizes(0,0,0)
   count = long_sizes(s[0],s[1],s[2])

   narr = ascontiguousarray(zeros(s[0] * s[1] * s[2], dtype='int32'))

   print narr[0]
   starttime = time.clock()
#libminc.miget_real_value_hyperslab(test, 5, start, count, 
#				   narr.ctypes.data_as(POINTER(c_float)))
   libminc.miget_hyperslab_normalized(test, 4, start, count,
				      c_double(-2147483648),
				      c_double(2147483647),
				      narr.ctypes.data_as(POINTER(c_int)))
   print "Getting hyperslab took %.5f seconds" % (time.clock() - starttime)
   print narr[100000]
   # reshape the numpy array to be a 3D array like the volume
   print narr[0]
   print narr.shape
   
   narr.shape = (s[0],s[1],s[2])
   print narr.shape
   print narr[0,0,0]
   
   
   # cute trick - smooth the volume by iterative neighbourhood averages
   print "computing ten neighbourhood averages using %s method" % method
   times = arange(10, dtype="double")
   for i in range(10):
      starttime = time.clock()
      if method == "numpy":
	 narr[1:-1,1:-1,1:-1] = (narr[0:-2,1:-1,1:-1] + 
				 narr[1:-1,0:-2,1:-1] + 
				 narr[1:-1,1:-1,0:-2] + 
				 narr[2:,1:-1,1:-1] + 
				 narr[1:-1,2:,1:-1] + 
				 narr[1:-1,1:-1,2:]) / 6
      elif method == "blitz":
	 code = "narr[1:-1,1:-1,1:-1] = (narr[0:-2,1:-1,1:-1] + "\
	     "narr[1:-1,0:-2,1:-1] + "\
	     "narr[1:-1,1:-1,0:-2] + "\
	     "narr[2:,1:-1,1:-1] + "\
	     "narr[1:-1,2:,1:-1] + "\
	     "narr[1:-1,1:-1,2:]) / 6"
	 weave.blitz(code, check_size=0)
      elif method == "weave":
	 code = """
#line 68 "pyminc_test2.py"
for (int x=1; x<nx-1; ++x) {
  for (int y=1; y<ny-1; ++y) {
    for (int z=1; z<nz-1; ++z) {
       narr(x,y,z) = (narr(x-1,y,z) + narr(x+1,y,z) + 
                      narr(x,y-1,z) + narr(x,y+1,z) + 
                      narr(x,y,z-1) + narr(x,y,z+1)) / 6;
    }
  }
}
"""
	 nx,ny,nz = s[0],s[1],s[2]
	 weave.inline(code, ['narr', 'nx', 'ny', 'nz'], 
		      type_converters=converters.blitz,
		      compiler="gcc")

      times[i] = time.clock() - starttime
      print "Iterations %d took %.3f seconds" % (i,times[i])

   print "done averaging. Took a total of %.3f seconds, averaging %.3f seconds" % (sum(times), average(times))

   d_new_tmp = [0,0,0]
   for i in range(3):
      d_new_tmp[i] = c_void_p()
      libminc.micopy_dimension(d[i], d_new_tmp[i])

   d_new = dimensions(d_new_tmp[0], d_new_tmp[1], d_new_tmp[2])

   new_volume = mihandle()
   print "before volume"
   starttime = time.clock()
   libminc.micreate_volume(output, 3, d_new, MI_TYPE_UBYTE, MI_CLASS_REAL, 
			   None, new_volume)
   libminc.micreate_volume_image(new_volume)
   print "after volume"
   vmin = 0.0
   vmax = 255.0
   rmax = narr.max()
   rmin = narr.min()
   print "max and min", rmax, rmin
   out_array = array( (((narr+0.0) - rmin)/(rmax-rmin)*(vmax-vmin)) + vmin, dtype='ubyte')
   print out_array.shape
   libminc.miset_volume_valid_range(new_volume, 255, 0)
   libminc.miset_volume_range(new_volume, narr.max(), narr.min())
   print "Creating new volume took %.5f seconds" % (time.clock() - starttime)
   print "before setting hyperslab"
   starttime = time.clock()
   dim_1 = s[0] - 1
   dim_2 = s[1] - 1
   dim_3 = s[2] - 1
   print narr[dim_1,dim_2,dim_3]
   print (((narr[dim_1,dim_2,dim_3] - rmin)/(rmax-rmin)*(vmax*vmin)) + vmin)
   print out_array[dim_1,dim_2,dim_3], out_array.max(), out_array.min(), average(out_array)
   print narr.dtype, out_array.dtype
   print out_array
#libminc.miset_real_value_hyperslab(new_volume, 4, start, count,
#				   narr.ctypes.data_as(POINTER(c_int)))
   libminc.miset_voxel_value_hyperslab(new_volume, MI_TYPE_UBYTE,
				       start, count,
				       out_array.ctypes.data_as(POINTER(c_ubyte)))
   print "Setting hyperslab took %.5f seconds" % (time.clock() - starttime)
   libminc.miclose_volume(new_volume)
Пример #18
0
def blitz(p):
    e2 = np.zeros((p.shape[0] - 2, p.shape[1] - 2), np.float)
    weave.blitz("e2 = p[:-2,1:-1]-p[2:,1:-1]+p[1:-1,:-2]-p[1:-1,2:]")
    return e2
N = 1000000

a = arange(N,dtype=float64)
b = arange(N,dtype=float64)
c = arange(N,dtype=float64)
d = arange(N,dtype=float64)

result = empty(N,dtype=float64)

t1= time.clock()
result = a + b*(c-d)
t2=time.clock()
numpy_time = t2-t1

t1= time.clock()
weave.blitz("result = a+b*(c-d)")
t2=time.clock()
blitz_time = t2-t1
print N, numpy_time, blitz_time, numpy_time/blitz_time


code = """
       for(int i=0;i<Na[0];i++)
       {
           result[i] = a[i]+b[i]*(c[i]-d[i]);
       }
       """


t1= time.clock()
weave.inline(code,['a','b','c','d','result'], compiler='gcc')
                    + img[1:-1 , :-2]  # top
                    + img[1:-1 ,2:  ]  # bottom
                    ) / 5.0"""

import time
t1 = time.time()
for i in range(10):
    exec(expr)
t2 = time.time()
numpy_time = t2 - t1
numpy_avg_img = avg_img

avg_img = empty((img.shape[0] - 2, img.shape[1] - 2), dtype=float64)

# Run it once so that it gets compiled.
weave.blitz(expr)

t1 = time.time()
for i in range(10):
    weave.blitz(expr)
t2 = time.time()
blitz_time = t2 - t1
blitz_avg_img = avg_img

avg_img = empty((img.shape[0] - 2, img.shape[1] - 2), dtype=float64)
code = """for (int i=0; i<Navg_img[0];i++)
          { 
            for (int j=0; j<Navg_img[1];j++)  
            {
              AVG_IMG2(i,j) =(  IMG2(i+1 ,j+1)  // center
                              + IMG2(i ,  j+1)  // left
Пример #21
0
#!/usr/bin/env python
"""Simple weave.blitz examples."""

import numpy as N
import scipy as S
from scipy import weave

a = N.arange(10)
x = N.empty_like(a)
weave.blitz('x=a+2*a*a')
print x
print x - (a + 2 * a * a)
Пример #22
0
def minc_test(input, method, output):

    if method in ["weave", "blitz"]:
        try:
            from scipy import weave
            from scipy.weave import converters
        except ImportError:
            print("method '%s' not available: " % method, file=sys.stderr)
            raise

    # create a new mihandle and open a volume
    starttime = time.clock()
    test = mihandle()
    libminc.miopen_volume(input, 1, test)
    print("Opening volume took %.5f seconds" % (time.clock() - starttime))

    # define a location, a voxel, and get that location from the mihandle
    l = location(0, 0, 0)
    v = voxel()
    libminc.miget_real_value(test, l, 3, v)
    print("Voxel: %f" % v.value)

    # get volume dimensions and their sizes
    d = dimensions(0, 0, 0)
    s = int_sizes(0, 0, 0)
    libminc.miget_volume_dimensions(test, MI_DIMCLASS_SPATIAL, MI_DIMATTR_ALL,
                                    MI_DIMORDER_FILE, 3, d)
    libminc.miget_dimension_sizes(d, 3, s)
    print("sizes: %d %d %d " % (s[0], s[1], s[2]))

    # get a hyperslab of the whole volume as numpy array
    start = long_sizes(0, 0, 0)
    count = long_sizes(s[0], s[1], s[2])

    narr = ascontiguousarray(zeros(s[0] * s[1] * s[2], dtype='int32'))

    print(narr[0])
    starttime = time.clock()
    #libminc.miget_real_value_hyperslab(test, 5, start, count,
    #                                   narr.ctypes.data_as(POINTER(c_float)))
    libminc.miget_hyperslab_normalized(test, 4, start, count,
                                       c_double(-2147483648),
                                       c_double(2147483647),
                                       narr.ctypes.data_as(POINTER(c_int)))
    print("Getting hyperslab took %.5f seconds" % (time.clock() - starttime))
    print(narr[100000])
    # reshape the numpy array to be a 3D array like the volume
    print(narr[0])
    print(narr.shape)

    narr.shape = (s[0], s[1], s[2])
    print(narr.shape)
    print(narr[0, 0, 0])

    # cute trick - smooth the volume by iterative neighbourhood averages
    print("computing ten neighbourhood averages using %s method" % method)
    times = arange(10, dtype="double")
    for i in range(10):
        starttime = time.clock()
        if method == "numpy":
            narr[1:-1, 1:-1,
                 1:-1] = (narr[0:-2, 1:-1, 1:-1] + narr[1:-1, 0:-2, 1:-1] +
                          narr[1:-1, 1:-1, 0:-2] + narr[2:, 1:-1, 1:-1] +
                          narr[1:-1, 2:, 1:-1] + narr[1:-1, 1:-1, 2:]) / 6
        elif method == "blitz":
            code = "narr[1:-1,1:-1,1:-1] = (narr[0:-2,1:-1,1:-1] + "\
                                            "narr[1:-1,0:-2,1:-1] + "\
                                            "narr[1:-1,1:-1,0:-2] + "\
                                            "narr[2:,1:-1,1:-1] + "\
                                            "narr[1:-1,2:,1:-1] + "\
                                            "narr[1:-1,1:-1,2:]) / 6"
            weave.blitz(code, check_size=0)
        elif method == "weave":
            code = """
#line 90 "pyminc_test2.py"
for (int x=1; x<nx-1; ++x) {
  for (int y=1; y<ny-1; ++y) {
    for (int z=1; z<nz-1; ++z) {
       narr(x,y,z) = (narr(x-1,y,z) + narr(x+1,y,z) + 
                      narr(x,y-1,z) + narr(x,y+1,z) + 
                      narr(x,y,z-1) + narr(x,y,z+1)) / 6;
    }
  }
}
"""
            nx, ny, nz = s[0], s[1], s[2]
            weave.inline(code, ['narr', 'nx', 'ny', 'nz'],
                         type_converters=converters.blitz,
                         compiler="gcc")
        else:
            raise ValueError("unknown method: %s" % method)

        times[i] = time.clock() - starttime
        print("Iterations %d took %.3f seconds" % (i, times[i]))

    print(
        "done averaging. Took a total of %.3f seconds, averaging %.3f seconds"
        % (sum(times), average(times)))

    d_new_tmp = [0, 0, 0]
    for i in range(3):
        d_new_tmp[i] = c_void_p()
        libminc.micopy_dimension(d[i], d_new_tmp[i])

    d_new = dimensions(d_new_tmp[0], d_new_tmp[1], d_new_tmp[2])

    new_volume = mihandle()
    print("before volume")
    starttime = time.clock()
    libminc.micreate_volume(output, 3, d_new, MI_TYPE_UBYTE, MI_CLASS_REAL,
                            None, new_volume)
    libminc.micreate_volume_image(new_volume)
    print("after volume")
    vmin = 0.0
    vmax = 255.0
    rmax = narr.max()
    rmin = narr.min()
    print("max and min", rmax, rmin)
    out_array = array(
        (((narr + 0.0) - rmin) / (rmax - rmin) * (vmax - vmin)) + vmin,
        dtype='ubyte')
    print(out_array.shape)
    libminc.miset_volume_valid_range(new_volume, 255, 0)
    libminc.miset_volume_range(new_volume, narr.max(), narr.min())
    print("Creating new volume took %.5f seconds" % (time.clock() - starttime))
    print("before setting hyperslab")
    starttime = time.clock()
    dim_1 = s[0] - 1
    dim_2 = s[1] - 1
    dim_3 = s[2] - 1
    print(narr[dim_1, dim_2, dim_3])
    print((((narr[dim_1, dim_2, dim_3] - rmin) / (rmax - rmin) *
            (vmax * vmin)) + vmin))
    print(out_array[dim_1, dim_2, dim_3], out_array.max(), out_array.min(),
          average(out_array))
    print(narr.dtype, out_array.dtype)
    print(out_array)
    #libminc.miset_real_value_hyperslab(new_volume, 4, start, count,
    #                                   narr.ctypes.data_as(POINTER(c_int)))
    libminc.miset_voxel_value_hyperslab(
        new_volume, MI_TYPE_UBYTE, start, count,
        out_array.ctypes.data_as(POINTER(c_ubyte)))
    print("Setting hyperslab took %.5f seconds" % (time.clock() - starttime))
    libminc.miclose_volume(new_volume)
                    + img[1:-1 , :-2]  # top
                    + img[1:-1 ,2:  ]  # bottom
                    ) / 5.0"""

import time
t1 = time.time()
for i in range(10):
    exec(expr)
t2 = time.time()                         
numpy_time = t2-t1
numpy_avg_img = avg_img

avg_img = empty((img.shape[0]-2, img.shape[1]-2), dtype=float64)

# Run it once so that it gets compiled.
weave.blitz(expr)

t1 = time.time()
for i in range(10):
    weave.blitz(expr)
t2 = time.time()                         
blitz_time = t2-t1
blitz_avg_img = avg_img

avg_img = empty((img.shape[0]-2, img.shape[1]-2), dtype=float64)
code = """for (int i=0; i<Navg_img[0];i++)
          { 
            for (int j=0; j<Navg_img[1];j++)  
            {
              AVG_IMG2(i,j) =(  IMG2(i+1 ,j+1)  // center
                              + IMG2(i ,  j+1)  // left
Пример #24
0
# Start the numerical solution of the problem
# Convergence criteria, Residual has to fall below Rtol
R = T[1:-1, 1:-1].copy()

while Rmax > Rtol:

    # Intialise Residual for every iteration
    Aw = k * dy / dx
    Ae = k * dy / dx
    An = k * dx / dy
    As = k * dx / dy
    Ap = Aw + Ae + An + As
    b = S * dx * dy

    e = "T[1:-1,1:-1] = (Aw*T[1:-1,:-2] + Ae*T[1:-1,2:] + An*T[2:,1:-1] + As*T[:-2,1:-1] + b)/Ap"
    weave.blitz(e, check_size=0)
    e = "R = Aw*T[1:-1,:-2] + Ae*T[1:-1,2:] + An*T[2:,1:-1] + As*T[:-2,1:-1] + b - Ap*T[1:-1,1:-1]"
    weave.blitz(e, check_size=0)
    e = "T[:,n] = Ts"
    weave.blitz(e, check_size=0)
    e = "T[n,:] = Ts"
    weave.blitz(e, check_size=0)
    e = "T[:,0] = T[:,1]"
    weave.blitz(e, check_size=0)
    e = "T[0,:] = T[1,:]"
    weave.blitz(e, check_size=0)

    R = abs(R)
    Rmax = R.max()

    # Solve the matrix and keep track on the residuals
def blitz(p):
    e2 = np.zeros((p.shape[0]-2, p.shape[1]-2), np.float)
    weave.blitz("e2 = p[:-2,1:-1]-p[2:,1:-1]+p[1:-1,:-2]-p[1:-1,2:]")
    return e2
Пример #26
0
#Start the numerical solution of the problem
#Convergence criteria, Residual has to fall below Rtol
R = T[1:-1,1:-1].copy()

while Rmax > Rtol:
  
  #Intialise Residual for every iteration
  Aw = k*dy/dx
  Ae = k*dy/dx
  An = k*dx/dy
  As = k*dx/dy
  Ap = Aw + Ae + An + As
  b = S*dx*dy
    
  e = "T[1:-1,1:-1] = (Aw*T[1:-1,:-2] + Ae*T[1:-1,2:] + An*T[2:,1:-1] + As*T[:-2,1:-1] + b)/Ap"
  weave.blitz(e, check_size=0)
  e = "R = Aw*T[1:-1,:-2] + Ae*T[1:-1,2:] + An*T[2:,1:-1] + As*T[:-2,1:-1] + b - Ap*T[1:-1,1:-1]"
  weave.blitz(e, check_size=0)
  e = "T[:,n] = Ts"
  weave.blitz(e, check_size=0)
  e = "T[n,:] = Ts"
  weave.blitz(e, check_size=0)
  e = "T[:,0] = T[:,1]"
  weave.blitz(e, check_size=0)
  e = "T[0,:] = T[1,:]"
  weave.blitz(e, check_size=0)
  
  R = abs(R)
  Rmax = R.max()

  #Solve the matrix and keep track on the residuals
Пример #27
0
def henon(a):
	a = numpy.array(a)
	params = numpy.array([1.4,0.3])
	expr = "[1-params[0]*(a[0]*a[0])+a[1], params[1]*a[0]]"
	return weave.blitz(expr)