Beispiel #1
0
def cg(A, b, x=None, tol=1e-5):
    # If no guess is given, set an empty guess
    if x is None:
        x = np.zeros(shape=b.shape, dtype=b.dtype)

    # Initialize arrays
    alpha = np.zeros(shape=(1, 1), dtype=b.dtype)
    rsold = np.zeros(shape=(1, 1), dtype=b.dtype)
    rsnew = np.zeros(shape=(1, 1), dtype=b.dtype)

    r = b - np.dot(A, x)
    p = r.copy()
    r_squared = r * r
    rsold = np.sum(r_squared)

    tol_squared = tol * tol
    while np.max(r_squared) > tol_squared:
        Ap = np.dot(A, p)
        alpha = rsold / np.dot(p, Ap)

        x = x + alpha * p
        r = r - alpha * Ap
        r_squared = r * r
        rsnew = np.sum(r_squared)

        p = r + (rsnew / rsold) * p
        rsold = rsnew

    return x
Beispiel #2
0
def normalMapFromHeightMap(heightmap):
    """
    Create a normal map from a height map (sometimes called a bumpmap)

    :param heightmap: height map to convert

    Comes from:
        http://www.juhanalankinen.com/calculating-normalmaps-with-python-and-numpy/
    """
    heightmap = numpyArray(heightmap)
    heightmap = normalize(heightmap)
    matI = np.identity(heightmap.shape[0] + 1)
    matNeg = -1 * matI[0:-1, 1:]
    matNeg[0, -1] = -1
    matI = matI[1:, 0:-1]
    matI[-1, 0] = 1
    matI += matNeg
    matGradX = (matI.dot(heightmap.T)).T
    matGradY = matI.dot(heightmap)
    matNormal = np.zeros([heightmap.shape[0], heightmap.shape[1], 3])
    matNormal[:, :, 0] = -matGradX
    matNormal[:, :, 1] = matGradY
    matNormal[:, :, 2] = 1.0
    fNormMax = np.max(np.abs(matNormal))
    matNormal = ((matNormal / fNormMax) + 1.0) / 2.0
    return matNormal
Beispiel #3
0
def random_galaxy(N):
    """ Generate a galaxy of random bodies """
    m = np.array((numpy.arange(0.0, 1.0, step=1.0 / N) + np.float64(10)) *
                 np.float64(m_sol / 10))
    x = np.array((numpy.arange(0.0, 1.0, step=1.0 / N) - np.float64(0.5)) *
                 np.float64(r_ly / 100))
    y = np.array((numpy.arange(0.0, 1.0, step=1.0 / N) - np.float64(0.5)) *
                 np.float64(r_ly / 100))
    z = np.array((numpy.arange(0.0, 1.0, step=1.0 / N) - np.float64(0.5)) *
                 np.float64(r_ly / 100))
    vx = np.zeros(N, dtype=np.float64)
    vy = np.zeros(N, dtype=np.float64)
    vz = np.zeros(N, dtype=np.float64)

    assert len(m) == N
    return m, x, y, z, vx, vy, vz
Beispiel #4
0
def sor_setup(W, H, dtype=np.float32, bohrium=False):
    if W % 2 > 0 or H % 2 > 0:
        raise Exception("Each dimension must have an even size.")
    full = np.zeros((H + 2, W + 2), dtype=dtype, bohrium=bohrium)
    full[:, 0] += -273.15
    full[:, -1] += -273.15
    full[0, :] += 40.0
    full[-1, :] += -273.13
    return full
Beispiel #5
0
def sor_setup(W,H,dtype=np.float32,bohrium=False):
    if W%2 > 0 or H%2 > 0:
        raise Exception("Each dimension must have an even size.")
    full = np.zeros((H+2,W+2), dtype=dtype,bohrium=bohrium)
    full[:,0]  += -273.15
    full[:,-1] += -273.15
    full[0,:]  +=  40.0
    full[-1,:] += -273.13
    return full
Beispiel #6
0
def simulate(galaxy, timesteps, visualize=False):
    for i in range(timesteps):
        move(galaxy, dt)
        util.Benchmark().flush()
        if visualize:  #NB: this is only for experiments
            T = np.zeros((3, len(galaxy['x'])), dtype=np.float32)
            T[0, :] = galaxy['x']
            T[1, :] = galaxy['y']
            T[2, :] = galaxy['z']
            np.visualize(T, "3d", 0, 0.0, 10)
