示例#1
0
    def Huniaxialanisotropy(self):
        """
        Calculate uniaxial anisotropy field.
        """
        mx_ = self.magnet.mx
        my_ = self.magnet.my
        mz_ = self.magnet.mz

        Ku_ = self.magnet.Ku
        thetaK_ = self.magnet.thetaK * degree
        phiK_ = self.magnet.phiK * degree

        Kux_ = Ku_ * np.sin(thetaK_) * np.cos(phiK_)
        Kuy_ = Ku_ * np.sin(thetaK_) * np.sin(phiK_)
        Kuz_ = Ku_ * np.cos(thetaK_)

        Hux_ = 2 * Kux_ / (self.magnet.Ms + 10**-10) * self.magnet.mask
        Huy_ = 2 * Kuy_ / (self.magnet.Ms + 10**-10) * self.magnet.mask
        Huz_ = 2 * Kuz_ / (self.magnet.Ms + 10**-10) * self.magnet.mask

        Hu_ = Hux_ * mx_ + Huy_ * my_ + Huz_ * mz_

        self.hux = Hu_ * np.sin(thetaK_) * np.cos(phiK_)
        self.huy = Hu_ * np.sin(thetaK_) * np.sin(phiK_)
        self.huz = Hu_ * np.cos(thetaK_)
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
示例#3
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
示例#4
0
def take_filter(N, filter):
    os = 4
    d = 0.5
    Ne = os * N
    t = cp.arange(0, Ne / 2 + 1) / Ne

    if (filter == 'ramp'):
        wfa = Ne * 0.5 * wint(12, t)  # .*(t/(2*d)<=1)%compute the weigths
    elif (filter == 'shepp-logan'):
        wfa = Ne * 0.5 * wint(12, t) * cp.sinc(t / (2 * d)) * (t / d <= 2)
    elif (filter == 'cosine'):
        wfa = Ne * 0.5 * wint(12, t) * cp.cos(cp.pi * t /
                                              (2 * d)) * (t / d <= 1)
    elif (filter == 'cosine2'):
        wfa = Ne * 0.5 * wint(12, t) * (cp.cos(cp.pi * t /
                                               (2 * d)))**2 * (t / d <= 1)
    elif (filter == 'hamming'):
        wfa = Ne * 0.5 * wint(
            12, t) * (.54 + .46 * cp.cos(cp.pi * t / d)) * (t / d <= 1)
    elif (filter == 'hann'):
        wfa = Ne * 0.5 * wint(
            12, t) * (1 + np.cos(cp.pi * t / d)) / 2.0 * (t / d <= 1)
    elif (filter == 'parzen'):
        wfa = Ne * 0.5 * wint(12, t) * pow(1 - t / d, 3) * (t / d <= 1)

    wfa = wfa * (wfa >= 0)
    wfamid = cp.array([2 * wfa[0]])
    tmp = wfa
    wfa = cp.concatenate((cp.flipud(tmp[1:]), wfamid))
    wfa = cp.concatenate((wfa, tmp[1:]))
    wfa = wfa[:-1].astype('float32')
    return wfa
示例#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
示例#6
0
def _cubic_smooth_coeff(signal, lamb):
    rho, omega = _coeff_smooth(lamb)
    cs = 1 - 2 * rho * cos(omega) + rho * rho
    K = len(signal)
    yp = zeros((K, ), signal.dtype.char)
    k = arange(K)
    yp[0] = (_hc(0, cs, rho, omega) * signal[0] +
             add(_hc(k + 1, cs, rho, omega) * signal))

    yp[1] = (_hc(0, cs, rho, omega) * signal[0] +
             _hc(1, cs, rho, omega) * signal[1] +
             add(_hc(k + 2, cs, rho, omega) * signal))

    for n in range(2, K):
        yp[n] = (cs * signal[n] + 2 * rho * cos(omega) * yp[n - 1] -
                 rho * rho * yp[n - 2])

    y = zeros((K, ), signal.dtype.char)

    y[K - 1] = add(
        (_hs(k, cs, rho, omega) + _hs(k + 1, cs, rho, omega)) * signal[::-1])
    y[K - 2] = add((_hs(k - 1, cs, rho, omega) + _hs(k + 2, cs, rho, omega)) *
                   signal[::-1])

    for n in range(K - 3, -1, -1):
        y[n] = (cs * yp[n] + 2 * rho * cos(omega) * y[n + 1] -
                rho * rho * y[n + 2])

    return y
