Example #1
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
Example #2
0
 def createWedge(self, subunit_num=0):
     ###Initialize the location of the protofilament to remove
     theta0=np.arctan2(self.com[0], self.com[1])+\
     np.deg2rad(subunit_num*self.twist_per_subunit)
         
     z0=(self.com[2]+self.rise_per_subunit*subunit_num)/self.pixel_size
     
     ###Define the length along the protofilament in terms of subunits 
     zsubunits=(self.zline.copy()-z0)*self.pixel_size/self.dimer_repeat_dist
     
     ###Define the angle of the center of the protofilament along the length of the segment
     theta=np.deg2rad((-self.helical_twist)*zsubunits)+theta0
     
     ###Initialize the wedge mask
     wedge=np.zeros(self.vol_dim.tolist())
     
     ###Define the size of the wedgemask
     fudge=np.deg2rad(360.0/(self.num_pfs*2))
     
     ###Generate the wedge mask
     for i in range(len(theta)):
         temp1=np.remainder(theta[i]-fudge+2*np.pi,2*np.pi)-2*np.pi
         temp2=np.remainder(theta[i]+fudge+2*np.pi,2*np.pi)-2*np.pi
         angles=[temp1, temp2]
         if max(angles)-min(angles)>2*fudge+.2:
             above=max(angles)
             below=min(angles)
             inds=np.logical_or(self.radmatrix>above,self.radmatrix<below)
         else:
             above=min(angles)
             below=max(angles)
             inds=np.logical_and(self.radmatrix>above,self.radmatrix<below)
             
         wedge[i,:,:][inds]=1
         
     return wedge
