Пример #1
0
def cg(A, b, x=None, tol=1e-5, force_niter=None):
    """
    Conjugate Gradient (CG) solver

    Implemented as example MATLAB code from <https://en.wikipedia.org/wiki/Conjugate_gradient_method>
    """
    # If no guess is given, set an empty guess
    if x is None:
        x = array_create.zeros_like(b)

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

    tol_squared = tol * tol
    i = 0
    while np.max(r_squared) > tol_squared or force_niter is not None:
        Ap = dot(A, p)
        alpha = rsold / 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
        if force_niter is not None and i >= force_niter:
            break
        i += 1
    return x
Пример #2
0
def cg(A, b, x=None, tol=1e-5, force_niter=None):
    """
    Conjugate Gradient (CG) solver

    Implemented as example MATLAB code from <https://en.wikipedia.org/wiki/Conjugate_gradient_method>
    """
    # If no guess is given, set an empty guess
    if x is None:
        x = array_create.zeros_like(b)

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

    tol_squared = tol * tol
    i = 0
    while np.max(r_squared) > tol_squared or force_niter is not None:
        Ap = dot(A, p)
        alpha = rsold / 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
        if force_niter is not None and i >= force_niter:
            break
        i += 1
    return x
Пример #3
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
Пример #4
0
def bestBounds(image, size, regionOfInterest=None):
    """
    utility determine the best bounds for a given size
    if regionOfInterest is None, then will center the crop

    :param image: any supported image type
    :param size: can be anything that getSize() supports
    :param regionOfInterest: a black and white mask used to liquid resize images
        (if =True, then auto-calculate as necessary)

    :return (x,y,x2,y2):
    """
    imsize = getSize(image)
    size = getSize(size)
    dx = max(int(imsize[0] - size[0]), 0)
    dy = max(int(imsize[1] - size[1]), 0)
    if regionOfInterest is None:
        return (dx / 2, dy / 2, imsize[0] - dx / 2, imsize[1] - dy / 2)
    if regionOfInterest is True:  # auto-calculate
        from . import autoInterest
        regionOfInterest = autoInterest.interest(image)
    # determine bounds
    n, s, e, w = 0, imsize[0] - 1, imsize[1] - 1, 0
    if dy > 0:
        col_roi = np.sum(regionOfInterest, axis=1)
        ff = False  # when there's a tie, alternate sides
        for _ in range(dy):
            if col_roi[e] > col_roi[w]:
                w += 1
                ff = True
            elif col_roi[e] < col_roi[w] or ff:
                e -= 1
                ff = False
            else:
                w += 1
                ff = True
    if dx > 0:
        col_roi = np.sum(regionOfInterest, axis=0)
        ff = False  # when there's a tie, alternate sides
        for _ in range(dx):
            if col_roi[s] > col_roi[n]:
                n += 1
                ff = True
            elif col_roi[s] < col_roi[n] or ff:
                s -= 1
                ff = False
            else:
                n += 1
                ff = True
    return (n, w, s, e)
    def smartsize(self, size: Tuple[int, int], useGolden: bool = False):
        """
        returns an image smartly cropped to the given size

        :param size: the size to change to
        :param useGolden: TODO: try to position regions of interest on golden mean
        """
        image = self.image
        if image is None:
            return image
        if image.size[0] < 1 or image.size[1] < 1:
            raise Exception("Image is busted. ", image.size)
        roi = self.roi
        resize = 1.0  # percent
        if size[0] != image.size[0]:
            resize = size[0] / max(image.size[0], 1)
        if size[1] != image.size[1]:
            resize = max(resize, size[1] / max(image.size[1], 1))
        # TODO: do I want to scale up the image directly,
        #   or get smart about oversizing and using region of interest??
        if resize != 1.0:
            newsize = (int(round(image.size[0] * resize)),
                       int(round(image.size[1] * resize)))
            image = image.resize(newsize)
            roi = roi.resize(newsize)
        # crop in on region of interest
        # for now, simply find the best place in the lingering dimension to crop
        if newsize[0] == size[0]:
            if newsize[1] != size[1]:
                # width matches, crop height
                d = int(size[1])
                a = np.sum(roi, axis=1)  # or use mean
                for u in range(len(a) - d):
                    a[u] = np.sum(a[u:u + d])
                a = a[0:-d]
                idx = np.argmax(a)
                cropTo = (0, idx, size[0], idx + size[1])
                image = image.crop(cropTo)
        else:
            # height matches, crop width
            d = int(size[0])
            a = np.sum(roi, axis=0)  # or use mean
            for u in range(len(a) - d):
                a[u] = np.sum(a[u:u + d])
            a = a[0:-d]
            idx = np.argmax(a)
            cropTo = (idx, 0, idx + size[0], size[1])
            image = image.crop(cropTo)
        return image
