def deltaC(size,center=None,magnitude=False):
    """
    returns an array where every value is the distance from
    the center point.

    :param center: center point, if not specified, assume size/2
    :param magnitude: return a single magnitude value instead of [dx,dy]
    """
    size=(int(size[0]),int(size[1]))
    if center is None:
        center=size[0]/2.0,size[1]/2.0
    if magnitude:
        if False:
            # old way, non-vector
            img=np.ndarray((size[0],size[1]))
            for x in range(size[0]):
                for y in range(size[1]):
                    img[x,y]=math.sqrt((x-center[0])**2+(y-center[1])**2)
        else:
            img=np.sqrt((np.arange(size[0])-center[0])**2+(np.arange(size[1])[:,None]-center[1])**2)
    else:
        img=np.ndarray((size[0],size[1],2))
        for x in range(size[0]):
            for y in range(size[1]):
                img[x,y]=(x-center[0]),(y-center[1])
    return img
def cartesian2logpolar(img, center=None, final_radius=None, initial_radius = None, phase_width = 3000):
    """
    See also:
        https://en.wikipedia.org/wiki/Log-polar_coordinates
    """
    if center is None:
        center=(img.shape[0]/2,img.shape[1]/2)
    if final_radius is None:
        final_radius=max(img.shape[0],img.shape[1])/2
    if initial_radius is None:
        initial_radius = 0
    phase_width=img.shape[0]/2

    theta , R = np.meshgrid(np.linspace(0, 2*np.pi, phase_width),
        np.arange(initial_radius, final_radius))
    Xcart  = np.exp(R)  * np.cos(theta) + center[0]
    Ycart  = np.exp(R)  * np.sin(theta) + center[1]
    Xcart = Xcart.astype(int)
    Ycart = Ycart.astype(int)

    if img.ndim ==3:
        polar_img = img[Ycart,Xcart,:]
        polar_img = np.reshape(polar_img,(final_radius-initial_radius,phase_width,img.shape[-1]))
    else:
        polar_img = img[Ycart,Xcart]
        polar_img = np.reshape(polar_img,(final_radius-initial_radius,phase_width))
    return polar_img
def cartesian2polar(img, center=None, final_radius=None, initial_radius = None, phase_width = 3000):
    """
    Comes from:
        https://stackoverflow.com/questions/9924135/fast-cartesian-to-polar-to-cartesian-in-python
    """
    img=numpyArray(img)
    if center is None:
        center=(img.shape[0]/2,img.shape[1]/2)
    if final_radius is None:
        final_radius=max(img.shape[0],img.shape[1])/2
    if initial_radius is None:
        initial_radius = 0
    phase_width=img.shape[0]/2

    theta , R = np.meshgrid(np.linspace(0, 2*np.pi, phase_width),
        np.arange(initial_radius, final_radius))
    Xcart  = R  * np.cos(theta) + center[0]
    Ycart  = R  * np.sin(theta) + center[1]
    Xcart = Xcart.astype(int)
    Ycart = Ycart.astype(int)

    if img.ndim ==3:
        polar_img = img[Ycart,Xcart,:]
        polar_img = np.reshape(polar_img,(final_radius-initial_radius,phase_width,img.shape[-1]))
    else:
        polar_img = img[Ycart,Xcart]
        polar_img = np.reshape(polar_img,(final_radius-initial_radius,phase_width))
    return polar_img
예제 #4
0
def solve_implicit(ks, a, b, c, d, b_edge=None, d_edge=None):
    land_mask = (ks >= 0)[:, :, bh.newaxis]
    edge_mask = land_mask & (bh.arange(a.shape[2])[bh.newaxis, bh.newaxis, :]
                             == ks[:, :, bh.newaxis])
    water_mask = land_mask & (bh.arange(a.shape[2])[bh.newaxis, bh.newaxis, :]
                              >= ks[:, :, bh.newaxis])

    a_tri = water_mask * a * bh.logical_not(edge_mask)
    b_tri = where(water_mask, b, 1.)
    if b_edge is not None:
        b_tri = where(edge_mask, b_edge, b_tri)
    c_tri = water_mask * c
    d_tri = water_mask * d
    if d_edge is not None:
        d_tri = where(edge_mask, d_edge, d_tri)

    return solve_tridiag(a_tri, b_tri, c_tri, d_tri), water_mask
예제 #5
0
def has_ext():
    try:
        a = bh.arange(4).astype(bh.float64).reshape(2, 2)
        bh.blas.gemm(a, a)
        return True
    except Exception as e:
        print("\n\033[31m[ext] Cannot test BLAS extension methods.\033[0m")
        print(e)
        return False
예제 #6
0
def has_ext():
    try:
        a = bh.arange(4).astype(bh.float64).reshape(2, 2)
        bh.blas.gemm(a, a)
        return True
    except Exception as e:
        print("\n\033[31m[ext] Cannot test BLAS extension methods.\033[0m")
        print(e)
        return False
예제 #7
0
def has_ext():
    try:
        a = bh.arange(4).astype(bh.float64).reshape(2, 2)
        bh.linalg.solve_tridiagonal(a, a, a, a)
        return True
    except Exception as e:
        print("\n\033[31m[ext] Cannot test TDMA extension methods.\033[0m")
        print(e)
        return False