def iexpand(image):
    """
    expand image by factor of 2

    Comes from:
        https://compvisionlab.wordpress.com/2013/05/13/image-blending-using-pyramid/
    """
    out = None
    kernel = generating_kernel(0.4)
    outimage = np.zeros((image.shape[0]*2, image.shape[1]*2), dtype=np.float64)
    outimage[::2,::2]=image[:,:]
    out = 4*scipy.signal.convolve2d(outimage,kernel,'same')
    return out
Beispiel #8
0
def random_galaxy(N, B, dtype=np.float64):
    """Generate a galaxy of random bodies"""

    galaxy = {  # We let all bodies stand still initially
        'm': (B.random_array(
            (N, ), dtype=dtype) + dtype(10)) * dtype(m_sol / 10),
        'x': (B.random_array(
            (N, ), dtype=dtype) - dtype(0.5)) * dtype(r_ly / 100),
        'y': (B.random_array(
            (N, ), dtype=dtype) - dtype(0.5)) * dtype(r_ly / 100),
        'z': (B.random_array(
            (N, ), dtype=dtype) - dtype(0.5)) * dtype(r_ly / 100),
        'vx': np.zeros(N, dtype=dtype),
        'vy': np.zeros(N, dtype=dtype),
        'vz': np.zeros(N, dtype=dtype)
    }
    if dtype == np.float32:
        galaxy['m'] /= 1e10
        galaxy['x'] /= 1e5
        galaxy['y'] /= 1e5
        galaxy['z'] /= 1e5
    return galaxy
Beispiel #9
0
def monte_carlo_pi(samples, iterations):

    s = np.zeros(1)
    for i in xrange(0, iterations):                     # sample
        x = np.random.random((samples), dtype=np.float64, bohrium=True)
        y = np.random.random((samples), dtype=np.float64, bohrium=True)

        m = np.sqrt(x*x + y*y)                          # model
        c = np.add.reduce((m<1.0).astype('float'))      # count

        s += c*4.0 / samples                            # approximate

    return s / (iterations)
Beispiel #10
0
def directionalBlur(img, size=15):
    """
    blur in a given direction

    https://www.packtpub.com/mapt/book/application_development/9781785283932/2/ch02lvl1sec21/motion-blur#!
    """
    oSize = img.shape
    kernel = np.zeros((size, size))
    kernel[int((size - 1) / 2), :] = np.ones(size)
    kernel = kernel / size
    img = scipy.signal.convolve(img, kernel)
    d = (img.shape[0] - oSize[0]) / 2, (img.shape[1] - oSize[1]) / 2
    img = img[d[0]:-d[0], d[1]:-d[1]]
    return img
def perlinNoise(size=(256,256),octaves=None,seed=None):
    """
    generate perlin noise
    """
    if octaves is None:
        octaves=math.log(max(size),2.0)
    ret=np.zeros(size)
    for n in range(1,int(octaves)):
        k=n
        amp=1.0#/octaves/float(n)
        px=randomNoise((size[0]/k,size[1]/k),seed)
        px=scipy.ndimage.zoom(px,(float(ret.shape[0])/px.shape[0],float(ret.shape[1])/px.shape[1]),order=2)
        px=np.clip(px,0.0,1.0) # unfortunately zoom function can cause values to go out of bounds :(
        ret=(ret+px*amp)/2.0 # average with existing
    ret=np.clip(ret,0.0,1.0)
    return ret
def waveImage(size=(256,256),repeats=2,angle=0,wave='sine',radial=False):
    """
    create an image based on a sine, saw, or triangle wave function
    """
    ret=np.zeros(size)
    if radial:
        raise NotImplementedError() # TODO: Implement radial wave images
    else:
        twopi=2*pi
        thetas=np.arange(size[0])*float(repeats)/size[0]*twopi
        if wave=='sine':
            ret[:,:]=0.5+0.5*np.sin(thetas)
        elif wave=='saw':
            n=np.round(thetas/twopi)
            thetas-=n*twopi
            ret[:,:]=np.where(thetas<0,thetas+twopi,thetas)/twopi
        elif wave=='triangle':
            ret[:,:]=1.0-2.0*np.abs(np.floor((thetas*(1.0/twopi))+0.5)-(thetas*(1.0/twopi)))
    return ret