Example #3
0
 def rotshift3D_spline(self, v, eulers, 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
     print shifts
     print eulers
     rot_origin = 0.5*np.array(v.shape)
     rot_rad = -np.deg2rad(eulers)
     phi = np.array([[np.cos(rot_rad[0]), np.sin(rot_rad[0]), 0],
                            [-np.sin(rot_rad[0]),np.cos(rot_rad[0]), 0],
                            [0                , 0              , 1]])
     theta=np.array([[np.cos(rot_rad[1]), 0,-np.sin(rot_rad[1])],[0,1,0],\
                         [np.sin(rot_rad[1]), 0, np.cos(rot_rad[1])]])
     psi=np.array([[np.cos(rot_rad[2]), np.sin(rot_rad[2]), 0],\
                       [-np.sin(rot_rad[2]),np.cos(rot_rad[2]), 0],\
                       [0,0,1]])
     rot_matrix=np.dot(np.dot(phi,theta),psi)
     offset = -(rot_origin-rot_origin.dot(rot_matrix)).dot(np.linalg.inv(rot_matrix))
     offset = offset - shifts
     transformed_v = affine_transform(v,rot_matrix,offset=offset,mode=mode)
     return transformed_v
Example #4
0
    def receive_power(self, tx_ant):
        # 「EEM-RTM理論説明書」3.1伝達公式参照
        # http://www.e-em.co.jp/doc/rtm_theory.pdf
        distance = self.get_distance_by_points(tx_ant) / 100    # Unit[m]
        theta = self.calc_theta_tx(tx_ant)
        phi = self.calc_phi_tx(distance[1]*100, tx_ant)
        R = self.R_horizontal(phi, const.epsilon_r)

        def E(reflection_coefficient, distance):
            E = cp.sqrt(self.directivity(theta)) * \
                cp.sqrt(self.directivity(theta)) * \
                reflection_coefficient * \
                (tx_ant.lambda_0 / (4 * cp.pi * distance)) * \
                cp.exp((-1j * tx_ant.k) * distance)
            return E

        Pr = (E(const.reflection_coefficient, distance[0]) + E(R, distance[1])) * \
            cp.exp(1j * cp.deg2rad(tx_ant.phase_offset)) * \
            cp.sqrt(tx_ant.power)

        return Pr
Example #5
0
def rotate(input,
           angle,
           axes=(1, 0),
           reshape=True,
           output=None,
           order=None,
           mode='constant',
           cval=0.0,
           prefilter=True):
    """Rotate an array.
    The array is rotated in the plane defined by the two axes given by the
    ``axes`` parameter using spline interpolation of the requested order.
    Args:
        input (cupy.ndarray): The input array.
        angle (float): The rotation angle in degrees.
        axes (tuple of 2 ints): The two axes that define the plane of rotation.
            Default is the first two axes.
        reshape (bool): If ``reshape`` is True, the output shape is adapted so
            that the input array is contained completely in the output. Default
            is True.
        output (cupy.ndarray or ~cupy.dtype): The array in which to place the
            output, or the dtype of the returned array.
        order (int): The order of the spline interpolation. If it is not given,
            order 1 is used. It is different from :mod:`scipy.ndimage` and can
            change in the future. Currently it supports only order 0 and 1.
        mode (str): Points outside the boundaries of the input are filled
            according to the given mode (``'constant'``, ``'nearest'``,
            ``'mirror'`` or ``'opencv'``). Default is ``'constant'``.
        cval (scalar): Value used for points outside the boundaries of
            the input if ``mode='constant'`` or ``mode='opencv'``. Default is
            0.0
        prefilter (bool): It is not used yet. It just exists for compatibility
            with :mod:`scipy.ndimage`.
    Returns:
        cupy.ndarray or None:
            The rotated input.
    .. seealso:: :func:`scipy.ndimage.rotate`
    """

    _check_parameter('rotate', order, mode)

    if mode == 'opencv':
        mode = '_opencv_edge'

    axes = list(axes)
    if axes[0] < 0:
        axes[0] += input.ndim
    if axes[1] < 0:
        axes[1] += input.ndim
    if axes[0] > axes[1]:
        axes = axes[1], axes[0]
    if axes[0] < 0 or input.ndim <= axes[1]:
        raise IndexError

    rad = cupy.deg2rad(angle)
    sin = math.sin(rad)
    cos = math.cos(rad)

    matrix = cupy.identity(input.ndim)
    matrix[axes[0], axes[0]] = cos
    matrix[axes[0], axes[1]] = sin
    matrix[axes[1], axes[0]] = -sin
    matrix[axes[1], axes[1]] = cos

    iy = input.shape[axes[0]]
    ix = input.shape[axes[1]]
    if reshape:
        mtrx = cupy.array([[cos, sin], [-sin, cos]])
        minc = [0, 0]
        maxc = [0, 0]
        coor = cupy.dot(mtrx, cupy.array([0, ix]))
        minc, maxc = _minmax(coor, minc, maxc)
        coor = cupy.dot(mtrx, cupy.array([iy, 0]))
        minc, maxc = _minmax(coor, minc, maxc)
        coor = cupy.dot(mtrx, cupy.array([iy, ix]))
        minc, maxc = _minmax(coor, minc, maxc)
        oy = int(maxc[0] - minc[0] + 0.5)
        ox = int(maxc[1] - minc[1] + 0.5)
    else:
        oy = input.shape[axes[0]]
        ox = input.shape[axes[1]]

    offset = cupy.zeros(input.ndim)
    offset[axes[0]] = oy / 2.0 - 0.5
    offset[axes[1]] = ox / 2.0 - 0.5
    offset = cupy.dot(matrix, offset)
    tmp = cupy.zeros(input.ndim)
    tmp[axes[0]] = iy / 2.0 - 0.5
    tmp[axes[1]] = ix / 2.0 - 0.5
    offset = tmp - offset

    output_shape = list(input.shape)
    output_shape[axes[0]] = oy
    output_shape[axes[1]] = ox

    return affine_transform(input, matrix, offset, output_shape, output, order,
                            mode, cval, prefilter)
def backProjectGPU2(vol_img, vol_bp, vol_phi, vol_the, recPosVol=[0,0,0], vol_offsetProjections=[0,0,0]):
    from pytom_numpy import vol2npy
    import cupy as cp
    from cupy import cos, sin
    import voltools

    projections = vol2npy(vol_img)
    proj_angles = vol2npy(vol_the)[0,0,:]

    dims = (vol_bp.sizeX(), vol_bp.sizeY(), vol_bp.sizeZ())
    # TODO add offsets

    # preparation
    reconstruction = cp.zeros(dims, dtype=cp.float32)
    theta_angles = cp.deg2rad(cp.array(proj_angles))

    # theta_angles_rad = (theta_angles)
    assert len(theta_angles) == projections.shape[2] #'Number of angles and projections should match'
    # create coordinates and stack them
    x, y, z = cp.meshgrid(cp.arange(0, dims[0]), cp.arange(0, dims[1]), cp.arange(0, dims[2]), indexing='ij')
    # backproject each projection into reconstruction

    for n in range(projections.shape[2]):
        # get projection
        src = cp.array(projections[:,:,n])

        # previous
        Z1 = Z2 = 0.0
        Y = theta_angles[n]
        x_offset = y_offset = z_offset = 0
        x_proj_offset = y_proj_offset = 0
        tr11 = cos(Y)*cos(Z1)*cos(Z2)-sin(Z1)*sin(Z2)
        # tr21 = cos(Y)*sin(Z1)*cos(Z2)+cos(Z1)*sin(Z2)
        tr31 = -sin(Y)*cos(Z2)
        # tr12 = -cos(Y)*cos(Z1)*sin(Z2)-sin(Z1)*cos(Z2)
        tr22 = -cos(Y)*sin(Z1)*sin(Z2)+cos(Z1)*cos(Z2)
        # tr32 = sin(Y)*sin(Z2)
        reconstruction_center_x = dims[0] // 2 - x_offset
        reconstruction_center_y = dims[1] // 2 - y_offset
        reconstruction_center_z = dims[2] // 2 - z_offset
        projection_center_x = dims[0] // 2 + x_proj_offset
        projection_center_y = dims[1] // 2 + y_proj_offset
        # interpolation_position_x = tr11 * (x - reconstruction_center_x) + tr21 * (y - reconstruction_center_y) + tr31 * (z - reconstruction_center_z) + projection_center_x
        # interpolation_position_y = tr12 * (x - reconstruction_center_x) + tr22 * (y - reconstruction_center_y) + tr32 * (z - reconstruction_center_z) + projection_center_y
        interpolation_position_x = tr11 * (x - reconstruction_center_x) + tr31 * (z - reconstruction_center_z) + projection_center_x
        interpolation_position_y = tr22 * (y - reconstruction_center_y) + projection_center_y
        proj_position_x = interpolation_position_x.astype(int)
        proj_position_y = interpolation_position_y.astype(int)
        interpolation_offset_x = (interpolation_position_x - proj_position_x)
        interpolation_offset_y = (interpolation_position_y - proj_position_y)
        m0, m1, m2 = cp.where((proj_position_x >= 1) & (proj_position_x < dims[0]) & (proj_position_y >= 1) & (proj_position_y < dims[1]))
        value_x1 = src[proj_position_x[m0, m1, m2]-1, proj_position_y[m0, m1, m2]-1] + \
                   (src[proj_position_x[m0, m1, m2], proj_position_y[m0, m1, m2]-1] - src[proj_position_x[m0, m1, m2]-1, proj_position_y[m0, m1, m2]-1]) * interpolation_offset_x[m0, m1, m2]
        value_x2 = src[proj_position_x[m0, m1, m2]-1, proj_position_y[m0, m1, m2]] + \
                   (src[proj_position_x[m0, m1, m2], proj_position_y[m0, m1, m2]] - src[proj_position_x[m0, m1, m2]-1, proj_position_y[m0, m1, m2]]) * interpolation_offset_x[m0, m1, m2]
        value_y = value_x1 + (value_x2 - value_x1) * interpolation_offset_y[m0, m1, m2]
        reconstruction[m0, m1, m2] += value_y
        del value_y
        del value_x1
        del value_x2
        del m0, m1, m2
        # import napari
        # with napari.gui_qt():
        #     viewer = napari.Viewer()
        #     viewer.add_image(reconstruction.get(), name='recon', interpolation='bilinear')
        #     viewer.add_image(np.log10(np.abs(np.fft.fftshift(np.fft.fftn(reconstruction.get())))), name='fft', interpolation='bilinear')
    rec = reconstruction.get()
    return rec

    for i in range(dims[0]):
        for j in range(dims[1]):
            for k in range(dims[2]):
                vol_bp.setV(float(rec[i][j][k]), int(i), int(j), int(k))


    return vol_bp
Example #7
0
def deltaE_cmc(lab1, lab2, kL=1, kC=1):
    """Color difference from the  CMC l:c standard.

    This color difference was developed by the Colour Measurement Committee
    (CMC) of the Society of Dyers and Colourists (United Kingdom). It is
    intended for use in the textile industry.

    The scale factors `kL`, `kC` set the weight given to differences in
    lightness and chroma relative to differences in hue.  The usual values are
    ``kL=2``, ``kC=1`` for "acceptability" and ``kL=1``, ``kC=1`` for
    "imperceptibility".  Colors with ``dE > 1`` are "different" for the given
    scale factors.

    Parameters
    ----------
    lab1 : array_like
        reference color (Lab colorspace)
    lab2 : array_like
        comparison color (Lab colorspace)

    Returns
    -------
    dE : array_like
        distance between colors `lab1` and `lab2`

    Notes
    -----
    deltaE_cmc the defines the scales for the lightness, hue, and chroma
    in terms of the first color.  Consequently
    ``deltaE_cmc(lab1, lab2) != deltaE_cmc(lab2, lab1)``

    References
    ----------
    .. [1] https://en.wikipedia.org/wiki/Color_difference
    .. [2] http://www.brucelindbloom.com/index.html?Eqn_DeltaE_CIE94.html
    .. [3] F. J. J. Clarke, R. McDonald, and B. Rigg, "Modification to the
           JPC79 colour-difference formula," J. Soc. Dyers Colour. 100, 128-132
           (1984).
    """
    L1, C1, h1 = cp.rollaxis(lab2lch(lab1), -1)[:3]
    L2, C2, h2 = cp.rollaxis(lab2lch(lab2), -1)[:3]

    dC = C1 - C2
    dL = L1 - L2
    dH2 = get_dH2(lab1, lab2)

    T = cp.where(cp.logical_and(cp.rad2deg(h1) >= 164, cp.rad2deg(h1) <= 345),
                 0.56 + 0.2 * cp.abs(np.cos(h1 + cp.deg2rad(168))),
                 0.36 + 0.4 * cp.abs(np.cos(h1 + cp.deg2rad(35)))
                 )
    c1_4 = C1 ** 4
    F = cp.sqrt(c1_4 / (c1_4 + 1900))

    SL = cp.where(L1 < 16, 0.511, 0.040975 * L1 / (1. + 0.01765 * L1))
    SC = 0.638 + 0.0638 * C1 / (1. + 0.0131 * C1)
    SH = SC * (F * T + 1 - F)

    dE2 = (dL / (kL * SL)) ** 2
    dE2 += (dC / (kC * SC)) ** 2
    dE2 += dH2 / (SH ** 2)
    return cp.sqrt(cp.maximum(dE2, 0, out=dE2), out=dE2)
Example #8
0
Params.cur_dir = 'M3DLF_' + sample + '/Input'
Params.out_dir = 'M3DLF_' + sample + '/Output'


class viewpoint:
    pos_x = 0
    pos_y = 0
    lon = 0
    lat = 0
    diag = 0
    fov = 0


viewpoint.pos_x = 0
viewpoint.pos_y = 0
viewpoint.lon = cp.deg2rad(0)
viewpoint.lat = cp.deg2rad(0)
viewpoint.diag = 860
viewpoint.fov = pi / 3

viewpoint.fov = round(viewpoint.fov * 10000)
viewpoint.fov = viewpoint.fov / 10000

LFDisp_forward = cp.zeros(3 * Params.LFU_W * Params.HEIGHT * Params.WIDTH)

LFDisp_backward = cp.zeros(3 * Params.LFU_W * Params.HEIGHT * Params.WIDTH)

x = cp.arange(Params.HEIGHT)
y = cp.arange(Params.WIDTH)
TY, TX = cp.meshgrid(x, y)