예제 #8
0
파일: mxmul.py 프로젝트: Ektorus/bohrium
def main():

    B = util.Benchmark()
    N, = B.size

    x = numpy.arange(N**2, dtype=numpy.float32)
    x.shape = (N, N)
    x.bohrium = B.bohrium

    y = numpy.arange(N**2, dtype=numpy.float32)
    y.shape = (N, N)
    x.bohrium = B.bohrium

    B.start()

    numpy.add.reduce(x[:,numpy.newaxis]*numpy.transpose(y),-1)

    B.stop()
    B.pprint()
    def weighted_line(r0, c0, r1, c1, w, rmin=0, rmax=np.inf):
        # The algorithm below works fine if c1 >= c0 and c1-c0 >= abs(r1-r0).
        # If either of these cases are violated, do some switches.
        if abs(c1-c0) < abs(r1-r0):
            # Switch x and y, and switch again when returning.
            xx, yy, val = weighted_line(c0, r0, c1, r1, w, rmin=rmin, rmax=rmax)
            return (yy, xx, val)

        # At this point we know that the distance in columns (x) is greater
        # than that in rows (y). Possibly one more switch if c0 > c1.
        if c0 > c1:
            return weighted_line(r1, c1, r0, c0, w, rmin=rmin, rmax=rmax)

        # The following is now always < 1 in abs
        num=r1-r0
        denom=c1-c0
        slope = np.divide(num,denom,out=np.zeros_like(denom), where=denom!=0)

        # Adjust weight by the slope
        w *= np.sqrt(1+np.abs(slope)) / 2

        # We write y as a function of x, because the slope is always <= 1
        # (in absolute value)
        x = np.arange(c0, c1+1, dtype=float)
        y = x * slope + (c1*r0-c0*r1) / (c1-c0)

        # Now instead of 2 values for y, we have 2*np.ceil(w/2).
        # All values are 1 except the upmost and bottommost.
        thickness = np.ceil(w/2)
        yy = (np.floor(y).reshape(-1,1) + np.arange(-thickness-1,thickness+2).reshape(1,-1))
        xx = np.repeat(x, yy.shape[1])
        vals = trapez(yy, y.reshape(-1,1), w).flatten()

        yy = yy.flatten()

        # Exclude useless parts and those outside of the interval
        # to avoid parts outside of the picture
        mask = np.logical_and.reduce((yy >= rmin, yy < rmax, vals > 0))

        return (yy[mask].astype(int), xx[mask].astype(int), vals[mask])
def logpolar2cartesian(polar_data):
    """
    From:
        https://stackoverflow.com/questions/2164570/reprojecting-polar-to-cartesian-grid
    """

    from scipy.ndimage.interpolation import map_coordinates

    theta_step=1
    range_step=500
    x=np.arange(-100000, 100000, 1000)
    y=x
    order=3

    # "x" and "y" are numpy arrays with the desired cartesian coordinates
    # we make a meshgrid with them
    X, Y = np.meshgrid(x, y)

    # Now that we have the X and Y coordinates of each point in the output plane
    # we can calculate their corresponding theta and range
    Tc = np.degrees(np.arctan2(Y, X)).ravel()
    Rc = np.ln(np.sqrt(X**2 + Y**2)).ravel()

    # Negative angles are corrected
    Tc[Tc < 0] = 360 + Tc[Tc < 0]

    # Using the known theta and range steps, the coordinates are mapped to
    # those of the data grid
    Tc = Tc / theta_step
    Rc = Rc / range_step

    # An array of polar coordinates is created stacking the previous arrays
    #coords = np.vstack((Ac, Sc))
    coords = np.vstack((Tc, Rc))

    # To avoid holes in the 360º - 0º boundary, the last column of the data
    # copied in the begining
    polar_data = np.vstack((polar_data, polar_data[-1,:]))

    # The data is mapped to the new coordinates
    # Values outside range are substituted with nans
    cart_data = map_coordinates(polar_data, coords, order=order, mode='constant', cval=np.nan)

    # The data is reshaped and returned
    return cart_data.reshape(len(Y), len(X)).T
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 naive_line(r0, c0, r1, c1):
        # The algorithm below works fine if c1 >= c0 and c1-c0 >= abs(r1-r0).
        # If either of these cases are violated, do some switches.
        if abs(c1-c0) < abs(r1-r0):
            # Switch x and y, and switch again when returning.
            xx, yy, val = naive_line(c0, r0, c1, r1)
            return (yy, xx, val)

        # At this point we know that the distance in columns (x) is greater
        # than that in rows (y). Possibly one more switch if c0 > c1.
        if c0 > c1:
            return naive_line(r1, c1, r0, c0)

        # We write y as a function of x, because the slope is always <= 1
        # (in absolute value)
        x = np.arange(c0, c1+1, dtype=float)
        y = x * (r1-r0) / (c1-c0) + (c1*r0-c0*r1) / (c1-c0)

        valbot = np.floor(y)-y+1
        valtop = y-np.floor(y)
        return (np.concatenate((np.floor(y), np.floor(y)+1)).astype(int), np.concatenate((x,x)).astype(int),np.concatenate((valbot, valtop)))