def collapse(lapl_pyr):
    """
    Reconstruct the image based on its laplacian pyramid.

    Comes from:
        https://compvisionlab.wordpress.com/2013/05/13/image-blending-using-pyramid/
    """
    output = None
    output = np.zeros((lapl_pyr[0].shape[0],lapl_pyr[0].shape[1]), dtype=np.float64)
    for i in range(len(lapl_pyr)-1,0,-1):
        lap = iexpand(lapl_pyr[i])
        lapb = lapl_pyr[i-1]
        if lap.shape[0] > lapb.shape[0]:
            lap = np.delete(lap,(-1),axis=0)
        if lap.shape[1] > lapb.shape[1]:
            lap = np.delete(lap,(-1),axis=1)
        tmp = lap + lapb
        lapl_pyr.pop()
        lapl_pyr.pop()
        lapl_pyr.append(tmp)
        output = tmp
    return output
def interest(image):
    """
    get regions of interest in the image

    returns b&w image where white=interesting, black=uninteresting
    """
    program = []  # (weight, function)
    if not has_opencv:
        print('WARN: Attempting auto-detection of regions of interest.')
        print('\t  This works A LOT better with OpenCV installed.')
        print('\t  try: pip install opencv-contrib-python')
        print(
            '\t  or go here: https://sourceforge.net/projects/opencvlibrary/files/'
        )
        program = [(0.5, selectSkin), (0.1, selectHighContrast),
                   (0.1, selectHighSaturation), (0.05, selectSobel)]
    else:
        program = [(0.8, selectEyes), (0.8, selectFaces), (0.5, selectSkin),
                   (0.3, selectHighContrast), (0.5, selectHighSaturation),
                   (0.3, selectSobel)]
    image = imageRepr.numpyArray(image)
    outImage = np.zeros(image.shape[0:2])
    totalWeight = 0
    for weight, _ in program:
        totalWeight += weight
    for weight, fn in program:
        weight = weight / totalWeight
        if weight < 0.001:
            #print("skipping",fn.__name__,weight)
            continue
        #print("calculating",fn.__name__,weight)
        im = fn(image)
        if weight != 1.0:
            im = im * weight
        outImage = outImage + im
    return normalize(outImage)
def getChannel(img, channel):
    """
    get a channel as a new image.

    :param img: the image to extract a color channel from
    :param channel: name of the channel to extract - supports R,G,B,A,H,S,V

    Returns a grayscale image, or None
    """
    img = numpyArray(img)
    if channel == 'R':
        if len(img.shape) == 2:
            img = img[:, :]
        else:
            img = img[:, :, 0]
    elif channel == 'G':
        if len(img.shape) == 2:
            img = img[:, :]
        else:
            img = img[:, :, 1]
    elif channel == 'B':
        if len(img.shape) == 2:
            img = img[:, :]
        else:
            img = img[:, :, 2]
    elif channel == 'A':
        if len(img.shape) == 2 or len(img[0, 0]) < 4:
            img = np.ones(img.shape)
        else:
            img = img[:, :, 3]
    elif channel == 'H':
        if len(img.shape) == 2:
            img = np.zeros(img.shape)
        else:
            img = rgb2hsvArray(img)[:, :, 0]
    elif channel == 'S':
        if len(img.shape) == 2:
            img = np.zeros(img.shape)
        else:
            img = rgb2hsvArray(img)[:, :, 1]
    elif channel == 'V':
        if len(img.shape) == 2:
            pass
        else:
            img = rgb2hsvArray(img)[:, :, 2]
    elif channel == 'C':
        if len(img.shape) == 2:
            img = np.zeros(img.shape)
        else:
            img = rgb2cmykArray(img)[:, :, 0]
    elif channel == 'M':
        if len(img.shape) == 2:
            img = np.zeros(img.shape)
        else:
            img = rgb2cmykArray(img)[:, :, 1]
    elif channel == 'Y':
        if len(img.shape) == 2:
            img = np.zeros(img.shape)
        else:
            img = rgb2cmykArray(img)[:, :, 2]
    elif channel == 'K':
        if len(img.shape) == 2:
            pass
        else:
            img = rgb2cmykArray(img)[:, :, 3]
    else:
        raise Exception('Unknown channel: ' + channel)
    return img