Пример #6
0
def avalanche(x, A, f, N):

    count = 0
    degree = np.sum(A, 0, dtype=np.int32)
    #print(degree.shape)
    xc = degree + (degree == 0)
    spikes = x >= xc
    ava = spikes.copy()
    while np.dot(degree, spikes) > 0:
        ava = (ava + spikes) > 0
        spikes = x >= xc

        add_particles = np.dot(A, spikes)
        #subtract=np.multiply(np.random.rand(N),spikes)>f
        nonzero = add_particles.nonzero()[0]
        add_particles[nonzero] = np.random.rand(
            len(nonzero)) > f  #leak of avalanching particles

        x = x + add_particles
        x = x - np.multiply(spikes, degree)
        #x = x - (np.random.rand(N)>f)
        #x = np.multiply(x,(x>0))
        count = count + 1

    return [x, ava]
Пример #7
0
def avalanche(x, A, f, N):

    count = 0
    degree = np.sum(A, 0, dtype=np.int32)
    #print(degree.shape)
    xc = degree + (degree == 0)
    spikes = x >= xc
    ava = spikes.copy()
    while np.sum(np.multiply(degree, spikes)) > 0:
        ava = (ava + spikes) > 0
        spikes = x >= xc

        x = x + np.dot(A, spikes)
        x = x - np.multiply(spikes, degree)
        x = x - (np.random.rand(N) > f)
        x = np.multiply(x, (x > 0))
        count = count + 1

    return [x, ava]
Пример #8
0
def move(galaxy, dt):
    """Move the bodies
    first find forces and change velocity and then move positions
    """
    n = len(galaxy['x'])
    # Calculate all dictances component wise (with sign)
    dx = galaxy['x'][np.newaxis, :].T - galaxy['x']
    dy = galaxy['y'][np.newaxis, :].T - galaxy['y']
    dz = galaxy['z'][np.newaxis, :].T - galaxy['z']

    # Euclidian distances (all bodys)
    r = np.sqrt(dx**2 + dy**2 + dz**2)
    diagonal(r)[:] = 1.0

    # prevent collition
    mask = r < 1.0
    r = r * ~mask + 1.0 * mask

    m = galaxy['m'][np.newaxis, :].T

    # Calculate the acceleration component wise
    Fx = G * m * dx / r**3
    Fy = G * m * dy / r**3
    Fz = G * m * dz / r**3
    # Set the force (acceleration) a body exerts on it self to zero
    diagonal(Fx)[:] = 0.0
    diagonal(Fy)[:] = 0.0
    diagonal(Fz)[:] = 0.0

    galaxy['vx'] += dt * np.sum(Fx, axis=0)
    galaxy['vy'] += dt * np.sum(Fy, axis=0)
    galaxy['vz'] += dt * np.sum(Fz, axis=0)

    galaxy['x'] += dt * galaxy['vx']
    galaxy['y'] += dt * galaxy['vy']
    galaxy['z'] += dt * galaxy['vz']
Пример #9
0
def norm(x, ord=None, axis=None):
    """
    This version of norm is not fully compliant with the NumPy version,
    it only supports computing 2-norm of a vector.
    """

    if ord != None:
        raise NotImplementedError("Unsupported value param ord=%s" % ord)
    if axis != None:
        raise NotImplementedError("Unsupported value of param ord=%s" % axis)

    r = np.sum(x*x)
    if issubclass(np.dtype(r.dtype).type, np.integer):
        r_f32 = np.empty(r.shape, dtype=np.float32)
        r_f32[:] = r
        r = r_f32
    return np.sqrt(r)