示例#7
0
def CheckIfEscaped(photon_state, tau_atm, escaped_mu):
    ######################################################################################
    # This checks if a photon has escaped, calculates the momentum that photon takes with it
    # then removes that photon from the list.
    #
    # photon_state -- A CuPy array consisting of [x,y,z,phi,theta,lambda] for each photon.
    # tau_atm -- The depth of the atmosphere.
    ######################################################################################

    # Looks for all the photons above the atmosphere.
    escaped_photons = cp.where(photon_state[:, 2] >= tau_atm)[0]
    momentum_transfer = 0

    if len(escaped_photons) > 0:
        # Find the angles the particles escaped at
        escaped_mu += cp.cos(photon_state[escaped_photons, 4]).tolist()

        # Calculates the momentum transferred, this is the difference between the initial z momentum and the final z momentum
        momentum_transfer = float(
            cp.sum(h * (-cp.cos(photon_state[escaped_photons, 4])) /
                   photon_state[escaped_photons, 5]))

        # Remove the escaped photons
        photon_state = RemovePhotons(photon_state, escaped_photons)

    return photon_state, momentum_transfer, escaped_mu
示例#8
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)
示例#9
0
文件: util.py 项目: nikitinvv/gwp2d
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
示例#10
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
示例#11
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
示例#12
0
文件: gate.py 项目: gyu-don/cupygate
 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
示例#13
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])))
示例#14
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
示例#15
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)
示例#16
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
示例#17
0
def spherical_cosmask(n,mask_radius, edge_width, origin=None):
    """mask = spherical_cosmask(n, mask_radius, edge_width, origin)
    """

    if type(n) is int:
        n = np.array([n])

    sz = np.array([1, 1, 1])
    sz[0:np.size(n)] = n[:]

    szl = -np.floor(sz/2)
    szh = szl + sz

    x,y,z = np.meshgrid( np.arange(szl[0],szh[0]), 
                         np.arange(szl[1],szh[1]), 
                         np.arange(szl[2],szh[2]), indexing='ij', sparse=True)

    r = np.sqrt(x*x + y*y + z*z)

    m = np.zeros(sz.tolist())

#    edgezone = np.where( (x*x + y*y + z*z >= mask_radius) & (x*x + y*y + z*z <= np.square(mask_radius + edge_width)))

    edgezone = np.all( [ (x*x + y*y + z*z >= mask_radius), (x*x + y*y + z*z <= np.square(mask_radius + edge_width))], axis=0)
    m[edgezone] = 0.5 + 0.5*np.cos( 2*np.pi*(r[edgezone] - mask_radius) / (2*edge_width))
    m[ np.all( [ (x*x + y*y + z*z <= mask_radius*mask_radius) ], axis=0 ) ] = 1

#    m[ np.where(x*x + y*y + z*z <= mask_radius*mask_radius)] = 1

    return m
示例#18
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
示例#19
0
文件: toolbox.py 项目: 3d-pli/SLIX
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
示例#20
0
def cos(a, cuda=False):
    if cuda:
        res = cp.cos(a)
        cp.cuda.Stream.null.synchronize()
        return res
    else:
        return np.cos(a)