def pad_z_edges(arr):
    arr_shape = list(arr.shape)
    arr_shape[2] += 2
    out = bh.zeros(arr_shape, arr.dtype)
    out[:, :, 1:-1] = arr
    return out
def integrate_tke(u, v, w, maskU, maskV, maskW, dxt, dxu, dyt, dyu, dzt, dzw, cost, cosu, kbot, kappaM, mxl, forc, forc_tke_surface, tke, dtke):
    tau = 0
    taup1 = 1
    taum1 = 2

    dt_tracer = 1
    dt_mom = 1
    AB_eps = 0.1
    alpha_tke = 1.
    c_eps = 0.7
    K_h_tke = 2000.

    flux_east = bh.zeros_like(maskU)
    flux_north = bh.zeros_like(maskU)
    flux_top = bh.zeros_like(maskU)

    sqrttke = bh.sqrt(bh.maximum(0., tke[:, :, :, tau]))

    """
    integrate Tke equation on W grid with surface flux boundary condition
    """
    dt_tke = dt_mom  # use momentum time step to prevent spurious oscillations

    """
    vertical mixing and dissipation of TKE
    """
    ks = kbot[2:-2, 2:-2] - 1

    a_tri = bh.zeros_like(maskU[2:-2, 2:-2])
    b_tri = bh.zeros_like(maskU[2:-2, 2:-2])
    c_tri = bh.zeros_like(maskU[2:-2, 2:-2])
    d_tri = bh.zeros_like(maskU[2:-2, 2:-2])
    delta = bh.zeros_like(maskU[2:-2, 2:-2])

    delta[:, :, :-1] = dt_tke / dzt[bh.newaxis, bh.newaxis, 1:] * alpha_tke * 0.5 \
        * (kappaM[2:-2, 2:-2, :-1] + kappaM[2:-2, 2:-2, 1:])

    a_tri[:, :, 1:-1] = -delta[:, :, :-2] / \
        dzw[bh.newaxis, bh.newaxis, 1:-1]
    a_tri[:, :, -1] = -delta[:, :, -2] / (0.5 * dzw[-1])

    b_tri[:, :, 1:-1] = 1 + (delta[:, :, 1:-1] + delta[:, :, :-2]) / dzw[bh.newaxis, bh.newaxis, 1:-1] \
        + dt_tke * c_eps \
        * sqrttke[2:-2, 2:-2, 1:-1] / mxl[2:-2, 2:-2, 1:-1]
    b_tri[:, :, -1] = 1 + delta[:, :, -2] / (0.5 * dzw[-1]) \
        + dt_tke * c_eps / mxl[2:-2, 2:-
                                     2, -1] * sqrttke[2:-2, 2:-2, -1]
    b_tri_edge = 1 + delta / dzw[bh.newaxis, bh.newaxis, :] \
        + dt_tke * c_eps / mxl[2:-2, 2:-2, :] * sqrttke[2:-2, 2:-2, :]

    c_tri[:, :, :-1] = -delta[:, :, :-1] / dzw[bh.newaxis, bh.newaxis, :-1]

    d_tri[...] = tke[2:-2, 2:-2, :, tau] + dt_tke * forc[2:-2, 2:-2, :]
    d_tri[:, :, -1] += dt_tke * forc_tke_surface[2:-2, 2:-2] / (0.5 * dzw[-1])

    sol, water_mask = solve_implicit(ks, a_tri, b_tri, c_tri, d_tri, b_edge=b_tri_edge)
    tke[2:-2, 2:-2, :, taup1] = where(water_mask, sol, tke[2:-2, 2:-2, :, taup1])

    """
    Add TKE if surface density flux drains TKE in uppermost box
    """
    tke_surf_corr = bh.zeros(maskU.shape[:2])
    mask = tke[2:-2, 2:-2, -1, taup1] < 0.0
    tke_surf_corr[2:-2, 2:-2] = where(
        mask,
        -tke[2:-2, 2:-2, -1, taup1] * 0.5 * dzw[-1] / dt_tke,
        0.
    )
    tke[2:-2, 2:-2, -1, taup1] = bh.maximum(0., tke[2:-2, 2:-2, -1, taup1])

    """
    add tendency due to lateral diffusion
    """
    flux_east[:-1, :, :] = K_h_tke * (tke[1:, :, :, tau] - tke[:-1, :, :, tau]) \
        / (cost[bh.newaxis, :, bh.newaxis] * dxu[:-1, bh.newaxis, bh.newaxis]) * maskU[:-1, :, :]
    flux_east[-1, :, :] = 0.
    flux_north[:, :-1, :] = K_h_tke * (tke[:, 1:, :, tau] - tke[:, :-1, :, tau]) \
        / dyu[bh.newaxis, :-1, bh.newaxis] * maskV[:, :-1, :] * cosu[bh.newaxis, :-1, bh.newaxis]
    flux_north[:, -1, :] = 0.
    tke[2:-2, 2:-2, :, taup1] += dt_tke * maskW[2:-2, 2:-2, :] * \
        ((flux_east[2:-2, 2:-2, :] - flux_east[1:-3, 2:-2, :])
            / (cost[bh.newaxis, 2:-2, bh.newaxis] * dxt[2:-2, bh.newaxis, bh.newaxis])
            + (flux_north[2:-2, 2:-2, :] - flux_north[2:-2, 1:-3, :])
            / (cost[bh.newaxis, 2:-2, bh.newaxis] * dyt[bh.newaxis, 2:-2, bh.newaxis]))

    """
    add tendency due to advection
    """
    adv_flux_superbee_wgrid(
        flux_east, flux_north, flux_top, tke[:, :, :, tau],
        u[..., tau], v[..., tau], w[..., tau], maskW, dxt, dyt, dzw,
        cost, cosu, dt_tracer
    )

    dtke[2:-2, 2:-2, :, tau] = maskW[2:-2, 2:-2, :] * (-(flux_east[2:-2, 2:-2, :] - flux_east[1:-3, 2:-2, :])
        / (cost[bh.newaxis, 2:-2, bh.newaxis] * dxt[2:-2, bh.newaxis, bh.newaxis])
        - (flux_north[2:-2, 2:-2, :] - flux_north[2:-2, 1:-3, :])
        / (cost[bh.newaxis, 2:-2, bh.newaxis] * dyt[bh.newaxis, 2:-2, bh.newaxis]))
    dtke[:, :, 0, tau] += -flux_top[:, :, 0] / dzw[0]
    dtke[:, :, 1:-1, tau] += - \
        (flux_top[:, :, 1:-1] - flux_top[:, :, :-2]) / dzw[1:-1]
    dtke[:, :, -1, tau] += - \
        (flux_top[:, :, -1] - flux_top[:, :, -2]) / \
        (0.5 * dzw[-1])

    """
    Adam Bashforth time stepping
    """
    tke[:, :, :, taup1] += dt_tracer * ((1.5 + AB_eps) * dtke[:, :, :, tau] - (0.5 + AB_eps) * dtke[:, :, :, taum1])

    return tke, dtke, tke_surf_corr