Пример #10
0
def norm(x, ord=None, axis=None):
    """
    This version of norm is not fully compliant with the NumPy version,
    it only supports computing 2-norm of a vector.
    """

    if ord != None:
        raise NotImplementedError("Unsupported value param ord=%s" % ord)
    if axis != None:
        raise NotImplementedError("Unsupported value of param ord=%s" % axis)

    r = np.sum(x * x)
    if issubclass(np.dtype(r.dtype).type, np.integer):
        r_f32 = np.empty(r.shape, dtype=np.float32)
        r_f32[:] = r
        r = r_f32
    return np.sqrt(r)
Пример #11
0
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)

i = 0
for phase in phases:
    image[:] = np.sum(cinner * np.cos(phase) - sinner * np.sin(phase),
                      axis=0) + k
    plt.imshow(image.copy2numpy(), cmap="RdGy")
    fig.savefig("quasi-{:03d}.png".format(i),
                bbox_inches='tight',
                pad_inches=0)
    i += 1
Пример #12
0
#!/usr/bin/dython2
import bohrium as bh
a = bh.array(range(9 * 100000))
a = bh.sum(a)
print(a)
Пример #13
0
#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)
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
Пример #14
0
def test_reduce(np, bohrium, shape):

    return np.sum(np.ones(shape))

if __name__ == "__main__":

    """
    print("NUMPY")
    import numpy as np
    print test_reduce(np, False, (10, 10, 10))
    print test_reduce(np, False, (10, 10, 10))
    """

    print("BOHRIUM")
    import bohrium as np
    shape = (10,10,10)
    a = np.sum(np.ones(shape))
    b = np.sum(np.ones(shape))
    c = np.add.reduce(np.add.reduce(np.add.reduce(np.ones(shape))))
    d = np.sum(np.ones(shape))
    print a,b,c,d

    #print np.add.reduce(np.add.reduce(np.add.reduce(np.ones(shape))))

    #t1 = np.add.reduce(np.ones(shape))
    #t2 = np.add.reduce(t1)
    #t3 = np.add.reduce(t2)
    #del t1, t2
    #print t3
Пример #15
0
def selectByColor(img,
                  color,
                  tolerance=0,
                  soften=10,
                  smartSoften=True,
                  colorspace='RGB'):
    """
    Select all pixels of a given color

    :param img: can be a pil image, numpy array, etc
    :param color: (in colorspace units) can be anything that pickColor returns:
        a color int array
        a color string to decode
        a color range (colorLow,colorHigh)
        an array of any of these
    :param tolerance: how close the selection must be
    :param soften: apply a soften radius to the edges of the selection
    :param smartSoften: multiply the soften radius by how near the pixel is to the selection color
    :param colorspace: change the given img (assumed to be RGB) into another corlorspace before matching

    :returns: black and white image in a numpy array (usable as a selection or a mask)
    """
    from . import colorSpaces
    img = numpyArray(img)
    img = colorSpaces.changeColorspace(img, colorspace)
    if (isinstance(color, list)
            and isinstance(color[0], list)) or (isinstance(color, np.ndarray)
                                                and len(color.shape) > 1):
        # there are multiple colors, so select them all one at a time
        # TODO: this could possibly be made faster with array operations??
        ret = None
        for c in color:
            if ret is None:
                ret = selectByColor(img, c, tolerance, soften, smartSoften)
            else:
                ret = ret + selectByColor(img, c, tolerance, soften,
                                          smartSoften)
        ret = clampImage(ret)
    elif isinstance(color, tuple):
        # color range - select all colors "between" these two in the given color space
        color = (matchColorToImage(color[0],
                                   img), matchColorToImage(color[1], img))
        matches = np.logical_and(img >= color[0], img <= color[1])
        ret = np.where(matches.all(axis=2), 1.0, 0.0)
    else:
        # a single color (or a series of colors that have been averaged down to one)
        color = matchColorToImage(color, img)
        if isFloat(color):
            imax = 1.0
            imin = 0.0
        else:
            imax = 255
            imin = 0
        numColors = img.shape[-1]
        avgDelta = np.sum(np.abs(img[:, :] - color), axis=-1) / numColors
        ret = np.where(avgDelta <= tolerance, imax, imin)
        if soften > 0:
            ret = gaussianBlur(ret, soften)
            if smartSoften:
                ret = np.minimum(imax, ret / avgDelta)
    return ret
Пример #16
0
#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))

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