示例#21
0
def fzeta_loop_weights(Ntheta, Nrho, betas, rhos, a, osthlarge):
    krho = cp.arange(-Nrho/2, Nrho/2, dtype='float32')
    Nthetalarge = osthlarge*Ntheta
    thsplarge = cp.arange(-Nthetalarge/2, Nthetalarge/2,
                          dtype='float32') / Nthetalarge*betas
    fZ = cp.zeros([Nrho, Nthetalarge], dtype='complex64')
    h = cp.ones(Nthetalarge, dtype='float32')
    # correcting = 1+[-3 4 -1]/24correcting(1) = 2*(correcting(1)-0.5)
    # correcting = 1+array([-23681,55688,-66109,57024,-31523,9976,-1375])/120960.0correcting[0] = 2*(correcting[0]-0.5)
    correcting = 1+cp.array([-216254335, 679543284, -1412947389, 2415881496, -3103579086,
                             2939942400, -2023224114, 984515304, -321455811, 63253516, -5675265])/958003200.0
    correcting[0] = 2*(correcting[0]-0.5)
    h[0] = h[0]*(correcting[0])
    for j in range(1, len(correcting)):
        h[j] = h[j]*correcting[j]
        h[-1-j+1] = h[-1-j+1]*(correcting[j])
    for j in range(len(krho)):
        fcosa = pow(cp.cos(thsplarge), (-2*cp.pi*1j*krho[j]/rhos-1-a))
        fZ[j, :] = cp.fft.fftshift(cp.fft.fft(cp.fft.fftshift(h*fcosa)))
    fZ = fZ[:, Nthetalarge//2-Ntheta//2:Nthetalarge//2+Ntheta//2]
    fZ = fZ*(thsplarge[1]-thsplarge[0])
    # put imag to 0 for the border
    fZ[0] = 0
    fZ[:, 0] = 0
    return fZ
示例#22
0
 def signal_func(ts):
     # Calculate adjusted center frequencies, according to chirp
     chirp_phase = 2 * xp.pi * (
         (f_start - self.fch1) * ts + 0.5 * drift_rate * ts**2)
     if not self.ascending:
         chirp_phase = -chirp_phase
     return level * xp.cos(chirp_phase + phase)
示例#23
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
示例#24
0
 def updateGeometry(self):
     # GPU variables
     self._psi = cp.zeros(self.shape, dtype=cp.complex64)
     self._phi = cp.zeros(self.shape, dtype=cp.uint8)
     self._theta = cp.zeros(self.shape, dtype=cp.float32)
     self._rho = cp.zeros(self.shape, dtype=cp.float32)
     alpha = cp.cos(cp.radians(self.phis, dtype=cp.float32))
     x = alpha*(cp.arange(self.width, dtype=cp.float32) -
                cp.float64(self.xs))
     y = cp.arange(self.height, dtype=cp.float32) - cp.float32(self.ys)
     qx = self.qprp * x
     qy = self.qprp * y
     self._iqx = (1j * qx).astype(cp.complex64)
     self._iqy = (1j * qy).astype(cp.complex64)
     self._iqxz = (1j * self.qpar * x * x).astype(cp.complex64)
     self._iqyz = (1j * self.qpar * y * y).astype(cp.complex64)
     self.outeratan2f(y, x, self._theta)
     self.outerhypot(qy, qx, self._rho)
     # CPU variables
     self.phi = self._phi.get()
     self.iqx = self._iqx.get()
     self.iqy = self._iqy.get()
     self.theta = self._theta.get().astype(cp.float64)
     self.qr = self._rho.get().astype(cp.float64)
     self.sigUpdateGeometry.emit()
示例#25
0
    def test_elementwise_trinary(self):
        desc_a = cutensor.create_tensor_descriptor(self.a, ct.OP_SQRT)
        desc_b = cutensor.create_tensor_descriptor(self.b, ct.OP_TANH)
        desc_c = cutensor.create_tensor_descriptor(self.c, ct.OP_COS)

        d = cutensor.elementwise_trinary(self.alpha,
                                         self.a,
                                         desc_a,
                                         self.mode_a,
                                         self.beta,
                                         self.b,
                                         desc_b,
                                         self.mode_b,
                                         self.gamma,
                                         self.c,
                                         desc_c,
                                         self.mode_c,
                                         op_AB=ct.OP_ADD,
                                         op_ABC=ct.OP_MUL)

        testing.assert_allclose((self.alpha * cupy.sqrt(self.a_transposed) +
                                 self.beta * cupy.tanh(self.b_transposed)) *
                                self.gamma * cupy.cos(self.c),
                                d,
                                rtol=1e-6,
                                atol=1e-6)
示例#26
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_)
示例#27
0
def apply_kernel(moments,
                 kernel,
                 num_moments,
                 num_vecs,
                 extra_points=1,
                 precision=32):
    """
    Parameters
    ----------
    Apply a given kernel in a given array of moments.
    Return the cosine transform of type III.
    """

    num_points = extra_points + num_moments

    if kernel is not None:
        moments = moments * kernel

    mu_ext = cp.zeros(num_points, dtype=moments.dtype)
    mu_ext[0:num_moments] = moments

    smooth_moments = dctIII(mu_ext, precision)
    points = cp.arange(0, num_points)
    ek = cp.cos(cp.pi * (points + 0.5) / num_points)
    gk = cp.pi * cp.sqrt(1. - ek**2)

    rho = cp.divide(smooth_moments, gk)

    return ek, rho
示例#28
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()
示例#29
0
 def _lossP(self, A, P):
     floor = 1.0E-6
     inum = cupy.array(1.0j, cupy.complex64)
     loss = (self.alpha * (1 - cupy.cos(P['y'] - P['x']))).mean()
     grad = self._overlapadd(
         cupy.fft.irfft(self.alpha * cupy.sin(P['y'] - P['x']) / cupy.fmax(
             A['x'], floor) * cupy.exp(inum * (P['x'] - 0.5 * cupy.pi))) *
         self.norm)
     return loss, grad
示例#30
0
 def random_in_unit_sphere() -> Vec3:
     """
     This method is modified from:
     https://karthikkaranth.me/blog/generating-random-points-in-a-sphere/#better-choice-of-spherical-coordinates
     """
     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)
示例#31
0
文件: svm_test.py 项目: leotam/cupic
  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")