Esempio n. 1
0
def geodistance_cp(lng1, lat1, lng2, lat2):
    lng1, lat1, lng2, lat2 = map(cp.radians, [lng1, lat1, lng2, lat2])
    dlon = lng2 - lng1
    dlat = lat2 - lat1
    a = cp.sin(dlat / 2)**2 + cp.cos(lat1) * cp.cos(lat2) * cp.sin(dlon / 2)**2
    dis = 2 * cp.arcsin(cp.sqrt(a)) * 6371 * 1000
    return dis
def HaversineLocal(busMatrix, lineMatrix, haversine=True):
    MatrizOnibus = cp.copy(busMatrix)
    MatrizLinhas = cp.copy(lineMatrix)

    MatrizLinhas = cp.dsplit(MatrizLinhas, 2)
    MatrizOnibus = cp.dsplit(MatrizOnibus, 2)

    infVector = cp.squeeze(cp.sum(cp.isnan(MatrizLinhas[0]), axis=1), axis=-1)

    MatrizLinhas[0] = cp.expand_dims(MatrizLinhas[0], axis=-1)
    MatrizLinhas[1] = cp.expand_dims(MatrizLinhas[1], axis=-1)
    MatrizOnibus[0] = cp.expand_dims(MatrizOnibus[0], axis=-1)
    MatrizOnibus[1] = cp.expand_dims(MatrizOnibus[1], axis=-1)

    MatrizOnibus[0] *= cp.pi / 180
    MatrizOnibus[1] *= cp.pi / 180
    MatrizLinhas[1] = cp.transpose(MatrizLinhas[1], [2, 3, 0, 1]) * cp.pi / 180
    MatrizLinhas[0] = cp.transpose(MatrizLinhas[0], [2, 3, 0, 1]) * cp.pi / 180

    # Haversine or euclidian, based on <haversine>
    if haversine:
        results = 1000*2*6371.0088*cp.arcsin(
        cp.sqrt(
            (cp.sin((MatrizOnibus[0] - MatrizLinhas[0])*0.5)**2 + \
             cp.cos(MatrizOnibus[0])* cp.cos(MatrizLinhas[0]) * cp.sin((MatrizOnibus[1] - MatrizLinhas[1])*0.5)**2)
        ))
    else:
        results = cp.sqrt((MatrizOnibus[0] - MatrizLinhas[0])**2 +
                          (MatrizOnibus[1] - MatrizLinhas[1])**2)

    return results, infVector