Beispiel #18
0
def main():
    B = util.Benchmark()

    nx      = B.size[0]
    ny      = B.size[1]
    nz      = B.size[2]
    ITER    = B.size[3]

    NO_OBST = 1
    omega   = 1.0
    density = 1.0
    deltaU  = 1e-7
    t1      = 1/3.0
    t2      = 1/18.0
    t3      = 1/36.0

    B.start()
    F       = np.ones((19, nx, ny, nz), dtype=np.float64)
    F[:]    = density/19.0
    FEQ     = np.ones((19, nx, ny, nz), dtype=np.float64)
    FEQ[:]  = density/19.0
    T       = np.zeros((19, nx, ny, nz), dtype=np.float64)

    #Create the scenery.
    BOUND   = np.zeros((nx, ny, nz), dtype=np.float64)
    BOUNDi  = np.ones((nx, ny, nz), dtype=np.float64)
    """
    if not NO_OBST:
        for i in xrange(nx):
            for j in xrange(ny):
                for k in xrange(nz):
                    if ((i-4)**2+(j-5)**2+(k-6)**2) < 6:
                        BOUND[i,j,k] += 1.0
                        BOUNDi[i,j,k] += 0.0
    BOUND[:,0,:]    += 1.0
    BOUNDi[:,0,:]   *= 0.0
    """

    if util.Benchmark().bohrium:
        np.flush()
    for ts in xrange(0, ITER):

        ##Propagate / Streaming step
        T[:] = F
        #nearest-neighbours
        F[1,:,:,0]   = T[1,:,:,-1]
        F[1,:,:,1:]  = T[1,:,:,:-1]
        F[2,:,:,:-1] = T[2,:,:,1:]
        F[2,:,:,-1]  = T[2,:,:,0]
        F[3,:,0,:]   = T[3,:,-1,:]
        F[3,:,1:,:]  = T[3,:,:-1,:]
        F[4,:,:-1,:] = T[4,:,1:,:]
        F[4,:,-1,:]  = T[4,:,0,:]
        F[5,0,:,:]   = T[5,-1,:,:]
        F[5,1:,:,:]  = T[5,:-1,:,:]
        F[6,:-1,:,:] = T[6,1:,:,:]
        F[6,-1,:,:]  = T[6,0,:,:]
        #next-nearest neighbours
        F[7,0 ,0 ,:] = T[7,-1 , -1,:]
        F[7,0 ,1:,:] = T[7,-1 ,:-1,:]
        F[7,1:,0 ,:] = T[7,:-1, -1,:]
        F[7,1:,1:,:] = T[7,:-1,:-1,:]

        F[8,0 ,:-1,:] = T[8,-1 ,1:,:]
        F[8,0 , -1,:] = T[8,-1 ,0 ,:]
        F[8,1:,:-1,:] = T[8,:-1,1:,:]
        F[8,1:, -1,:] = T[8,:-1,0 ,:]

        F[9,:-1,0 ,:] = T[9,1:, -1,:]
        F[9,:-1,1:,:] = T[9,1:,:-1,:]
        F[9,-1 ,0 ,:] = T[9,0 ,  0,:]
        F[9,-1 ,1:,:] = T[9,0 ,:-1,:]

        F[10,:-1,:-1,:] = T[10,1:,1:,:]
        F[10,:-1, -1,:] = T[10,1:,0 ,:]
        F[10,-1 ,:-1,:] = T[10,0 ,1:,:]
        F[10,-1 , -1,:] = T[10,0 ,0 ,:]

        F[11,0 ,:,0 ] = T[11,0  ,:, -1]
        F[11,0 ,:,1:] = T[11,0  ,:,:-1]
        F[11,1:,:,0 ] = T[11,:-1,:, -1]
        F[11,1:,:,1:] = T[11,:-1,:,:-1]

        F[12,0 ,:,:-1] = T[12, -1,:,1:]
        F[12,0 ,:, -1] = T[12, -1,:,0 ]
        F[12,1:,:,:-1] = T[12,:-1,:,1:]
        F[12,1:,:, -1] = T[12,:-1,:,0 ]

        F[13,:-1,:,0 ] = T[13,1:,:, -1]
        F[13,:-1,:,1:] = T[13,1:,:,:-1]
        F[13, -1,:,0 ] = T[13,0 ,:, -1]
        F[13, -1,:,1:] = T[13,0 ,:,:-1]

        F[14,:-1,:,:-1] = T[14,1:,:,1:]
        F[14,:-1,:, -1] = T[14,1:,:,0 ]
        F[14,-1 ,:,:-1] = T[14,0 ,:,1:]
        F[14,-1 ,:, -1] = T[14,0 ,:,0 ]

        F[15,:,0 ,0 ] = T[15,:, -1, -1]
        F[15,:,0 ,1:] = T[15,:, -1,:-1]
        F[15,:,1:,0 ] = T[15,:,:-1, -1]
        F[15,:,1:,1:] = T[15,:,:-1,:-1]

        F[16,:,0 ,:-1] = T[16,:, -1,1:]
        F[16,:,0 , -1] = T[16,:, -1,0 ]
        F[16,:,1:,:-1] = T[16,:,:-1,1:]
        F[16,:,1:, -1] = T[16,:,:-1,0 ]

        F[17,:,:-1,0 ] = T[17,:,1:, -1]
        F[17,:,:-1,1:] = T[17,:,1:,:-1]
        F[17,:, -1,0 ] = T[17,:,0 , -1]
        F[17,:, -1,1:] = T[17,:,0 ,:-1]

        F[18,:,:-1,:-1] = T[18,:,1:,1:]
        F[18,:,:-1, -1] = T[18,:,1:,0 ]
        F[18,:,-1 ,:-1] = T[18,:,0 ,1:]
        F[18,:,-1 , -1] = T[18,:,0 ,0 ]
        #Densities bouncing back at next timestep
        BB = np.empty(F.shape)
        T[:] = F
        T[1:,:,:,:] *= BOUND[np.newaxis,:,:,:]
        BB[2 ,:,:,:] += T[1 ,:,:,:]
        BB[1 ,:,:,:] += T[2 ,:,:,:]
        BB[4 ,:,:,:] += T[3 ,:,:,:]
        BB[3 ,:,:,:] += T[4 ,:,:,:]
        BB[6 ,:,:,:] += T[5 ,:,:,:]
        BB[5 ,:,:,:] += T[6 ,:,:,:]
        BB[10,:,:,:] += T[7 ,:,:,:]
        BB[9 ,:,:,:] += T[8 ,:,:,:]
        BB[8 ,:,:,:] += T[9 ,:,:,:]
        BB[7 ,:,:,:] += T[10,:,:,:]
        BB[14,:,:,:] += T[11,:,:,:]
        BB[13,:,:,:] += T[12,:,:,:]
        BB[12,:,:,:] += T[13,:,:,:]
        BB[11,:,:,:] += T[14,:,:,:]
        BB[18,:,:,:] += T[15,:,:,:]
        BB[17,:,:,:] += T[16,:,:,:]
        BB[16,:,:,:] += T[17,:,:,:]
        BB[15,:,:,:] += T[18,:,:,:]

        # Relax calculate equilibrium state (FEQ) with equivalent speed and density to F
        DENSITY = np.add.reduce(F)

        #UX = F[5,:,:,:].copy()
        UX = np.ones(F[5,:,:,:].shape, dtype=np.float64)
        UX[:,:,:] = F[5,:,:,:]

        UX += F[7,:,:,:]
        UX += F[8,:,:,:]
        UX += F[11,:,:,:]
        UX += F[12,:,:,:]
        UX -= F[6,:,:,:]
        UX -= F[9,:,:,:]
        UX -= F[10,:,:,:]
        UX -= F[13,:,:,:]
        UX -= F[14,:,:,:]
        UX /=DENSITY

        #UY = F[3,:,:,:].copy()
        UY = np.ones(F[3,:,:,:].shape, dtype=np.float64)
        UY[:,:,:] = F[3,:,:,:]

        UY += F[7,:,:,:]
        UY += F[9,:,:,:]
        UY += F[15,:,:,:]
        UY += F[16,:,:,:]
        UY -= F[4,:,:,:]
        UY -= F[8,:,:,:]
        UY -= F[10,:,:,:]
        UY -= F[17,:,:,:]
        UY -= F[18,:,:,:]
        UY /=DENSITY

        #UZ = F[1,:,:,:].copy()
        UZ = np.ones(F[1,:,:,:].shape, dtype=np.float64)
        UZ[:,:,:] = F[1,:,:,:]

        UZ += F[11,:,:,:]
        UZ += F[13,:,:,:]
        UZ += F[15,:,:,:]
        UZ += F[17,:,:,:]
        UZ -= F[2,:,:,:]
        UZ -= F[12,:,:,:]
        UZ -= F[14,:,:,:]
        UZ -= F[16,:,:,:]
        UZ -= F[18,:,:,:]
        UZ /=DENSITY

        UX[0,:,:] += deltaU #Increase inlet pressure
                            #Set bourderies to zero.
        UX[:,:,:] *= BOUNDi
        UY[:,:,:] *= BOUNDi
        UZ[:,:,:] *= BOUNDi
        DENSITY[:,:,:] *= BOUNDi

        U_SQU = UX**2 + UY**2 + UZ**2

        # Calculate equilibrium distribution: stationary
        FEQ[0,:,:,:] = (t1*DENSITY)*(1.0-3.0*U_SQU/2.0)
        # nearest-neighbours
        T1 = 3.0/2.0*U_SQU
        tDENSITY = t2*DENSITY
        FEQ[1,:,:,:]=tDENSITY*(1.0 + 3.0*UZ + 9.0/2.0*UZ**2 - T1)
        FEQ[2,:,:,:]=tDENSITY*(1.0 - 3.0*UZ + 9.0/2.0*UZ**2 - T1)
        FEQ[3,:,:,:]=tDENSITY*(1.0 + 3.0*UY + 9.0/2.0*UY**2 - T1)
        FEQ[4,:,:,:]=tDENSITY*(1.0 - 3.0*UY + 9.0/2.0*UY**2 - T1)
        FEQ[5,:,:,:]=tDENSITY*(1.0 + 3.0*UX + 9.0/2.0*UX**2 - T1)
        FEQ[6,:,:,:]=tDENSITY*(1.0 - 3.0*UX + 9.0/2.0*UX**2 - T1)
        # next-nearest neighbours
        T1 = 3.0*U_SQU/2.0
        tDENSITY = t3*DENSITY
        U8 = UX+UY
        FEQ[7,:,:,:] =tDENSITY*(1.0 + 3.0*U8  + 9.0/2.0*(U8)**2  - T1)
        U9 = UX-UY
        FEQ[8,:,:,:] =tDENSITY*(1.0 + 3.0*U9  + 9.0/2.0*(U9)**2  - T1)
        U10 = -UX+UY
        FEQ[9,:,:,:] =tDENSITY*(1.0 + 3.0*U10 + 9.0/2.0*(U10)**2 - T1)
        U8 *= -1.0
        FEQ[10,:,:,:]=tDENSITY*(1.0 + 3.0*U8 + 9.0/2.0*(U8)**2 - T1)
        U12 = UX+UZ
        FEQ[11,:,:,:]=tDENSITY*(1.0 + 3.0*U12 + 9.0/2.0*(U12)**2 - T1)
        U12 *= 1.0
        FEQ[14,:,:,:]=tDENSITY*(1.0 + 3.0*U12 + 9.0/2.0*(U12)**2 - T1)
        U13 = UX-UZ
        FEQ[12,:,:,:]=tDENSITY*(1.0 + 3.0*U13 + 9.0/2.0*(U13)**2 - T1)
        U13 *= -1.0
        FEQ[13,:,:,:]=tDENSITY*(1.0 + 3.0*U13 + 9.0/2.0*(U13)**2 - T1)
        U16 = UY+UZ
        FEQ[15,:,:,:]=tDENSITY*(1.0 + 3.0*U16 + 9.0/2.0*(U16)**2 - T1)
        U17 = UY-UZ
        FEQ[16,:,:,:]=tDENSITY*(1.0 + 3.0*U17 + 9.0/2.0*(U17)**2 - T1)
        U17 *= -1.0
        FEQ[17,:,:,:]=tDENSITY*(1.0 + 3.0*U17 + 9.0/2.0*(U17)**2 - T1)
        U16 *= -1.0
        FEQ[18,:,:,:]=tDENSITY*(1.0 + 3.0*U16 + 9.0/2.0*(U16)**2 - T1)
        F *= (1.0-omega)
        F += omega * FEQ

        #Densities bouncing back at next timestep
        F[1:,:,:,:] *= BOUNDi[np.newaxis,:,:,:]
        F[1:,:,:,:] += BB[1:,:,:,:]

        del BB
        del T1
        del UX, UY, UZ
        del U_SQU
        del DENSITY, tDENSITY
        del U8, U9, U10, U12, U13, U16, U17
        if util.Benchmark().bohrium:
            np.flush()

    B.stop()
    B.pprint()

    if B.outputfn:
        B.tofile(B.outputfn, {'res': UX})

    """
nx.set_edge_attributes(G_dir, recency)
#print()
#print(G_dir.edges(data=True))

print(G_dir.edges(data=True))

degree = np.array(np.sum(A, 0), dtype=np.int32)

G_undir.clear()
del (R)
del (temp)
del (recency)

#Initial State
x = np.zeros(N, dtype=np.int32)
for i in range(N):
    if degree[i] > 0:
        #np.random.seed(1)
        x[i] = np.random.randint(0, degree[i])
    else:
        x[i] = 0

xb = x

count = 0
#xsave = [0]*steps
#save_As=[]
#save_distribution = []
WRITE("Starting simulation")