def perlinNoiseX(size=(256,256),seed=None):
    """
    Generate a black and white image consisting of perlinNoise (clouds)
    """
    def lerp(a,b,x):
        "linear interpolation"
        return a + x * (b-a)
    def fade(t):
        "6t^5 - 15t^4 + 10t^3"
        return 6 * t**5 - 15 * t**4 + 10 * t**3
    def gradient(h,x,y):
        "converts h to the right gradient vector and return the dot product with (x,y)"
        vectors = np.array([[0,1],[0,-1],[1,0],[-1,0]])
        g = vectors[h%4]
        return g[:,:,0] * x + g[:,:,1] * y
    # permutation table
    if seed is not None:
        np.random.seed(seed)
    p = np.arange(256,dtype=int)
    np.random.shuffle(p)
    p = np.stack([p,p]).flatten()
    # coordinates of the top-left
    xi = size[0].astype(int)
    yi = size[1].astype(int)
    # internal coordinates
    xf = size[0] - xi
    yf = size[1] - yi
    # fade factors
    u = fade(xf)
    v = fade(yf)
    # noise components
    n00 = gradient(p[p[xi]+yi],xf,yf)
    n01 = gradient(p[p[xi]+yi+1],xf,yf-1)
    n11 = gradient(p[p[xi+1]+yi+1],xf-1,yf-1)
    n10 = gradient(p[p[xi+1]+yi],xf-1,yf)
    # combine noises
    x1 = lerp(n00,n10,u)
    x2 = lerp(n01,n11,u)
    return lerp(x1,x2,v)
def curves(image,
           controlPoints,
           clampBlack=0,
           clampWhite=1,
           degree=None,
           extrapolate=True):
    """
    Perform a curves adjustment on an image

    :param image: evaluate the curve at these points can be pil image or numpy array
    :param controlPoints: set of [x,y] points that define the mapping
    :param clampBlack: clamp the black pixels to this value
    :param clampBlack: clamp the white pixels to this value
    :param degree: polynomial degree (if omitted, make it the same as the
        number of control points)
    :param extrapolate: go beyond the defined area of the curve to get values
        (oterwise returns NaN for outside values)

    :return: the adjusted image
    """
    import scipy.interpolate
    img = numpyArray(image)
    count = len(controlPoints)
    if degree is None:
        degree = count - 1
    else:
        degree = np.clip(degree, 1, count - 1)
    knots = np.clip(np.arange(count + degree + 1) - degree, 0, count - degree)
    spline = scipy.interpolate.BSpline(knots, controlPoints, degree)
    if len(img.shape) < 3:
        # for some reason it keeps the original point, which we need to strip off
        resultPoints = spline(img[:, :], extrapolate=extrapolate)[:, :, 0]
    else:
        # for some reason it keeps the original point, which we need to strip off
        resultPoints = spline(img[:, :, :], extrapolate=extrapolate)[:, :, :,
                                                                     0]
    resultPoints = clampImage(resultPoints, clampBlack, clampWhite)
    return pilImage(resultPoints)
예제 #15
0
# -*- coding: utf-8 -*-
import bohrium as np
from math import pi
import matplotlib.pyplot as plt
import matplotlib.colors as colors

fig = plt.figure()
plt.xticks([])
plt.yticks([])

k = 5  # number of plane waves
stripes = 37  # number of stripes per wave
N = 512  # image size in pixels
ite = 30  # iterations
phases = np.arange(0, 2 * pi, 2 * pi / ite)

image = np.empty((N, N))

d = np.arange(-N / 2, N / 2, dtype=np.float64)

xv, yv = np.meshgrid(d, d)
theta = np.arctan2(yv, xv)
r = np.log(np.sqrt(xv * xv + yv * yv))
r[np.isinf(r) == True] = 0

tcos = theta * np.cos(np.arange(0, pi, pi / k))[:, np.newaxis, np.newaxis]
rsin = r * np.sin(np.arange(0, pi, pi / k))[:, np.newaxis, np.newaxis]
inner = (tcos - rsin) * stripes

cinner = np.cos(inner)
sinner = np.sin(inner)
예제 #16
0
G_dir.add_edges_from(G_undir.edges())

A = nx.to_numpy_matrix(G_dir.to_undirected(), dtype=np.bool)
A = np.asarray(A, dtype=np.bool)

#fig = plt.figure(figsize=(5, 5))
#plt.title("Adjacency Matrix")
#plt.imshow(A,cmap="Greys",interpolation="none")
#%matplotlib inline
#sns.heatmap(A, cmap="Greys")
#plt.show()

#storex = np.zeros((N,steps))
#storex_noava = np.zeros((N,steps))

temp = np.arange(0, int(2 * G_undir.number_of_edges()))
R = [(temp[2 * i], temp[2 * i + 1]) for i in range(G_undir.number_of_edges())]
recency = {}
for edge, rec in zip(G_dir.edges(), R):
    recency[edge] = {'recency': rec}

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)