Esempio n. 3
0
def exactFilter(tilt_angles, tiltAngle, sX, sY, sliceWidth, arr=[]):
    """
    exactFilter: Generates the exact weighting function required for weighted backprojection - y-axis is tilt axis
    Reference : Optik, Exact filters for general geometry three dimensional reconstuction, vol.73,146,1986.
    @param tilt_angles: list of all the tilt angles in one tilt series
    @param titlAngle: tilt angle for which the exact weighting function is calculated
    @param sizeX: size of weighted image in X
    @param sizeY: size of weighted image in Y

    @return: filter volume

    """

    from cupy import array, matrix, sin, pi, arange, float32, column_stack, argmin, clip, ones, ceil

    # Using Friedel Symmetry in Fourier space.
    # sY = sY // 2 + 1

    # Calculate the relative angles in radians.
    diffAngles = (array(tilt_angles) - tiltAngle) * pi / 180.

    # Closest angle to tiltAngle (but not tiltAngle) sets the maximal frequency of overlap (Crowther's frequency).
    # Weights only need to be calculated up to this frequency.
    sampling = min(abs(diffAngles)[abs(diffAngles) > 0.001])
    crowtherFreq = min(sX // 2, int(ceil(1 / sin(sampling))))
    arrCrowther = matrix(abs(arange(-crowtherFreq, min(sX // 2, crowtherFreq + 1))))

    # Calculate weights
    wfuncCrowther = 1. / (clip(1 - array(matrix(abs(sin(diffAngles))).T * arrCrowther) ** 2, 0, 2)).sum(axis=0)

    # Create full with weightFunc
    wfunc = ones((sX, sY, 1), dtype=float32)
    wfunc[sX // 2 - crowtherFreq:sX // 2 + min(sX // 2, crowtherFreq + 1), :, 0] = column_stack(
        ([(wfuncCrowther), ] * (sY))).astype(float32)
    return wfunc
Esempio n. 4
0
def unit_vectors(direction, return_numpy=True):
    """
    Calculate the unit vectors (UnitX, UnitY) from a given direction angle.

    Args:

        direction: 3D NumPy array - direction angles in degrees

        return_numpy: Necessary if using `use_gpu`. Specifies if a CuPy or Numpy
        array will be returned.

    Returns:

        UnitX, UnitY: 3D NumPy array, 3D NumPy array
            x- and y-vector component in arrays
    """
    direction_gpu = cupy.array(direction)
    direction_gpu_rad = cupy.deg2rad(direction_gpu)
    UnitX = -cupy.sin(0.5 * cupy.pi) * cupy.cos(direction_gpu_rad)
    UnitY = cupy.sin(0.5 * cupy.pi) * cupy.sin(direction_gpu_rad)
    del direction_gpu_rad

    UnitX[cupy.isclose(direction_gpu, -1)] = 0
    UnitY[cupy.isclose(direction_gpu, -1)] = 0
    del direction_gpu

    if return_numpy:
        return UnitX.get(), UnitY.get()
    return UnitX, UnitY
Esempio n. 5
0
def ripple(x, y, z, t):
    f = cp.sin(x + t / 5) + cp.sin(y + t / 5)
    r = cp.abs(z - f) < 0.2
    f = cp.cos(x + t / 5) + cp.cos(y + t / 5)
    g = cp.abs(z - f) < 0.2
    b = g * 0
    return r * 10, g * 10, b
Esempio n. 6
0
def latlong2osgbgrid_cupy(lat, long, input_degrees=True):
    '''
    Converts latitude and longitude (ellipsoidal) coordinates into northing and easting (grid) coordinates, using a Transverse Mercator projection.
    
    Inputs:
    lat: latitude coordinate (north)
    long: longitude coordinate (east)
    input_degrees: if True (default), interprets the coordinates as degrees; otherwise, interprets coordinates as radians
    
    Output:
    (northing, easting)
    '''

    if input_degrees:
        lat = lat * cp.pi / 180
        long = long * cp.pi / 180

    a = 6377563.396
    b = 6356256.909
    e2 = (a**2 - b**2) / a**2

    N0 = -100000  # northing of true origin
    E0 = 400000  # easting of true origin
    F0 = .9996012717  # scale factor on central meridian
    phi0 = 49 * cp.pi / 180  # latitude of true origin
    lambda0 = -2 * cp.pi / 180  # longitude of true origin and central meridian

    sinlat = cp.sin(lat)
    coslat = cp.cos(lat)
    tanlat = cp.tan(lat)

    latdiff = lat - phi0
    longdiff = long - lambda0

    n = (a - b) / (a + b)
    nu = a * F0 * (1 - e2 * sinlat**2)**-.5
    rho = a * F0 * (1 - e2) * (1 - e2 * sinlat**2)**-1.5
    eta2 = nu / rho - 1
    M = b * F0 * (
        (1 + n + 5 / 4 * (n**2 + n**3)) * latdiff -
        (3 *
         (n + n**2) + 21 / 8 * n**3) * cp.sin(latdiff) * cp.cos(lat + phi0) +
        15 / 8 * (n**2 + n**3) * cp.sin(2 * (latdiff)) * cp.cos(2 *
                                                                (lat + phi0)) -
        35 / 24 * n**3 * cp.sin(3 * (latdiff)) * cp.cos(3 * (lat + phi0)))
    I = M + N0
    II = nu / 2 * sinlat * coslat
    III = nu / 24 * sinlat * coslat**3 * (5 - tanlat**2 + 9 * eta2)
    IIIA = nu / 720 * sinlat * coslat**5 * (61 - 58 * tanlat**2 + tanlat**4)
    IV = nu * coslat
    V = nu / 6 * coslat**3 * (nu / rho - cp.tan(lat)**2)
    VI = nu / 120 * coslat**5 * (5 - 18 * tanlat**2 + tanlat**4 + 14 * eta2 -
                                 58 * tanlat**2 * eta2)

    northing = I + II * longdiff**2 + III * longdiff**4 + IIIA * longdiff**6
    easting = E0 + IV * longdiff + V * longdiff**3 + VI * longdiff**5

    return (northing, easting)
Esempio n. 7
0
def helix2(x, y, z, t):
    R = 2
    t *= -1
    z2 = z + cp.sin(3 * z) + (t + cp.sin(t / 10)) / 5
    x2 = R * cp.sin(z2)
    y2 = R * cp.cos(z2)
    dist = (x - x2)**2 + (y - y2)**2
    g = dist < 1
    return g * 2, g * 10, g * 5
Esempio n. 8
0
def wave_tiles(x, y, z, t):
    tile_size = 2
    floor_x, floor_y = cp.floor(x / tile_size), cp.floor(y / tile_size)
    red_tiles = ((floor_x + floor_y) % 2) < 1
    tile_height = .5 * (cp.sin(floor_x + t / 10) + cp.sin(floor_y + t / 10))
    tile_mask = (z < tile_height) & (z > tile_height - 1)
    blue_tiles = ~red_tiles & tile_mask
    red_tiles = red_tiles & tile_mask
    return red_tiles * 5, 0 * red_tiles, blue_tiles * 5
Esempio n. 9
0
def chalice(x, y, z, t):
    r = cp.sqrt(x**2 + y**2)
    foot = (r < 2) & (z < .5 - r / 2) & (z > 0)
    stem = (r < .15) & (z > 0) & (z < 3)
    cup = (z > r**2 + 3) & (z < (r + .1)**2 + 3) & (r < 2)
    liquid = (z > (r + .1)**2 + 3) & (
        z < r**2 * 0.5 + 5 + .1 *
        (cp.sin(r * 2 * 4 + t / 4) + cp.sin(x + y + t / 3))) & (r < 2)
    return liquid * 8, foot * 10 + stem * 10 + cup * 10, liquid * 4
Esempio n. 10
0
def helix(x, y, z, t):
    R = 3
    z2 = z + cp.sin(-2 * z) + (t + cp.sin(t / 10)) / 5
    x2 = R * cp.cos(z2)
    y2 = R * cp.sin(z2)
    dist = (x - x2)**2 + (y - y2)**2
    r = (dist < 1)
    g = r * 0
    b = g
    return r * 10, g, b
Esempio n. 11
0
def rotate(x, theta, reverse=False):
    """Rotate coordinates with respect to the angle theta
    """
    R = cp.array([[cp.cos(theta), -cp.sin(theta)],
                  [cp.sin(theta), cp.cos(theta)]])
    if (reverse):
        R = R.swapaxes(0, 1)
    xr = cp.zeros(x.shape, dtype='float32')
    xr[:, 0] = R[1, 0] * x[:, 1] + R[1, 1] * x[:, 0]
    xr[:, 1] = R[0, 0] * x[:, 1] + R[0, 1] * x[:, 0]
    return xr
Esempio n. 12
0
def getparameters(beta, dtheta, ds, N, Nproj):
    aR = cp.sin(beta / 2) / (1 + cp.sin(beta / 2))
    am = (cp.cos(beta / 2) - cp.sin(beta / 2)) / (1 + cp.sin(beta / 2))

    # wrapping
    g = osg(aR, beta / 2)
    Ntheta = N
    Nrho = 2 * N
    dtheta = (2 * beta) / Ntheta
    drho = (g - cp.log(am)) / Nrho
    return (Nrho, Ntheta, dtheta, drho, aR, am, g)
Esempio n. 13
0
def beach(x, y, z, t):
    sun = 10 * (((x - 10)**2 + y**2 + (z - 5)**2) < 2)
    sky = z > -1
    water_freq = .1
    sand = ((x < 0) & (z < cp.abs(x) / 100)) | ((x >= 0) & (z < -x**2 / 100))
    water = (x > 2 * cp.sin(y / 4 + .25 * cp.sin(t * water_freq / 2))
             ) * ~sand * (z < .15 * (cp.sin(t * water_freq) - 1))
    depths = z / 100 * sand + z / 10 * water
    return (sand + depths + sky / 2 + sun,
            sand + water + depths + sky / 20 + sun * .75,
            water * 15 + depths * 5 + sky / 2)
Esempio n. 14
0
def bars(x, y, z, t):
    w = 1
    h = 1
    R = 3
    f = .125
    r = (x % R < w) & (y % 4 > R - h) & (z / 2 + 1 < cp.sin(
        f * cp.ceil(x / R) * cp.ceil(y / R) * t / 100))
    g = (x % R < w) & (y % 4 > R - h) & (z / 2 + 1 < cp.sin(
        f * cp.ceil(x / R) * cp.ceil(y / R) * t / 100))
    b = (x % R < w) & (y % 4 > R - h) & (z / 2 + 1 < cp.sin(
        f * cp.ceil(x / R) * cp.ceil(y / R) * t / 100))
    return r * 20, g * 3 - z / 10, b * 20
Esempio n. 15
0
def create_fwd(P):
    # convolution function
    fZ = cp.fft.fftshift(fzeta_loop_weights(
        P.Ntheta, P.Nrho, 2*P.beta, P.g-cp.log(P.am), 0, 4))
    # (lp2C1,lp2C2), transformed log-polar to Cartesian coordinates
    tmp1 = cp.outer(cp.exp(cp.array(P.rhosp)), cp.cos(cp.array(P.thsp))).flatten()
    tmp2 = cp.outer(cp.exp(cp.array(P.rhosp)), cp.sin(cp.array(P.thsp))).flatten()
    lp2C1 = [None]*P.Nspan
    lp2C2 = [None]*P.Nspan
    for k in range(P.Nspan):
        lp2C1[k] = ((tmp1-(1-P.aR))*cp.cos(k*P.beta+P.beta/2) -
                    tmp2*cp.sin(k*P.beta+P.beta/2))/P.aR
        lp2C2[k] = ((tmp1-(1-P.aR))*cp.sin(k*P.beta+P.beta/2) +
                    tmp2*cp.cos(k*P.beta+P.beta/2))/P.aR
        lp2C2[k] *= (-1)  # adjust for Tomopy
        cids = cp.where((lp2C1[k]**2+lp2C2[k]**2) <= 1)[0]
        lp2C1[k] = lp2C1[k][cids]
        lp2C2[k] = lp2C2[k][cids]
    # pids, index in polar grids after splitting by spans
    pids = [None]*P.Nspan
    [s0, th0] = cp.meshgrid(P.s, P.proj)
    th0 = th0.flatten()
    s0 = s0.flatten()
    for k in range(0, P.Nspan):
        pids[k] = cp.where((th0 >= k*P.beta-P.beta/2) &
                           (th0 < k*P.beta+P.beta/2))[0]

    # (p2lp1,p2lp2), transformed polar to log-polar coordinates
    p2lp1 = [None]*P.Nspan
    p2lp2 = [None]*P.Nspan
    for k in range(P.Nspan):
        th00 = th0[pids[k]]-k*P.beta
        s00 = s0[pids[k]]
        p2lp1[k] = th00
        p2lp2[k] = np.log(s00*P.aR+(1-P.aR)*np.cos(th00))

    # adapt for gpu interp
    for k in range(0, P.Nspan):
        lp2C1[k] = (lp2C1[k]+1)/2*(P.N-1)
        lp2C2[k] = (lp2C2[k]+1)/2*(P.N-1)
        p2lp1[k] = (p2lp1[k]-P.thsp[0])/(P.thsp[-1]-P.thsp[0])*(P.Ntheta-1)
        p2lp2[k] = (p2lp2[k]-P.rhosp[0])/(P.rhosp[-1]-P.rhosp[0])*(P.Nrho-1)
    const = cp.sqrt(P.N*P.osangles/P.Nproj)*cp.pi/4 / \
        P.aR/cp.sqrt(2)  # adjust constant
    fZgpu = fZ[:, :P.Ntheta//2+1]*const
    if(P.interp_type == 'cubic'):
        fZgpu = fZgpu/(P.B3com[:, :P.Ntheta//2+1])

    Pfwd0 = Pfwd(fZgpu, lp2C1, lp2C2, p2lp1, p2lp2, cids, pids)
    # array representation
    parsi, parsf = savePfwdpars(Pfwd0)
    return Pfwd0, parsi, parsf
Esempio n. 16
0
def nonlin_evo(psiP2, psiP1, psi0, psiM1, psiM2, c0, c2, c4, V, p, dt, spin_f):
    # Calculate densities:
    n = abs(psiP2) ** 2 + abs(psiP1) ** 2 + abs(psi0) ** 2 + abs(psiM1) ** 2 + abs(psiM2) ** 2
    A00 = 1 / cp.sqrt(5) * (psi0 ** 2 - 2 * psiP1 * psiM1 + 2 * psiP2 * psiM2)
    fz = 2 * (abs(psiP2) ** 2 - abs(psiM2) ** 2) + abs(psiP1) ** 2 - abs(psiM1) ** 2

    # Evolve spin-singlet term -c4*(n^2-|alpha|^2)
    S = cp.sqrt(n ** 2 - abs(A00) ** 2)
    S = cp.nan_to_num(S)

    cosT = cp.cos(c4 * S * dt)
    sinT = cp.sin(c4 * S * dt) / S
    sinT[S == 0] = 0  # Corrects division by 0

    Wfn = [psiP2 * cosT + 1j * (n * psiP2 - A00 * cp.conj(psiM2)) * sinT,
           psiP1 * cosT + 1j * (n * psiP1 + A00 * cp.conj(psiM1)) * sinT,
           psi0 * cosT + 1j * (n * psi0 - A00 * cp.conj(psi0)) * sinT,
           psiM1 * cosT + 1j * (n * psiM1 + A00 * cp.conj(psiP1)) * sinT,
           psiM2 * cosT + 1j * (n * psiM2 - A00 * cp.conj(psiP2)) * sinT]

    # Calculate spin vectors
    fp = cp.sqrt(6) * (Wfn[1] * cp.conj(Wfn[2]) + Wfn[2] * cp.conj(Wfn[3])) + 2 * (Wfn[3] * cp.conj(Wfn[4]) +
                                                                                   Wfn[0] * cp.conj(Wfn[1]))
    F = cp.sqrt(fz ** 2 + abs(fp) ** 2)

    # Calculate cos, sin and Qfactor terms:
    C1, S1 = cp.cos(c2 * F * dt), cp.sin(c2 * F * dt)
    C2, S2 = cp.cos(2 * c2 * F * dt), cp.sin(2 * c2 * F * dt)
    Qfactor = 1j * (-4 / 3 * S1 + 1 / 6 * S2)
    Q2factor = (-5 / 4 + 4 / 3 * C1 - 1 / 12 * C2)
    Q3factor = 1j * (1 / 3 * S1 - 1 / 6 * S2)
    Q4factor = (1 / 4 - 1 / 3 * C1 + 1 / 12 * C2)

    fzQ = cp.nan_to_num(fz / F)
    fpQ = cp.nan_to_num(fp / F)

    Qpsi = calc_Qpsi(fzQ, fpQ, Wfn)
    Q2psi = calc_Qpsi(fzQ, fpQ, Qpsi)
    Q3psi = calc_Qpsi(fzQ, fpQ, Q2psi)
    Q4psi = calc_Qpsi(fzQ, fpQ, Q3psi)

    # Evolve spin term c2 * F^2
    for ii in range(len(Wfn)):
        Wfn[ii] += Qfactor * Qpsi[ii] + Q2factor * Q2psi[ii] + Q3factor * Q3psi[ii] + Q4factor * Q4psi[ii]

    # Evolve (c0+c4)*n^2 + (V + pm)*n:
    for ii in range(len(Wfn)):
        mF = spin_f - ii
        Wfn[ii] *= cp.exp(-1j * dt * ((c0 + c4) * n + V + p * mF))

    return Wfn
Esempio n. 17
0
def run_cupy(lat2, lon2):
    import cupy as cp

    # Allocate temporary arrays
    size = len(lat2)
    a = cp.empty(size, dtype='float64')
    dlat = cp.empty(size, dtype='float64')
    dlon = cp.empty(size, dtype='float64')

    # Transfer inputs to the GPU
    lat2 = cp.array(lat2)
    lon2 = cp.array(lon2)

    # Begin computation
    lat1 = 0.70984286
    lon1 = 1.23892197
    MILES_CONST = 3959.0

    cp.subtract(lat2, lat1, out=dlat)
    cp.subtract(lon2, lon1, out=dlon)

    # dlat = sin(dlat / 2.0) ** 2.0
    cp.divide(dlat, 2.0, out=dlat)
    cp.sin(dlat, out=dlat)
    cp.multiply(dlat, dlat, out=dlat)

    # a = cos(lat1) * cos(lat2)
    lat1_cos = math.cos(lat1)
    cp.cos(lat2, out=a)
    cp.multiply(a, lat1_cos, out=a)

    # a = a + sin(dlon / 2.0) ** 2.0
    cp.divide(dlon, 2.0, out=dlon)
    cp.sin(dlon, out=dlon)
    cp.multiply(dlon, dlon, out=dlon)
    cp.multiply(a, dlon, out=a)
    cp.add(dlat, a, out=a)

    c = a
    cp.sqrt(a, out=a)
    cp.arcsin(a, out=a)
    cp.multiply(a, 2.0, out=c)

    mi = c
    cp.multiply(c, MILES_CONST, out=mi)

    # Transfer outputs back to CPU
    a = cp.asnumpy(a)

    return a
Esempio n. 18
0
 def random_in_unit_sphere():
     u = random_float()
     v = random_float()
     theta = u * 2 * cp.pi
     phi = cp.arccos(2 * v - 1)
     r = cp.cbrt(random_float())
     sinTheta = cp.sin(theta)
     cosTheta = cp.cos(theta)
     sinPhi = cp.sin(phi)
     cosPhi = cp.cos(phi)
     x = r * sinPhi * cosTheta
     y = r * sinPhi * sinTheta
     z = r * cosPhi
     return Vec3(x, y, z)
Esempio n. 19
0
def rotshift3D_spline(v, phi=0, shifts=np.array([0,0,0]), mode='wrap'):
# With a nod to:
#  http://stackoverflow.com/questions/20161175/how-can-i-use-scipy-ndimage-interpolation-affine-transform-to-rotate-an-image-ab
    rot_origin = 0.5*np.array(v.shape)
    rot_rad = -phi*np.pi/180.0
    rot_matrix = np.array([[np.cos(rot_rad), np.sin(rot_rad), 0],
                           [-np.sin(rot_rad),np.cos(rot_rad), 0], 
                           [0                , 0              , 1]])
    offset = -(rot_origin-rot_origin.dot(rot_matrix)).dot(np.linalg.inv(rot_matrix))
    offset = offset - shifts

    transformed_v = ndimage.interpolation.affine_transform(v,rot_matrix,offset=offset,mode=mode)

    return transformed_v
Esempio n. 20
0
 def apply(self, helper, qubits, targets):
     n_qubits = helper["n_qubits"]
     i = helper["indices"]
     theta = self.theta
     for target in slicing(targets, n_qubits):
         newq = cupy.zeros_like(qubits)
         newq[(i & (1 << target)) == 0] = (
             cupy.cos(theta / 2) * qubits[(i & (1 << target)) == 0] +
             -cupy.sin(theta / 2) * qubits[(i & (1 << target)) != 0])
         newq[(i & (1 << target)) != 0] = (
             cupy.sin(theta / 2) * qubits[(i & (1 << target)) == 0] +
             cupy.cos(theta / 2) * qubits[(i & (1 << target)) != 0])
         qubits = newq
     return qubits
Esempio n. 21
0
 def random_in_unit_sphere_list(size: int) -> Vec3List:
     u = random_float_list(size)
     v = random_float_list(size)
     theta = u * 2 * cp.pi
     phi = cp.arccos(2 * v - 1)
     r = cp.cbrt(random_float_list(size))
     sinTheta = cp.sin(theta)
     cosTheta = cp.cos(theta)
     sinPhi = cp.sin(phi)
     cosPhi = cp.cos(phi)
     x = r * sinPhi * cosTheta
     y = r * sinPhi * sinTheta
     z = r * cosPhi
     return Vec3List(cp.transpose(cp.array([x, y, z])))
Esempio n. 22
0
def sin(a, cuda=False):
    if cuda:
        res = cp.sin(a)
        cp.cuda.Stream.null.synchronize()
        return res
    else:
        return np.sin(a)
Esempio n. 23
0
def sin_ac(z):
    if (cupy_ready and (z.size > 40000) and (z.size <= gpu_array_max_size)):
        z_gpu = cp.asarray(z)
        r_gpu = cp.sin(z_gpu)
        return cp.asnumpy(r_gpu)
    else:
        return np.sin(z)
Esempio n. 24
0
def jackson(
    num_moments,
    precision=32,
):
    """
    This function generates the Jackson kernel for a given  number of
    Chebyscev moments

    Parameters
    ----------
        num_moments: (uint)
            number of Chebyshev moments
    Return
    ------
        jackson_kernel: cupy array(shape=(num_moments,), dtype=tf_float)

    Note
    ----
        See .. _The Kernel Polynomial Method:
        https://arxiv.org/pdf/cond-mat/0504627.pdf for more details
    """
    cp_float = cp.float64
    if precision == 32:
        cp_float = cp.float32

    kernel_moments = cp.arange(num_moments, dtype=cp_float)
    norm = cp.pi / (num_moments + 1)
    phase_vec = norm * kernel_moments
    kernel = (num_moments - kernel_moments + 1) * cp.cos(phase_vec)
    kernel = kernel + cp.sin(phase_vec) / cp.tan(norm)
    kernel = kernel / (num_moments + 1)

    return kernel
Esempio n. 25
0
def _sin_flow_gen(image0, max_motion=4.5, npics=5):
    """Generate a synthetic ground truth optical flow with a sinusoid as
      first component.

    Parameters:
    ----
    image0: ndarray
        The base image to be warped.
    max_motion: float
        Maximum flow magnitude.
    npics: int
        Number of sinusoid pics.

    Returns
    -------
    flow, image1 : ndarray
        The synthetic ground truth optical flow with a sinusoid as
        first component and the corresponding warped image.

    """
    grid = cp.meshgrid(*[cp.arange(n) for n in image0.shape], indexing='ij')
    grid = cp.stack(grid)
    # TODO: make upstream scikit-image PR changing gt_flow dtype to float
    gt_flow = cp.zeros_like(grid, dtype=float)
    gt_flow[0,
            ...] = max_motion * cp.sin(grid[0] / grid[0].max() * npics * np.pi)
    image1 = warp(image0, grid - gt_flow, mode="nearest")
    return gt_flow, image1
Esempio n. 26
0
def _log_polar_mapping(output_coords, k_angle, k_radius, center):
    """Inverse mapping function to convert from Cartesian to polar coordinates

    Parameters
    ----------
    output_coords : ndarray
        `(M, 2)` array of `(col, row)` coordinates in the output image
    k_angle : float
        Scaling factor that relates the intended number of rows in the output
        image to angle: ``k_angle = nrows / (2 * np.pi)``
    k_radius : float
        Scaling factor that relates the radius of the circle bounding the
        area to be transformed to the intended number of columns in the output
        image: ``k_radius = width / math.log(radius)``
    center : tuple (row, col)
        Coordinates that represent the center of the circle that bounds the
        area to be transformed in an input image.

    Returns
    -------
    coords : ndarray
        `(M, 2)` array of `(col, row)` coordinates in the input image that
        correspond to the `output_coords` given as input.
    """
    angle = output_coords[:, 1] / k_angle
    rr = ((cp.exp(output_coords[:, 0] / k_radius)) * cp.sin(angle)) + center[0]
    cc = ((cp.exp(output_coords[:, 0] / k_radius)) * cp.cos(angle)) + center[1]
    coords = cp.column_stack((cc, rr))
    return coords
Esempio n. 27
0
def mixed_matrix(grid_steps, grid_step_size, subtraction_trick):
    """
    Calculate a magical matrix that solves the Helmholtz or Laplace equation
    (subtraction_trick=True and subtraction_trick=False correspondingly)
    if you elementwise-multiply the RHS by it "in DST-DCT-transformed-space".
    See Samarskiy-Nikolaev, p. 189 and around.
    """
    # mul[i, j] = 1 / (lam[i] + lam[j])
    # lam[k] = 4 / h**2 * sin(k * pi * h / (2 * L))**2, where L = h * (N - 1)
    # but k for lam_i spans from 1..N-2, while k for lam_j covers 0..N-1
    ki, kj = cp.arange(1, grid_steps - 1), cp.arange(grid_steps)
    li = 4 / grid_step_size**2 * cp.sin(ki * cp.pi / (2 * (grid_steps - 1)))**2
    lj = 4 / grid_step_size**2 * cp.sin(kj * cp.pi / (2 * (grid_steps - 1)))**2
    lambda_i, lambda_j = li[:, None], lj[None, :]
    mul = 1 / (lambda_i + lambda_j + (1 if subtraction_trick else 0))
    return mul / (2 * (grid_steps - 1))**2  # additional 2xDST normalization
Esempio n. 28
0
    def setRandomMagnetization(self):
        """
        Set initial magnetization to a random state.
        """
        self.thetaM0 = np.random.uniform(0, 180, size=self.mask.shape)
        self.phiM0 = np.random.uniform(0, 360, size=self.mask.shape)
        thetaM0_ = self.thetaM0 * degree
        phiM0_ = self.phiM0 * degree

        self.mx = np.zeros(shape=(self.mask.shape))
        self.my = np.zeros(shape=(self.mask.shape))
        self.mz = np.zeros(shape=(self.mask.shape))

        self.mx = self.mask * np.sin(thetaM0_) * np.cos(phiM0_)
        self.my = self.mask * np.sin(thetaM0_) * np.sin(phiM0_)
        self.mz = self.mask * np.cos(thetaM0_)
Esempio n. 29
0
 def sphere(self, n, diameter=None):
     if n is None:
         dia = diameter
     else:
         dia = self.sphere_dia[n]
     s = cp.pi * self.rad * dia / self.size
     s[s == 0] = 1.e-5
     return ((cp.sin(s) - s * cp.cos(s)) / s**3).ravel()
Esempio n. 30
0
def test_denoise_tv_chambolle_1d():
    """Apply the TV denoising algorithm on a 1D sinusoid."""
    x = 125 + 100 * cp.sin(cp.linspace(0, 8 * cp.pi, 1000))
    x += 20 * cp.random.rand(x.size)
    x = cp.clip(x, 0, 255)
    res = restoration.denoise_tv_chambolle(x.astype(np.uint8), weight=0.1)
    assert res.dtype == float
    assert res.std() * 255 < x.std()
Esempio n. 31
0
  def testGetstateSetstate(self):
    nDims = 32 # need multiple of 8, because of sse
    nClass = 4
    size = 20
    labels = _RGEN.random_integers(0, nClass - 1, size)
    samples = np.zeros((size, nDims), dtype=_DTYPE)

    centers = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])

    for i in range(0, size):
      t = 6.28 * _RGEN.random_sample()
      samples[i][0] = 2 * centers[labels[i]][0] + 0.5*_RGEN.rand() * np.cos(t)
      samples[i][1] = 2 * centers[labels[i]][1] + 0.5*_RGEN.rand() * np.sin(t)

    classifier = svm_dense(0, nDims, seed=_SEED, probability = True)

    for y, xList in zip(labels, samples):
      x = np.array(xList, dtype=_DTYPE)
      classifier.add_sample(float(y), x)

    classifier.train(gamma=1.0/3.0, C=100, eps=1e-1)
    classifier.cross_validate(2, gamma=0.5, C=10, eps=1e-3)

    s1 = classifier.__getstate__()
    h1 = hashlib.md5(s1).hexdigest()

    classifier2 = svm_dense(0, nDims)
    classifier2.__setstate__(s1)
    s2 = classifier2.__getstate__()
    h2 = hashlib.md5(s2).hexdigest()

    self.assertEqual(h1, h2)

    with open("svm_test.bin", "wb") as f:
      pickle.dump(classifier, f)
    with open("svm_test.bin", "rb") as f:
      classifier3 = pickle.load(f)
    s3 = classifier3.__getstate__()
    h3 = hashlib.md5(s3).hexdigest()

    self.assertEqual(h1, h3)

    os.unlink("svm_test.bin")