Esempio n. 1
0
def test_mask():
    length = 100
    ramps = [np.linspace(0, 4 * np.pi, length),
             np.linspace(0, 8 * np.pi, length),
             np.linspace(0, 6 * np.pi, length)]
    image = np.vstack(ramps)
    mask_1d = np.ones((length,), dtype=np.bool)
    mask_1d[0] = mask_1d[-1] = False
    for i in range(len(ramps)):
        # mask all ramps but the i'th one
        mask = np.zeros(image.shape, dtype=np.bool)
        mask |= mask_1d.reshape(1, -1)
        mask[i, :] = False   # unmask i'th ramp
        image_wrapped = np.ma.array(np.angle(np.exp(1j * image)), mask=mask)
        image_unwrapped = unwrap_phase(image_wrapped)
        image_unwrapped -= image_unwrapped[0, 0]    # remove phase shift
        # The end of the unwrapped array should have value equal to the
        # endpoint of the unmasked ramp
        assert_array_almost_equal_nulp(image_unwrapped[:, -1], image[i, -1])
        assert_(np.ma.isMaskedArray(image_unwrapped))

        # Same tests, but forcing use of the 3D unwrapper by reshaping
        with expected_warnings(['length 1 dimension']):
            shape = (1,) + image_wrapped.shape
            image_wrapped_3d = image_wrapped.reshape(shape)
            image_unwrapped_3d = unwrap_phase(image_wrapped_3d)
            # remove phase shift
            image_unwrapped_3d -= image_unwrapped_3d[0, 0, 0]
        assert_array_almost_equal_nulp(image_unwrapped_3d[:, :, -1],
                                       image[i, -1])
Esempio n. 2
0
def check_wrap_around(ndim, axis):
    # create a ramp, but with the last pixel along axis equalling the first
    elements = 100
    ramp = np.linspace(0, 12 * np.pi, elements)
    ramp[-1] = ramp[0]
    image = ramp.reshape(tuple([elements if n == axis else 1
                                for n in range(ndim)]))
    image_wrapped = np.angle(np.exp(1j * image))

    index_first = tuple([0] * ndim)
    index_last = tuple([-1 if n == axis else 0 for n in range(ndim)])
    # unwrap the image without wrap around
    with warnings.catch_warnings():
        # We do not want warnings about length 1 dimensions
        warnings.simplefilter("ignore")
        image_unwrap_no_wrap_around = unwrap_phase(image_wrapped, seed=0)
    print('endpoints without wrap_around:',
          image_unwrap_no_wrap_around[index_first],
          image_unwrap_no_wrap_around[index_last])
    # without wrap around, the endpoints of the image should differ
    assert_(abs(image_unwrap_no_wrap_around[index_first] -
                image_unwrap_no_wrap_around[index_last]) > np.pi)
    # unwrap the image with wrap around
    wrap_around = [n == axis for n in range(ndim)]
    with warnings.catch_warnings():
        # We do not want warnings about length 1 dimensions
        warnings.simplefilter("ignore")
        image_unwrap_wrap_around = unwrap_phase(image_wrapped, wrap_around,
                                                seed=0)
    print('endpoints with wrap_around:',
          image_unwrap_wrap_around[index_first],
          image_unwrap_wrap_around[index_last])
    # with wrap around, the endpoints of the image should be equal
    assert_almost_equal(image_unwrap_wrap_around[index_first],
                        image_unwrap_wrap_around[index_last])
Esempio n. 3
0
def test_mask():
    length = 100
    ramps = [
        np.linspace(0, 4 * np.pi, length),
        np.linspace(0, 8 * np.pi, length),
        np.linspace(0, 6 * np.pi, length)
    ]
    image = np.vstack(ramps)
    mask_1d = np.ones((length, ), dtype=np.bool)
    mask_1d[0] = mask_1d[-1] = False
    for i in range(len(ramps)):
        # mask all ramps but the i'th one
        mask = np.zeros(image.shape, dtype=np.bool)
        mask |= mask_1d.reshape(1, -1)
        mask[i, :] = False  # unmask i'th ramp
        image_wrapped = np.ma.array(np.angle(np.exp(1j * image)), mask=mask)
        image_unwrapped = unwrap_phase(image_wrapped)
        image_unwrapped -= image_unwrapped[0, 0]  # remove phase shift
        # The end of the unwrapped array should have value equal to the
        # endpoint of the unmasked ramp
        assert_array_almost_equal_nulp(image_unwrapped[:, -1], image[i, -1])
        assert_(np.ma.isMaskedArray(image_unwrapped))

        # Same tests, but forcing use of the 3D unwrapper by reshaping
        with expected_warnings(['length 1 dimension']):
            shape = (1, ) + image_wrapped.shape
            image_wrapped_3d = image_wrapped.reshape(shape)
            image_unwrapped_3d = unwrap_phase(image_wrapped_3d)
            # remove phase shift
            image_unwrapped_3d -= image_unwrapped_3d[0, 0, 0]
        assert_array_almost_equal_nulp(image_unwrapped_3d[:, :, -1], image[i,
                                                                           -1])
Esempio n. 4
0
def check_wrap_around(ndim, axis):
    # create a ramp, but with the last pixel along axis equalling the first
    elements = 100
    ramp = np.linspace(0, 12 * np.pi, elements)
    ramp[-1] = ramp[0]
    image = ramp.reshape(
        tuple([elements if n == axis else 1 for n in range(ndim)]))
    image_wrapped = np.angle(np.exp(1j * image))

    index_first = tuple([0] * ndim)
    index_last = tuple([-1 if n == axis else 0 for n in range(ndim)])
    # unwrap the image without wrap around
    with warnings.catch_warnings():
        # We do not want warnings about length 1 dimensions
        warnings.simplefilter("ignore")
        image_unwrap_no_wrap_around = unwrap_phase(image_wrapped, seed=0)
    print('endpoints without wrap_around:',
          image_unwrap_no_wrap_around[index_first],
          image_unwrap_no_wrap_around[index_last])
    # without wrap around, the endpoints of the image should differ
    assert abs(image_unwrap_no_wrap_around[index_first] -
               image_unwrap_no_wrap_around[index_last]) > np.pi
    # unwrap the image with wrap around
    wrap_around = [n == axis for n in range(ndim)]
    with warnings.catch_warnings():
        # We do not want warnings about length 1 dimensions
        warnings.simplefilter("ignore")
        image_unwrap_wrap_around = unwrap_phase(image_wrapped,
                                                wrap_around,
                                                seed=0)
    print('endpoints with wrap_around:', image_unwrap_wrap_around[index_first],
          image_unwrap_wrap_around[index_last])
    # with wrap around, the endpoints of the image should be equal
    assert_almost_equal(image_unwrap_wrap_around[index_first],
                        image_unwrap_wrap_around[index_last])
Esempio n. 5
0
def _unwrapping_phase(img2unwrap, rx=[], ry=[], airpix=[]):
    """
    Unwrap the phases of a projection

    Parameters
    ----------
    img2unwrap : ndarray
        A 2-dimensional array containing the image to be unwrapped
    rx, ry : tuple or list of ints
        Limits of the are to be unwrapped in x and y
    airpix : tuple or list of ints
        Position of pixel in the air/vacuum area

    Returns
    -------
    img2unwrap : array_like
        Unwrapped image
    """
    if rx == [] and ry == []:
        img2unwrap = unwrap_phase(im2unwrap)
        img2unwrap -= -2 * np.pi * np.round(img2unwrap / (2 * np.pi))
    else:
        # select the region to be unwrapped
        img2wrap_sel = img2unwrap[ry[0]:ry[-1], rx[0]:rx[-1]]
        # unwrap the region using the algorithm from skimage
        img2unwrap_sel = unwrap_phase(img2wrap_sel)
        # update the image in the original array
        img2unwrap[ry[0]:ry[-1], rx[0]:rx[-1]] = img2unwrap_sel
        img2unwrap[ry[0]:ry[-1], rx[0]:rx[-1]] = (
            img2unwrap_sel -
            2 * np.pi * np.round(img2unwrap[airpix[1], airpix[0]] /
                                 (2 * np.pi)))

    return img2unwrap
Esempio n. 6
0
def phase(center_1, r_1, center_2, r_2, dataEM):

    # Load the elements
    ft_holo_1 = np.fft.fft2(dataEM.holo_1)
    ft_holo_2 = np.fft.fft2(dataEM.holo_2_aligned)
    ft_holo_ref = np.fft.fft2(dataEM.holo_ref)

    # Generate the mask in the image space
    m_1, g_uns_1 = mask.mask_gaussian(center_1, r_1, ft_holo_1.shape)
    m_2, g_uns_2 = mask.mask_gaussian(center_2, r_2, ft_holo_2.shape)

    # Mask and calculate the phase component
    masked_ft_holo_1 = np.multiply(m_1, np.fft.fftshift(ft_holo_1))
    masked_ft_holo_2 = np.multiply(m_2, np.fft.fftshift(ft_holo_2))
    masked_ft_holo_ref = np.multiply(m_1, np.fft.fftshift(ft_holo_ref))
    # masked_ft_holo_ref_2 =  np.multiply(m, np.fft.fftshift(ft_holo_ref_2))

    # shift and crop before unwraping
    i_fft_1 = np.fft.ifft2(np.fft.ifftshift(masked_ft_holo_1))
    i_fft_2 = np.fft.ifft2(np.fft.ifftshift(masked_ft_holo_2))
    amplitude_1_distorded = np.abs(i_fft_1)
    amplitude_2_distorded = np.abs(i_fft_2)
    phase_1_distorded = np.angle(i_fft_1)
    phase_2_distorded = np.angle(i_fft_2)

    dataEM.phase_ref = unwrap_phase(np.angle(
        np.fft.ifft2(np.fft.ifftshift(masked_ft_holo_ref))),
                                    seed=None)
    phase_1_distorded_unwrap = unwrap_phase(phase_1_distorded, seed=None)
    phase_2_distorded_unwrap = unwrap_phase(phase_2_distorded, seed=None)

    phase_1_unwrap = phase_1_distorded_unwrap  # - dataEM.phase_ref
    phase_2_unwrap = phase_2_distorded_unwrap  # - dataEM.phase_ref

    amplitude_crop = alignholo.crop_phase([0, 0], amplitude_1_distorded,
                                          amplitude_2_distorded)

    dataEM.phase_1 = np.float64(phase_1_distorded_unwrap)
    dataEM.phase_2 = np.float64(phase_2_distorded_unwrap)
    dataEM.amplitude_1 = amplitude_crop[0]
    dataEM.amplitude_2 = amplitude_crop[1]

    # dataEM.phase_ref_2 = unwrap_phase(np.angle(np.fft.ifft2(np.fft.ifftshift(masked_ft_holo_ref_2))))

    dataEM.diff_1_ref_notsmoothed = dataEM.phase_1
    dataEM.diff_2_ref_notsmoothed = dataEM.phase_2
    dataEM.diff_2_1_cor_notsmoothed = dataEM.phase_1
    dataEM.diff_2_1_not_cor_notsmoothed = dataEM.phase_2
    '''dataEM.diff_1_ref = gaussian_filter(dataEM.diff_1_ref_notsmoothed, 6)
    dataEM.diff_2_ref = gaussian_filter(dataEM.diff_2_ref_notsmoothed, 6)
    dataEM.diff_2_1_not_cor = gaussian_filter(dataEM.diff_2_1_not_cor_notsmoothed, 6)
    dataEM.diff_2_1_cor = gaussian_filter(dataEM.diff_2_1_cor_notsmoothed, 6)'''

    dataEM.diff_1_ref = dataEM.diff_1_ref_notsmoothed
    dataEM.diff_2_ref = dataEM.diff_2_ref_notsmoothed
    dataEM.diff_2_1_not_cor = dataEM.diff_2_1_not_cor_notsmoothed
    dataEM.diff_2_1_cor = dataEM.diff_2_1_cor_notsmoothed
Esempio n. 7
0
def test_unwrap_1d():
    image = np.linspace(0, 10 * np.pi, 100)
    check_unwrap(image)
    # Masked arrays are not allowed in 1D
    with testing.raises(ValueError):
        check_unwrap(image, True)
    # wrap_around is not allowed in 1D
    with testing.raises(ValueError):
        unwrap_phase(image, True, seed=0)
Esempio n. 8
0
def test_unwrap_1d():
    image = np.linspace(0, 10 * np.pi, 100)
    check_unwrap(image)
    # Masked arrays are not allowed in 1D
    with testing.raises(ValueError):
        check_unwrap(image, True)
    # wrap_around is not allowed in 1D
    with testing.raises(ValueError):
        unwrap_phase(image, True, seed=0)
Esempio n. 9
0
def update_ref(Uref, emdata):
    def residuals(delta_g_model, delta_g_exp):
        delta_g_model_x = delta_g_model[0]
        delta_g_model_y = delta_g_model[1]
        d_g_x = delta_g_model_x * np.ones(
            (delta_g_exp.shape[1], delta_g_exp.shape[2]))
        d_g_y = delta_g_model_y * np.ones(
            (delta_g_exp.shape[1], delta_g_exp.shape[2]))
        d_g = np.array([d_g_x, d_g_y])
        err = delta_g_exp - d_g
        print('Iteration dans residual')
        return err.flatten()

    # Load data
    emdata_U = emdata.diff_2_1_cor[Uref[1]:Uref[3], Uref[0]:Uref[2]]
    model_U = np.array([0, 0])

    q_U = np.array([
        1 / (2 * np.pi) * np.gradient(unwrap_phase(emdata_U))[0],
        1 / (2 * np.pi) * np.gradient(unwrap_phase(emdata_U))[1]
    ])

    emdata_V = emdata.diff_2_1_not_cor[Uref[1]:Uref[3], Uref[0]:Uref[2]]
    model_V = np.array([0, 0])

    q_V = np.array([
        1 / (2 * np.pi) * np.gradient(unwrap_phase(emdata_V))[0],
        1 / (2 * np.pi) * np.gradient(unwrap_phase(emdata_V))[1]
    ])

    # Calculate the delta_g_model_u using the least square fit method
    model_U = leastsq(residuals, model_U, args=q_U)
    print('Resultat du calcul')
    print(model_U)
    model_V = leastsq(residuals, model_V, args=q_V)
    print('Resultat du calcul')
    print(model_V)
    # Build 3D array of the delta g model on the entire image
    d_q_x = model_U[0][0] * np.ones(emdata.diff_2_1_cor.shape)
    d_q_y = model_U[0][1] * np.ones(emdata.diff_2_1_cor.shape)
    Q_model_3d = np.array([d_q_x, d_q_y])

    d_r_x = model_V[0][0] * np.ones(emdata.diff_2_1_not_cor.shape)
    d_r_y = model_V[0][1] * np.ones(emdata.diff_2_1_not_cor.shape)
    R_model_3d = np.array([d_r_x, d_r_y])

    # Recalculate and store phase
    mesh_x, mesh_y = np.meshgrid(np.arange(emdata.diff_2_1_cor.shape[1]),
                                 np.arange(emdata.diff_2_1_cor.shape[0]))
    emdata.diff_2_1_cor = np.array(
        emdata.diff_2_1_cor) - 2 * np.pi * (np.multiply(
            Q_model_3d[1], mesh_x) + np.multiply(Q_model_3d[0], mesh_y))
    emdata.diff_2_1_not_cor = np.array(
        emdata.diff_2_1_not_cor) - 2 * np.pi * (np.multiply(
            R_model_3d[1], mesh_x) + np.multiply(R_model_3d[0], mesh_y))
    """def residuals(delta_g_model, delta_g_exp):
Esempio n. 10
0
def call_unwrap(phase, mask=None, seed=None):
    if mask is not None:
        assert (mask.shape == phase.shape)
        masked = np.ma.masked_array(phase, mask)
        phi = np.array(unwrap_phase(masked, seed=seed))
        # phi[mask] = phi[np.invert(mask)].mean()
        phi[mask] = 0
        return phi
    else:
        return np.array(unwrap_phase(phase, seed=seed))
Esempio n. 11
0
    def phase_retrieval(self, sp=(0, 0), bg=(0, 0), strategy="try"):
        # open img
        self.sp.open_image()
        self.bg.open_image()
        check_img_size(self.sp.img)
        check_img_size(self.bg.img)

        # FFT
        self.sp.twodfft()
        self.bg.twodfft()

        # ----------------------------------------------------------------
        x, y = 0, 0
        bgx, bgy = 0, 0
        if strategy == "try":
            x, y = self.try_the_position(self.sp)
            bgx, bgy = self.try_the_position(self.bg)
        elif strategy == "cheat":
            x, y = sp[0], sp[1]
            bgx, bgy = bg[0], bg[1]

        # crop real or virtual image
        self.sp.crop_first_order(x, y, IMAGESIZE//4)
        self.bg.crop_first_order(bgx, bgy, IMAGESIZE//4)
        print("sp position: ", (x, y), "bg position: ", (bgx, bgy))

        # iFFT
        self.sp.twodifft(self.sp.crop_raw_f_domain)
        self.bg.twodifft(self.bg.crop_raw_f_domain)
        self.wrapped_sp = self.sp.iff
        self.wrapped_bg = self.bg.iff
        # self.plot_fdomain()

        # unwapping
        self.unwarpped_sp = unwrap_phase(self.wrapped_sp)
        self.unwarpped_bg = unwrap_phase(self.wrapped_bg)

        # ----------------------------------------------------------------

        # shift
        sp_mean = np.mean(self.unwarpped_sp)
        bg_mean = np.mean(self.unwarpped_bg)
        self.unwarpped_sp += np.pi * self.shift(sp_mean)
        self.unwarpped_bg += np.pi * self.shift(bg_mean)

        # resize
        self.final_sp = self.resize_image(self.unwarpped_sp, self.image_size)
        self.final_bg = self.resize_image(self.unwarpped_bg, self.image_size)

        # subtract
        self.final = self.final_sp - self.final_bg

        # m_factor
        diff = M - np.mean(self.final)
        self.final = self.final + diff
Esempio n. 12
0
    def get_unwrapped_phase(self,
                            *,
                            aperture: Aperture = None,
                            z: float = None) -> Tuple[np.ndarray, Aperture]:
        if (aperture and z) is not None:

            # оптимизация апертуры для правильного разворачивания фазы
            aperture.modify(self, z)

            return unwrap_phase(self.__phase *
                                aperture.aperture_view), aperture
        else:
            return unwrap_phase(self.__phase), aperture
Esempio n. 13
0
    def get_strain(self):
        """
        Use the refined phase matrix and g vectors to calculate
        the strain matrices. 
        
        Returns
        -------
        e_xx: ndarray
              Strain along X direction
        e_yy: ndarray
              Strain along Y direction
        e_th: ndarray
              Rotational strain
        e_dg: ndarray
              Diagonal Strain

        Notes
        -----
        Use the refined G vectors to generate a matrix
        of the lattice parameters, which is stored as the
        class attribute `a_matrix`. This is multiplied by the
        refined phase matrix, and the multiplicand is subsequently
        differentiated to get the strain parameters.
        
        See Also
        --------
        phase_diff
        """
        if not self.reference_check:
            raise RuntimeError(
                "Please refine the phase and g vectors first as refine_phase()"
            )
        g_matrix = np.zeros((2, 2), dtype=np.float64)
        g_matrix[0, :] = np.flip(np.asarray(self.gvec_1_fin))
        g_matrix[1, :] = np.flip(np.asarray(self.gvec_2_fin))
        self.a_matrix = np.linalg.inv(np.transpose(g_matrix))
        P1 = skr.unwrap_phase(self.P_matrix1_fin)
        P2 = skr.unwrap_phase(self.P_matrix1_fin)
        rolled_p = np.asarray((np.reshape(P1, -1), np.reshape(P2, -1)))
        u_matrix = np.matmul(self.a_matrix, rolled_p)
        u_x = np.reshape(u_matrix[0, :], P1.shape)
        u_y = np.reshape(u_matrix[1, :], P2.shape)
        self.e_xx, e_xy = st.gpa.phase_diff(u_x)
        e_yx, self.e_yy = st.gpa.phase_diff(u_y)
        self.e_th = 0.5 * (e_xy - e_yx)
        self.e_dg = 0.5 * (e_xy + e_yx)
        self.e_yy -= np.median(self.e_yy[self.ref_reg])
        self.e_dg -= np.median(self.e_dg[self.ref_reg])
        self.e_th -= np.median(self.e_th[self.ref_reg])
        self.e_xx -= np.median(self.e_xx[self.ref_reg])
        return self.e_xx, self.e_yy, self.e_th, self.e_dg
Esempio n. 14
0
def add_atmos(wf, it):
    """
    creates a phase offset matrix for each wavelength at each time step,
    sampled from the atmosphere generated by hcipy

    HCIpy generates an atmosphere with given parameters. The returned field is in units of phase delay for each
    wavelength. prop_add_phase wants the phase delay to be in units of meters for each wavelength, so we convert to
    meters via the wavelength/np.pi

    :param wf: a single (2D) wfo.wf_collection[iw,ib] at one wavelength and object
    :param it: timestep# in obs_sequence. Comes from medis_main.gen_timeseries()
    :return: nothing returned, wfo is modified with proper.prop_add_phase
    """
    if tp.use_atmos is False:
        pass  # don't do anything. Putting this type of check here allows universal toggling on/off rather than
        # commenting/uncommenting in the proper perscription
    else:
        wavelength = wf.lamda  # the .lamda comes from proper, not from Wavefronts class

        # Check for Existing File
        atmos_map = get_filename(it, wavelength)
        # dprint(f"atmos map applied is {atmos_map}")
        if not os.path.exists(atmos_map):
            gen_atmos(plot=True)

        atm_map = fits.open(atmos_map)[1].data
        atm_map = unwrap_phase(atm_map)
        atm_map *= wavelength / (
            2 * np.pi
        )  # converts atmosphere in units of phase delay (rad) into distance (m)
        proper.prop_add_phase(wf, atm_map)
Esempio n. 15
0
def phase_from_plasma_background(interferogram,
                                 background,
                                 mask,
                                 mask_center,
                                 mask_size,
                                 mask_gauss=False,
                                 remove=True,
                                 unwrap=True):
    y1, y2, x1, x2 = mask
    img_phase = phase(
        inverse_fourier(
            apply_mask(fourier(interferogram),
                       mask_center,
                       mask_size,
                       gauss=mask_gauss)))[y1:y2, x1:x2]
    back_phase = phase(
        inverse_fourier(
            apply_mask(fourier(background),
                       mask_center,
                       mask_size,
                       gauss=mask_gauss)))[y1:y2, x1:x2]
    if unwrap:
        reconstructed_phase = unwrap_phase(back_phase - img_phase)
    else:
        reconstructed_phase = (np.pi + img_phase -
                               back_phase) % (2 * np.pi) + np.pi
    if remove:
        reconstructed_phase = remove_plane(reconstructed_phase)
    return reconstructed_phase - reconstructed_phase.min()
Esempio n. 16
0
def test_unwrap_3d_all_masked():
    # all elements masked
    image = np.ma.zeros((10, 10, 10))
    image[:] = np.ma.masked
    unwrap = unwrap_phase(image)
    assert_(np.ma.isMaskedArray(unwrap))
    assert_(np.all(unwrap.mask))

    # 1 unmasked element, still zero edges
    image = np.ma.zeros((10, 10, 10))
    image[:] = np.ma.masked
    image[0, 0, 0] = 0
    unwrap = unwrap_phase(image)
    assert_(np.ma.isMaskedArray(unwrap))
    assert_(np.sum(unwrap.mask) == 999)  # all but one masked
    assert_(unwrap[0, 0, 0] == 0)
Esempio n. 17
0
    def retrievePF(self, bscale=1.00, psf_diam=50, resample=None):
        # an ultrasimplified version
        # comment on 08/12: I am still not convinced of the way of setting background.

        z_offset, zz = psf_zplane(self.PSF, self.dz, self.l /
                                  3.2)  # This should be the reason!!!! >_<
        A = self.PF.plane
        #         z_offset = -z_offset # To deliberately add something wrong
        Mx, My = np.meshgrid(
            np.arange(self.nx) - self.nx / 2.,
            np.arange(self.nx) - self.nx / 2.)
        r_pxl = _msqrt(Mx**2 + My**2)
        bk_inner = 16
        bk_outer = 20
        hcyl = np.array(self.nz *
                        [np.logical_and(r_pxl >= bk_inner, r_pxl < bk_outer)])
        background = np.mean(self.PSF[hcyl]) * bscale
        print("   background = ", background)
        print("   z_offset = ", z_offset)
        if (resample == False):
            PSF_sample = self.PSF
            zs = zz - z_offset
        else:
            PSF_sample = self.PSF[::resample]
            zs = zz[::resample] - z_offset
        complex_PF = self.PF.psf2pf(PSF_sample, zs, background, A, self.nIt)
        Pupil_final = _PupilFunction(complex_PF, self.PF)
        self.pf_complex = Pupil_final.complex
        self.pf_phase = unwrap_phase(Pupil_final.phase)
        self.pf_ampli = Pupil_final.amplitude
Esempio n. 18
0
def phase_comp(psi_comp, uwrap=False, dens=None):
    """Compute the phase (angle) of a single complex wavefunction component.

    Parameters
    ----------
    psi_comp : NumPy :obj:`array` or PyTorch :obj:`Tensor`
        A single wavefunction component.

    Returns
    -------
    angle : NumPy :obj:`array` or PyTorch :obj:`Tensor`
        The phase (angle) of the component's wavefunction.

    """
    if isinstance(psi_comp, np.ndarray):
        ang = np.angle(psi_comp)
        if uwrap:
            ang = rest.unwrap_phase(ang)
    elif isinstance(psi_comp, torch.Tensor):
        ang = torch.angle(psi_comp)
        if uwrap:
            raise NotImplementedError("Unwrapping the complex phase is not "
                                      "implemented for PyTorch tensors.")
    if dens is not None:
        ang[dens < (dens.max() * 1e-6)] = 0
    return ang
def main(out_range=0.4):
    image = color.rgb2gray(img_as_float(data.chelsea()))
    image = exposure.rescale_intensity(image, out_range=(0, 4 * np.pi))
    image_wrapped = np.angle(np.exp(1j * image))
    image_unwrapped = unwrap_phase(image_wrapped)

    fig, ax = plt.subplots(2, 2, sharex=True, sharey=True)
    ax1, ax2, ax3, ax4 = ax.ravel()

    fig.colorbar(ax1.imshow(image, cmap='gray', vmin=0, vmax=4 * np.pi),
                 ax=ax1)
    ax1.set_title('Original')

    fig.colorbar(ax2.imshow(image_wrapped,
                            cmap='gray',
                            vmin=-np.pi,
                            vmax=np.pi),
                 ax=ax2)
    ax2.set_title('Wrapped phase')

    fig.colorbar(ax3.imshow(image_unwrapped, cmap='gray'), ax=ax3)
    ax3.set_title('After phase unwrapping')

    fig.colorbar(ax4.imshow(image_unwrapped - image, cmap='gray'), ax=ax4)
    ax4.set_title('Unwrapped minus original')

    plt.tight_layout()
    plt.show()
Esempio n. 20
0
def open_loop_wfs(wfo, plane_name='wfs'):
    """
    saves the unwrapped phase [arctan2(imag/real)] of the wfo.wf_collection at each wavelength

    It is an idealized image (exact copy) of the wavefront phase per wavelength. Only the map for the first object
    (the star) is saved. We have initialized

    Here we hardmask on the WFS map to be a circle around the beam in the pupil plane. This hard masking prevents the
     DM from acting on non-beam signal, since the DM modelled by proper is a nxn square array, but the beam is nominally
     circular for circular apertures.

    #TODO the way this is saved for naming the WFS_map is going to break if you want to do closed loop WFS on a
    #TODO woofer-tweeter system

    :param wfo: wavefront object
    :param plane_name: name of the plane to enable or disable saving the WFS map
    :return: array containing only the unwrapped phase delay of the wavefront; shape=[n_wavelengths], units=radians
    """
    star_wf = wfo.wf_collection[:, 0]
    WFS_map = np.zeros((len(star_wf), sp.grid_size, sp.grid_size))

    for iw in range(len(star_wf)):  # for each wavelength
        hardmask_pupil(star_wf[iw])
        phasemap = proper.prop_get_phase(star_wf[iw])
        WFS_map[iw] = unwrap_phase(phasemap, wrap_around=[False, False])
        WFS_map[iw][phasemap == 0] = 0  #TODO is this still necessary?

    if 'WFS' in sp.save_list or sp.closed_loop:
        wfo.save_plane(location='WFS')

    return WFS_map
Esempio n. 21
0
def unwrap_freq( im ):
    max_im    = ut.scaling(np.absolute(im))
    scaled_im = (im)/max_im*np.pi
    #ut.plotim1(im)
    im  = unwrap_phase(scaled_im.astype(np.float))/np.pi*max_im
    ut.plotim1(np.real(im),bar=1)
    return im
Esempio n. 22
0
def unwrap_freq(im):
    max_im = 0.8 * ut.scaling(np.absolute(im))
    scaled_im = (im) / max_im * np.pi
    ut.plotim1(im, bar=1, pause_close=5)
    im = unwrap_phase(scaled_im) / np.pi * max_im
    ut.plotim1(im, bar=1, pause_close=5)
    return im
Esempio n. 23
0
 def view(self,method='log-fft',marker_idx=0,ax=None,show_markers=False,scale=10,colorbar=True,cmap='gray',**kwargs):
     
     marker = self.get_marker(marker_idx)
     
     if method == 'log-fft':
         display_image = np.log(1+scale*np.abs(self.fft_image))
         label = 'log(1 + scale * |F|)'
     elif method == 'masked-log-fft':
         display_image = self.apply_mask(np.log(1+scale*np.abs(self.fft_image)),marker)
         label = 'log(1 + scale * |F|)'
     elif method == 'raw-phase':
         display_image = self.raw_phase(marker)
         label = 'Raw phase [rad.]'
     elif method == 'raw-phase-unwrapped':
         display_image = unwrap_phase(self.raw_phase(marker))
         label = 'Raw phase [rad.]'
     elif method == 'reduced-phase':
         display_image = self.reduced_phase(marker)
         label = 'Reduced phase [rad.]'
     elif method == 'reference-phase':
         display_image = self.reference_phase(marker)
         label = 'Reference phase [rad.]'
     elif method == 'residual-reference-phase':
         display_image, optim = self.reciprocal_lattice(marker,return_residual=True)
         label = 'Residual reference phase [rad.]'
     elif method == 'strain-1d':
         display_image = self.strain_1d(marker)*100
         label = 'Strain [%]'
     elif method == 'exx':
         display_image = self.strain()[0,0]*100
         label = 'Strain exx [%]'
     elif method == 'eyy':
         display_image = self.strain()[1,1]*100
         label = 'Strain eyy [%]'
     elif method == 'planar':
         display_image = (self.strain()[0,0]+self.strain()[1,1])/2*100
         label = 'Strain (exx + eyy)/2 [%]'
     elif method == 'exy' or method == 'eyx':
         display_image = self.strain()[1,0]*100
         label = 'Strain exy [%]'
     elif method == 'rotation':
         _, display_image = self.strain(return_rotation=True)/np.pi*180
         label = 'Rotation [deg.]'
     else:
         raise RuntimeError('Method {0} not recognized'.format(method))
     
     if ax is None:
         ax=plt.subplot()
     imshow=ax.imshow(display_image.T,cmap=cmap,**kwargs)
     
     if colorbar:
         divider = make_axes_locatable(ax)
         cax = divider.append_axes("right", size="5%", pad=0.05)
         cbar = plt.colorbar(imshow, cax=cax)
         cbar.set_label(label)
     
     if show_markers:
         self.marker_collection.add_markers_to_ax(ax)
     
     plt.show()
Esempio n. 24
0
def planet_phantom_example():

    TR, alpha = 24e-3, np.deg2rad(70)

    sig, df = load_data()
    coil_index = 0
    sig = sig[:, :, coil_index, :]
    df = df[:, :, coil_index]

    sig = sig.transpose((2, 0, 1))  # Move pc to 0 index
    sig = sig[..., None]

    # Do T1, T2 mapping for each pixel
    mask = np.abs(sig[1, :, :, :]) > 5e-8

    print('-------')
    print(sig.shape)
    print(df.shape)
    print(mask.shape)

    # Do the thing
    t0 = perf_counter()
    Mmap, T1est, T2est, dfest = planet(sig, alpha, TR, pc_axis=0)
    print('Took %g sec to run PLANET' % (perf_counter() - t0))

    print(sig.shape)
    print(df.shape)
    print(dfest.shape)

    # Simple phase unwrapping of off-resonance estimate
    dfest = unwrap_phase(dfest * 2 * np.pi * TR) / (2 * np.pi * TR)

    nx, ny = 3, 3

    plt.subplot(nx, ny, 2)
    plt.imshow(T1est)
    plt.title('T1 est')
    plt.axis('off')

    plt.subplot(nx, ny, 5)
    plt.imshow(T2est)
    plt.title('T2 est')
    plt.axis('off')

    plt.subplot(nx, ny, 7)
    plt.imshow(np.abs(df))
    plt.title('df Truth')
    plt.axis('off')

    plt.subplot(nx, ny, 8)
    plt.imshow(np.abs(dfest))
    plt.title('df est')
    plt.axis('off')

    plt.subplot(nx, ny, 9)
    plt.imshow(np.abs(df - dfest[:, :, 0]))
    plt.title('NRMSE: %g' % normalized_root_mse(df, dfest[:, :, 0]))
    plt.axis('off')

    plt.show()
Esempio n. 25
0
def main(images):

    rows_no = images[0].shape[0]
    cols_no = images[0].shape[1]
    all_data = np.empty([rows_no, cols_no, len(images)])

    for index, image in enumerate(images):
        gray_image = convert_image_if_needed(image, convert_to="gray")
        all_data[:, :, index] = gray_image

    phase_all = all_data[:, :, 0]

    # Apply phase calculating from 5 frames
    for index_row, row in enumerate(all_data):
        for index_col, element in enumerate(row):
            phase = phase_calculating(element)
            phase_all[index_row, index_col] = phase

    # Unwrapping
    image_unwrapped = unwrap_phase(phase_all)

    # Moving values
    image_unwrapped_positive_range = moving_values_to_the_positive_range(
        image_unwrapped)

    # Substracting fixed component
    bez_stalej = substate_fixed_component(image_unwrapped_positive_range)

    return bez_stalej
Esempio n. 26
0
def test_unwrap_3d_all_masked():
    # all elements masked
    image = np.ma.zeros((10, 10, 10))
    image[:] = np.ma.masked
    unwrap = unwrap_phase(image)
    assert_(np.ma.isMaskedArray(unwrap))
    assert_(np.all(unwrap.mask))

    # 1 unmasked element, still zero edges
    image = np.ma.zeros((10, 10, 10))
    image[:] = np.ma.masked
    image[0, 0, 0] = 0
    unwrap = unwrap_phase(image)
    assert_(np.ma.isMaskedArray(unwrap))
    assert_(np.sum(unwrap.mask) == 999)   # all but one masked
    assert_(unwrap[0, 0, 0] == 0)
Esempio n. 27
0
def retro_wfs(star_fields, wfo, plane_name='wfs'):
    """
    Retrospective wfs (measure an old field)

    :param star_fields:
    :param wfo:
    :param plane_name:
    :return:
    """
    WFS_map = np.zeros((len(star_fields), sp.grid_size, sp.grid_size))
    from skimage.restoration import unwrap_phase
    for iw in range(len(star_fields)):
        quick2D(np.angle(star_fields),
                title='before mask',
                colormap='sunlight')
        phasemap = np.angle(star_fields[iw])
        masked_phase = np.ma.masked_equal(phasemap, 0)
        quick2D(masked_phase, title='before unwrap', colormap='sunlight')
        WFS_map[iw] = unwrap_phase(masked_phase, wrap_around=[False, False])
        WFS_map[iw][phasemap == 0] = 0
        quick2D(WFS_map[iw], title='after')
    if 'retro_closed_wfs' in sp.save_list:
        wfo.save_plane(location='WFS_map')

    return WFS_map
Esempio n. 28
0
    def from_ftdata(ft, x, y, unwrap=True):
        """Generate a PTF from the Fourier transform of a PSF.

        Parameters
        ----------
        ft : `numpy.ndarray`
            2D ndarray of Fourier transform data
        x : `numpy.ndarray`
            1D ndarray of x (axis 1) coordinates
        y : `numpy.ndarray`
            1D ndarray of y (axis 0) coordinates
        unwrap : `bool`, optional
            if True, unwrap phase

        Returns
        -------
        `PTF`
            a new PTF instance

        """
        ft = e.angle(ft)
        cy, cx = (int(e.ceil(s / 2)) for s in ft.shape)
        offset = ft[cy, cx]
        if offset != 0:
            ft /= offset

        if unwrap:
            from skimage import restoration
            ft = restoration.unwrap_phase(ft)
        return PTF(ft, x, y)
Esempio n. 29
0
def test_invalid_input():
    with testing.raises(ValueError):
        unwrap_phase(np.zeros([]))
    with testing.raises(ValueError):
        unwrap_phase(np.zeros((1, 1, 1, 1)))
    with testing.raises(ValueError):
        unwrap_phase(np.zeros((1, 1)), 3 * [False])
    with testing.raises(ValueError):
        unwrap_phase(np.zeros((1, 1)), 'False')
Esempio n. 30
0
def test_invalid_input():
    with testing.raises(ValueError):
        unwrap_phase(np.zeros([]))
    with testing.raises(ValueError):
        unwrap_phase(np.zeros((1, 1, 1, 1)))
    with testing.raises(ValueError):
        unwrap_phase(np.zeros((1, 1)), 3 * [False])
    with testing.raises(ValueError):
        unwrap_phase(np.zeros((1, 1)), 'False')
def unwrap_im(im):
    """
    Unwrap a np.uint8 phase image. Attention : it doubles the phase jumps.

    Parameters
    ----------

    im: numpy.uint8
        8-bit grayscale phase image to be unwrapped

    Returns
    ----------
    numpy.uint8 unwrapped image

    """

    im1 = im

    # ax1 = plt.subplot(241)
    # ax1.imshow(im1,'gray')
    # ax1.set_title('[0, 255]')
    # plt.xlim(1,900)
    # plt.ylim(1,900)
    # plt.xticks([1, 900])
    # plt.yticks([1, 900])

    im2 = exposure.rescale_intensity(1.0 * im1,
                                     in_range=(0, 255),
                                     out_range=(0, 4 * np.pi))

    # ax2 = plt.subplot(242)
    # ax2.imshow(im2,'gray')
    # ax2.set_title(r'$[0, 4\pi]$')
    # plt.xlim(1,900)
    # plt.ylim(1,900)
    # plt.xticks([1, 900])
    # plt.yticks([1, 900])

    im3 = np.angle(np.exp(1j * im2))

    # ax3 = plt.subplot(243)
    # ax3.imshow(im3,'gray')
    # ax3.set_title(r'$[-\pi, +\pi]$')
    # plt.xlim(1,900)
    # plt.ylim(1,900)
    # plt.xticks([1, 900])
    # plt.yticks([1, 900])

    im4 = restoration.unwrap_phase(im3)

    # ax4 = plt.subplot(244)
    # ax4.imshow(im4,'gray')
    # ax4.set_title(r'Modified image: ??')
    # plt.xlim(1,900)
    # plt.ylim(1,900)
    # plt.xticks([1, 900])
    # plt.yticks([1, 900])

    return im4
Esempio n. 32
0
def check_unwrap(image, mask=None):
    image_wrapped = np.angle(np.exp(1j * image))
    if mask is not None:
        print('Testing a masked image')
        image = np.ma.array(image, mask=mask, fill_value=0.5)
        image_wrapped = np.ma.array(image_wrapped, mask=mask, fill_value=0.5)
    image_unwrapped = unwrap_phase(image_wrapped, seed=0)
    assert_phase_almost_equal(image_unwrapped, image)
Esempio n. 33
0
def check_unwrap(image, mask=None):
    image_wrapped = np.angle(np.exp(1j * image))
    if mask is not None:
        print('Testing a masked image')
        image = np.ma.array(image, mask=mask)
        image_wrapped = np.ma.array(image_wrapped, mask=mask)
    image_unwrapped = unwrap_phase(image_wrapped, seed=0)
    assert_phase_almost_equal(image_unwrapped, image)
Esempio n. 34
0
def check_unwrap(image, mask=None):
    image_wrapped = np.angle(np.exp(1j * image))
    if not mask is None:
        print('Testing a masked image')
        image = np.ma.array(image, mask=mask)
        image_wrapped = np.ma.array(image_wrapped, mask=mask)
    image_unwrapped = unwrap_phase(image_wrapped)
    assert_phase_almost_equal(image_unwrapped, image)
Esempio n. 35
0
def plot_2d_complex(input_array,
                    mode='linear',
                    name='input_array',
                    *args,
                    **kwargs):
    fig, (ax1, ax2) = plt.subplots(1, 2)
    if 'coords' in kwargs:
        if mode == 'linear':
            im1 = ax1.imshow((np.abs(input_array)), extent=kwargs['coords'])
        if mode == 'log':
            im1 = ax1.imshow(np.log((np.abs(input_array))),
                             extent=kwargs['coords'])
        ax1.title.set_text('magnitude of ' + str(name) + ' ( in ' + str(mode) +
                           ' scale)')
        ax1.title.set_y(1.08)
        fig.colorbar(im1, ax=ax1)
        scaling = np.round(np.log10(np.abs(kwargs['coords'][0])))
        scaling = np.int(scaling)
        ax1.set_xlabel('axes in 10^(' + str(scaling) + ')')
        im2 = ax2.imshow(unwrap_phase(np.angle(input_array)),
                         extent=kwargs['coords'])
        ax2.title.set_text('phase of ' + str(name))
        ax2.title.set_y(1.08)
        fig.subplots_adjust(right=1.75)
        ax2.set_xlabel('axes in 10^(' + str(scaling) + ')')
        fig.colorbar(im2, ax=ax2)
    else:
        if mode == 'linear':
            im1 = ax1.imshow((np.abs(input_array)))
        if mode == 'log':
            im1 = ax1.imshow(np.log((np.abs(input_array))))
        ax1.title.set_text('magnitude  of ' + str(name) + ' ( in ' +
                           str(mode) + ' scale)')
        ax1.title.set_y(1.08)
        fig.colorbar(im1, ax=ax1)
        im2 = ax2.imshow(unwrap_phase(np.angle(input_array)))
        ax2.title.set_text('phase of ' + str(name))
        ax2.title.set_y(1.08)
        fig.subplots_adjust(right=1.75)
        fig.colorbar(im2, ax=ax2)
    plt.show()
    if 'print_max' in args:
        print('maximum value of ' + str(name) + ': ', np.max(abs(input_array)))
        print('minimum value of ' + str(name) + ': ', np.min(abs(input_array)))
        print('location of maxima in ' + str(name) + ': ',
              np.where(abs(input_array) == np.max(abs(input_array))))
Esempio n. 36
0
def test_unwrap_2d_all_masked():
    # Segmentation fault when image is masked array with a all elements masked
    # GitHub issue #1347
    # all elements masked
    image = np.ma.zeros((10, 10))
    image[:] = np.ma.masked
    unwrap = unwrap_phase(image)
    assert_(np.ma.isMaskedArray(unwrap))
    assert_(np.all(unwrap.mask))

    # 1 unmasked element, still zero edges
    image = np.ma.zeros((10, 10))
    image[:] = np.ma.masked
    image[0, 0] = 0
    unwrap = unwrap_phase(image)
    assert_(np.ma.isMaskedArray(unwrap))
    assert_(np.sum(unwrap.mask) == 99)  # all but one masked
    assert_(unwrap[0, 0] == 0)
Esempio n. 37
0
def test_unwrap_2d_all_masked():
    # Segmentation fault when image is masked array with a all elements masked
    # GitHub issue #1347
    # all elements masked
    image = np.ma.zeros((10, 10))
    image[:] = np.ma.masked
    unwrap = unwrap_phase(image)
    assert_(np.ma.isMaskedArray(unwrap))
    assert_(np.all(unwrap.mask))

    # 1 unmasked element, still zero edges
    image = np.ma.zeros((10, 10))
    image[:] = np.ma.masked
    image[0, 0] = 0
    unwrap = unwrap_phase(image)
    assert_(np.ma.isMaskedArray(unwrap))
    assert_(np.sum(unwrap.mask) == 99)    # all but one masked
    assert_(unwrap[0, 0] == 0)
Esempio n. 38
0
def load_folder_pupil(folder, flag = 'mod', radius = 49 ):
    # load and plot all the pupil functions in the chosen folder.
    pupil_list = glob.glob(folder + '*'+ flag+'*.npy')
    pupil_list.sort(key = os.path.getmtime)
    for pname in pupil_list:
        session_name = os.path.basename(pname).split('.')[0]
        pupil_name = session_name + '_pupil'
        print(session_name)
        raw_pupil = unwrap_phase(np.load(pname))/(2*np.pi) # convert to wavelength
        pupil = pupil_crop(raw_pupil,mask = True, rad = radius)
        figp = pupil_showcross(pupil)
        figp.savefig(folder+pupil_name)
        plt.close()
Esempio n. 39
0
def single_2Dgrating_analyses(img, img_ref=None, harmonicPeriod=None,
                              unwrapFlag=True, plotFlag=True, verbose=False):
    """
    Function to process the data of single 2D grating Talbot imaging. It
    wraps other functions in order to make all the process transparent

    """

    # Obtain Harmonic images
    h_img = single_grating_harmonic_images(img, harmonicPeriod,
                                           plotFlag=plotFlag,
                                           verbose=verbose)

    if img_ref is not None:  # relative wavefront

        h_img_ref = single_grating_harmonic_images(img_ref, harmonicPeriod,
                                                   plotFlag=plotFlag,
                                                   verbose=verbose)

        int00 = np.abs(h_img[0])/np.abs(h_img_ref[0])
        int01 = np.abs(h_img[1])/np.abs(h_img_ref[1])
        int10 = np.abs(h_img[2])/np.abs(h_img_ref[2])

        if unwrapFlag is True:

            arg01 = (unwrap_phase(np.angle(h_img[1]), seed=72673) -
                     unwrap_phase(np.angle(h_img_ref[1]), seed=72673))

            arg10 = (unwrap_phase(np.angle(h_img[2]), seed=72673) -
                     unwrap_phase(np.angle(h_img_ref[2]), seed=72673))

        else:
            arg01 = np.angle(h_img[1]) - np.angle(h_img_ref[1])
            arg10 = np.angle(h_img[2]) - np.angle(h_img_ref[2])

    else:  # absolute wavefront

        int00 = np.abs(h_img[0])
        int01 = np.abs(h_img[1])
        int10 = np.abs(h_img[2])

        if unwrapFlag is True:

            arg01 = unwrap_phase(np.angle(h_img[1]), seed=72673)
            arg10 = unwrap_phase(np.angle(h_img[2]), seed=72673)
        else:
            arg01 = np.angle(h_img[1])
            arg10 = np.angle(h_img[2])

    if unwrapFlag is True:  # remove pi jump
        arg01 -= int(np.round(np.mean(arg01/np.pi)))*np.pi
        arg10 -= int(np.round(np.mean(arg10/np.pi)))*np.pi

    darkField01 = int01/int00
    darkField10 = int10/int00

    return [int00, int01, int10,
            darkField01, darkField10,
            arg01, arg10]
Esempio n. 40
0
def wave_retrieval(data,r_data=None,filt=None,STEPS=False,s=0.1,ARGS=False):
  # go to fourier space
  f_data = np.fft.fft2(data)
  # get the k-vector (lots of finagling here for fft shift crap)
  if r_data is None:
    K = get_wave(f_data)
    kx,ky = np.fft.fftfreq(f_data.shape[0]),np.fft.fftfreq(f_data.shape[1])
    k = kx[K[0]],ky[K[1]]
    nx,ny = data.shape
    Y,X = np.meshgrid(np.arange(nx),np.arange(ny),sparse=False,indexing='xy')
  #  phplot.imageshow(data)
  #  phplot.imageshow(np.real(r_data))
  #  phplot.imageshow(np.real(r_data*np.exp(+1j*2.*np.pi*(k[0]*X+k[1]*Y))))
    # reference beam
    r_data = np.exp(+1j*2.*np.pi*(k[0]*X+k[1]*Y))


  # filter k-space with a gaussian around data of interest
  if filt is None:
    try:
      gf_data = f_gaussian(f_data,K)*f_data
    except UnboundLocalError:
      K = get_wave(f_data)
    finally:
      gf_data = f_gaussian(f_data,K)*f_data
      filt = np.ones(f_data.shape)
      filt = f_gaussian(filt,K)*filt
#      band = get_band(data,K)
#      filt = f_bandpass(filt,band)
#      filt = hilbert_transform(filt,'x')
  else:
    gf_data = filt*f_data
  # check it out!!
#  phplot.imageshow(phplot.dB_data(gauss_filter))
  # go back to xy space
  g_data = np.fft.ifft2(gf_data)

  o_data = g_data*r_data  # retrieve the wrapped phase from the digital reference beam
  wrapped_phase = np.arctan2(o_data.imag,o_data.real)
  # unwrap the phase (may be unneccesary)
  unwrapped_phase = unwrap_phase(wrapped_phase)
  phase = unwrapped_phase
  #phase = wrapped_phase

  if STEPS:
    return data,f_data,gauss_filter,wrapped_phase,unwrapped_phase,plane,phase

  if ARGS:
    return -phase,r_data,filt

  return -phase
Esempio n. 41
0
def parse_enz_solution(cfg, betak):
    if betak.ndim == 2:
        gpf = cfg.cpsf.czern.eval_grid(betak[:, 0])
    else:
        gpf = cfg.cpsf.czern.eval_grid(betak)
    wrph = np.arctan2(gpf.imag, gpf.real)
    wrph = np.mod(wrph, 2*np.pi) - np.pi

    ut1 = time()
    unph = unwrap_phase(wrph.reshape(
        (cfg.fit_L, cfg.fit_K), order='F')).ravel(order='F')
    ut2 = time()

    ft1 = time()
    alpha_hat = cfg.phase_fit.fit(unph)
    ft2 = time()

    alpha_hat[0] = 0.0

    return alpha_hat, ft2 - ft1, ut2 - ut1, wrph, unph
Esempio n. 42
0
def compute_local_phase_field(camp):
    """ Compute local phase of each cell
    """
    width, height, depth = camp.shape

    # compute thetas
    tau = compute_tau(camp)

    theta = np.empty((width, height)).tolist()
    for j in range(width):
        for i in range(height):
            cur = compute_phase_variable(camp[i, j], tau)
            theta[i][j] = np.array(cur)
    theta = np.rollaxis(np.array(theta), 2, 0)

    # fix phase jumps greater than PI
    for i in range(len(theta)):
        theta[i] = unwrap_phase(theta[i])

    return theta
Esempio n. 43
0
def hilbert_retrieval(data,plane=None,filt=None,STEPS=False,direction='x',ARGS=False):
  # fourier transform data and filter
  window_f = np.hanning
  w2 = np.sqrt(np.outer(window_f(data.shape[0]),window_f(data.shape[1])))
  f_data = np.fft.fft2(data)
  if filt is None:
    band = get_band(f_data)
    filt_f_data = f_bandpass(f_data,band)
    hilbert_f_data = hilbert_transform(filt_f_data,direction)
    filt = np.ones(f_data.shape)
    filt = f_bandpass(filt,band)
    filt = hilbert_transform(filt,direction)
  else:
    hilbert_f_data = f_data *filt

  # hilbert-transform
#  phplot.imageshow(phplot.dB_data(filt_f_data))
  hilbert_data = np.fft.ifft2(hilbert_f_data)

  # retrieve the wrapped phase
  wrapped_phase = np.arctan2(hilbert_data.imag,hilbert_data.real)

  # unwrap the phase
  unwrapped_phase = unwrap_phase(wrapped_phase)

  # flatten the data (if required - some methods can use the same level for all data)
  if plane is None:
    plane = diff_level(unwrapped_phase)
  phase = unwrapped_phase - plane

  if STEPS:
    return data,f_data,filt_f_data,hilbert_f_data,hilbert_data,wrapped_phase,unwrapped_phase,plane,phase

  if ARGS:
    return -phase,plane,filt
  return -phase
Esempio n. 44
0
def diagnosticPlot(solver):
    """
    Returns a matplotlib figure
    """
    ur = pint.UnitRegistry()
    MASK_CUTOFF = 1.0
    # N_PHASE_TICKS = 6
    NUM_COLOURS = 100
    # DISP_FRACTION = 1/10
    KS_FRACTION = 1/4
    ur = UnitRegistry()
    x, y = solver.grid.getSpatialGrid(scaled=False)
    x *= 1e6
    y *= 1e6

    x_ax = x[0, :]
    y_ax = y[:, 0]
    psi = solver.psi.get()
    # n = solver.n.get()
    P = solver.Pdt.get()
    P /= solver.dt

    N = psi.shape[0]
    time = solver.times
    energy = solver.energy
    number = solver.number
    pumpSlice = P[N/2, :]
    PthScaled = solver.Pth / np.max(P)
    pumpSlice /= np.max(P)

    rMiddle = abs(x[N/2, np.argmax(pumpSlice)])
    density = solver.getDensity(scaled=True)
    pumpCircle = plt.Circle((0.0, 0.0), radius=rMiddle, color='w',
                            linestyle='dashed', fill=False)

    fig, axes = plt.subplots(2, 3)
    time = solver.times
    energy = solver.energy
    number = solver.number

    density = solver.getDensity(scaled=True)
    pumpCircle = plt.Circle((0.0, 0.0), radius=rMiddle, color='w',
                            linestyle='dashed', fill=False)

    fig, axes = plt.subplots(2, 3)

    fig, axes = plt.subplots(2, 3)
    p0 = axes[0, 0].contourf(x, y, density, NUM_COLOURS)

    # RS density
    axes[0, 0].set_title("Density $\mu m ^{-2}$")
    # axes[0, 0].set_aspect('equal', 'box')
    axes[0, 0].set_aspect(1./axes[0, 0].get_data_ratio())
    axes[0, 0].add_artist(pumpCircle)
    plt.colorbar(p0, ax=axes[0, 0], fraction=0.046, pad=0.04)

    # KS density
    ksDensity = np.absolute(fft.fftshift(fft.fft2(psi)))
    ksLowerLim = int(N/2 - KS_FRACTION * N / 2)
    ksUpperLim = int(N/2 + KS_FRACTION * N / 2)
    p1 = axes[1, 0].contourf(x_ax[ksLowerLim:ksUpperLim],
                             y_ax[ksLowerLim:ksUpperLim],
                             ksDensity[ksLowerLim:ksUpperLim,
                                       ksLowerLim:ksUpperLim] /
                             np.max(ksDensity), NUM_COLOURS)
    axes[1, 0].set_title("KS Density")
    axes[1, 0].set_aspect('equal')
    plt.colorbar(p1, ax=axes[1, 0], fraction=0.046, pad=0.04)

    # Phase
    # p2 = axes[0, 1].contourf(x, y, np.angle(psi) + np.pi)
    phase = unwrap_phase(np.angle(psi))
    # Mask the values that are out the damping region are ignored
    mask = solver.damping.get() < MASK_CUTOFF
    phase = np.ma.array(phase, mask=mask) / np.pi
    # Set the minumum phase to zero
    phase -= np.min(phase)
    # maxPhase = np.ceil(np.max(phase) / np.pi)
    # minPhase = np.floor(np.min(phase) / np.pi)
    # step = np.ceil((maxPhase - minPhase) / N_PHASE_TICKS)
    # ticks = np.pi * np.arange(minPhase, maxPhase + 1, step=step)
    # labels = ["$%d \pi$" % i for i in np.arange(minPhase, maxPhase + 1)]
    p2 = axes[0, 1].contourf(x, y, phase, NUM_COLOURS)
    axes[0, 1].set_title("Phase")
    # axes[0, 1].set_aspect('equal', 'box')
    axes[0, 1].set_aspect(1./axes[0, 1].get_data_ratio())
    pumpCircle = plt.Circle((0.0, 0.0), radius=rMiddle, color='w',
                            linestyle='dashed', fill=False)
    axes[0, 1].add_artist(pumpCircle)
    cbar2 = plt.colorbar(p2, ax=axes[0, 1], fraction=0.046, pad=0.04)
    labels = [t.get_text() + '$\pi$' for t in cbar2.ax.get_yticklabels()]
    # cbar2 = plt.colorbar(p2, ax=axes[0, 1],
    #                      ticks=ticks,
    #                      fraction=0.046, pad=0.04)
    cbar2.ax.set_yticklabels(labels)
    # cbar2 = plt.colorbar(p2, ax=axes[0, 1],
    #                      ticks=np.pi * np.array([0, 1.0, 2.0]),
    #                      fraction=0.046, pad=0.04)
    # cbar2.ax.set_yticklabels(['0', '$\pi$', '$2\pi$'])

    # Resovoir density
    # p4 = axes[1, 1].contourf(x, y, n, NUM_COLOURS)
    # axes[1, 1].set_title("Resovoir density")
    # # axes[1, 1].set_aspect('equal', 'box')
    # axes[1, 1].set_aspect(1./axes[1, 1].get_data_ratio())
    # pumpCircle = plt.Circle((0.0, 0.0), radius=rMiddle, color='w',
    #                         linestyle='dashed', fill=False)
    # axes[1, 1].add_artist(pumpCircle)
    # plt.colorbar(p4, ax=axes[1, 1], fraction=0.046, pad=0.04)

    # Dispersion relation
    # dispLowerLim = int(N/2 - DISP_FRACTION * N / 2)
    # dispUpperLim = int(N/2 + DISP_FRACTION * N / 2)
    # Account for the fact that we have cut off some of the k axis in the
    # spectrum
    spectMax = int(solver.spectrum.shape[1])//2
    k_ax = solver.grid.k_axis_scaled[N//2 - spectMax:N//2 + spectMax]
    # Omega axis in units of 1 / seconds
    omega_axis = solver.omega_axis / ur.Quantity(solver.charT,
                                                 ur.second.to_base_units().
                                                 units)
    # Energy axis in milliev
    energy_axis = (omega_axis * ur.hbar).to("millieV").magnitude
    m = ur.Quantity(solver.paramContainer.getOutputParams()["m"].magnitude,
                    "electron_mass")
    L = ur.Quantity(solver.paramContainer.getOutputParams()["charL"].magnitude,
                    "micrometer")
    dispCurve = ((ur.hbar**2 * k_ax**2) / (2 * m * L**2)).to("millieV")\
        .magnitude
    # p4 = axes[1, 1].contourf(solver.grid.k_axis_scaled[dispLowerLim:
    #                                                    dispUpperLim],
    #                          energy_axis,
    #                          np.absolute(solver.spectrum)[:, dispLowerLim:
    #                                                       dispUpperLim],
    #                          NUM_COLOURS)
    axes[1, 1].contourf(k_ax, energy_axis, np.absolute(solver.spectrum),
                        NUM_COLOURS)
    axes[1, 1].plot(k_ax, dispCurve, color='w', ls=":", lw=0.2)

    yu = 5
    yl = -2
    axes[1, 1].set_ylim([yl, yu])
    # yl = - 1
    # print "yu = %f" % yu
    # print axes[1, 1].get_ylim()
    # axes[1,1].set_ylim([-1, 10])
    # p4 = axes[1, 1].contourf(np.absolute(solver.spectrum)[:, N/4:3*N/4],
    # NUM_COLOURS)
    axes[1, 1].set_title("Dispersion Relation")
    # axes[1, 0].set_aspect('equal')
    axes[1, 1].set_aspect(1./axes[1, 1].get_data_ratio())
    axes[1, 1].set_xlabel('k')
    axes[1, 1].set_ylabel('E (meV)')
    # plt.colorbar(p1, ax=axes[1, 0], fraction=0.046, pad=0.04)

    # Radial profile
    psiMax = np.max(np.absolute(psi[N/2, :]))
    # axes[0, 2].plot(x[N/2, :], np.absolute(psi[N/2, :]) / psiMax,
    #                 x[N/2, :], pumpFunction(x, y)[N/2, :] / pfMax)

    # axes[0, 2].axhline(PthScaled)
    axes[0, 2].plot(x_ax[N/4:3*N/4], np.absolute(psi[N/2, N/4:3*N/4])/psiMax,
                    x_ax[N/4:3*N/4], pumpSlice[N/4:3*N/4])
    axes[0, 2].set_title("Radial Profile")
    axes[0, 2].set_ylabel("Density")
    axes[0, 2].set_xlabel("x")
    axes[0, 2].set_aspect(1./axes[0, 2].get_data_ratio())

    # Energy and number
    axes[1, 2].plot(time, energy, color='k')
    axes[1, 2].ticklabel_format(style='sci', scilimits=(-3, 3), axis='y')
    # axes[1, 2].set_title("Energy")
    axes[1, 2].set_xlabel("Time")
    axes[1, 2].set_ylabel("Energy")

    ax2 = axes[1, 2].twinx()
    ax2.plot(time, number, 'b')
    ax2.ticklabel_format(style='sci', scilimits=(-3, 3), axis='y')
    ax2.set_ylabel("Number", color='b')
    for t1 in ax2.get_yticklabels():
        t1.set_color('b')
    ax2.set_aspect(1./ax2.get_data_ratio())

    # Plot lines to indicate the start and end of spectrum acquisition
    axes[1, 2].axvline(solver.dt * solver.spectStartStep, linestyle='-')
    axes[1, 2].axvline(solver.dt * solver.spectEndStep, linestyle='-')
    axes[1, 2].set_aspect(1./axes[1, 2].get_data_ratio())
    fig.tight_layout()
    return fig
    wpu.plot_slide_colorbar(intensity,
                            title='Intensity',
                            xlabel=r'x [$\mu m$]',
                            ylabel=r'y [$\mu m$]',
                            extent=wpu.extent_func(dpc_1d, pixelSize)*1e6)

    # %% Dark Field

    wpu.plot_slide_colorbar(dk_field, title='Dark Field',
                            xlabel=r'x [$\mu m$]',
                            ylabel=r'y [$\mu m$]',
                            extent=wpu.extent_func(dpc_1d, pixelSize)*1e6)

    # %% DPC

    dpc_1d = unwrap_phase(dpc_1d)
    wpu.plot_slide_colorbar(dpc_1d/np.pi/2.0,
                            title=r'DPC [$\pi rad$]',
                            xlabel=r'x [$\mu m$]',
                            ylabel=r'y [$\mu m$]',
                            extent=wpu.extent_func(dpc_1d, pixelSize)*1e6)

    # %%
    xx, yy = wpu.realcoordmatrix(dpc_1d.shape[1], pixelSize,
                                 dpc_1d.shape[0], pixelSize)
    wpu.plot_profile(xx*1e3, yy*1e3, dpc_1d/np.pi/2.0,
                     xlabel='[mm]', ylabel='[mm]')

    # %% chi2

    plt.figure()
 def complex(self, new):
     self._complex = new
     self._amplitude = abs(new)
     self._phase = unwrap_phase(np.angle(new))
Esempio n. 47
0
    n = 1.33
    NA = 1.00
    f = 9000
    nIt = 4

# PSF = PSF2
path = path1

ii=1
plt.close('all')


for pfile in PSF_list30:
    PSF = np.load(pfile)
    PF = retrievePF(PSF, dx, dz, l, n, NA, f, nIt)
    PF = unwrap_phase(PF)
    plt.figure(figsize=(4.5,4))
#     plt.imshow(PF, cmap = 'RdBu', )
    im = plt.imshow(PF, cmap = plt.cm.RdBu, extent=(-2,2,2,-2))
    plt.tick_params(
        axis = 'both',
        which = 'both', 
        bottom = 'off',
        top = 'off',
        right = 'off',
        left = 'off',
        labelleft='off',
        labelbottom = 'off')


    plt.tight_layout()
Esempio n. 48
0
        #if i == h/2:	
        #    plt.figure()
	#    plt.plot(fft)	
        
	# do shifting
	fft_shift = fft
	# clear duplicates and DC
	fft_shift[0:w/2]=0
	fft_shift[w-1:len(row)]=0	
	# shift
	fft_shift = np.roll(fft_shift,ind)
	c = np.fft.ifft(fft_shift)
	phi[i,:] = np.log(c).imag

unwrapped = unwrap_phase(phi)

plt.figure(figsize = (12,6) )
plt.gray()

plt.subplot(131)
plt.imshow(img)
plt.title("Image")

plt.subplot(132)
plt.imshow(phi)
plt.title("Wrapped Phase")

plt.subplot(133)
plt.imshow(unwrapped)
plt.title("Unwrapped Phase")
 def unwrap(self):
     unwrapped = unwrap_phase(self._PF.phase)
     return unwrapped
Esempio n. 50
0
"""

import numpy as np
from matplotlib import pyplot as plt
from skimage import data, img_as_float, color, exposure
from skimage.restoration import unwrap_phase


# Load an image as a floating-point grayscale
image = color.rgb2gray(img_as_float(data.chelsea()))
# Scale the image to [0, 4*pi]
image = exposure.rescale_intensity(image, out_range=(0, 4 * np.pi))
# Create a phase-wrapped image in the interval [-pi, pi)
image_wrapped = np.angle(np.exp(1j * image))
# Perform phase unwrapping
image_unwrapped = unwrap_phase(image_wrapped)

fig, ax = plt.subplots(2, 2)
ax1, ax2, ax3, ax4 = ax.ravel()

fig.colorbar(ax1.imshow(image, cmap='gray', vmin=0, vmax=4 * np.pi), ax=ax1)
ax1.set_title('Original')

fig.colorbar(ax2.imshow(image_wrapped, cmap='gray', vmin=-np.pi, vmax=np.pi), ax=ax2)
ax2.set_title('Wrapped phase')

fig.colorbar(ax3.imshow(image_unwrapped, cmap='gray'), ax=ax3)
ax3.set_title('After phase unwrapping')

fig.colorbar(ax4.imshow(image_unwrapped - image, cmap='gray'), ax=ax4)
ax4.set_title('Unwrapped minus original')
Esempio n. 51
0
 def unwrap(self):
     self.phi = unwrap_phase(self.phi)
     #self.phi = np.unwrap(self.phi)
     pass
templateX, templateY, templateWidth  = locate_glowplug(img, approxTemplate, debug=False)
template = get_autolite_template(templateWidth+templateSlop, img_h/2)

## perform analysis
if not os.path.exists('results'):
    os.makedirs('results')

frameNums = map(str,frameNums)
for i in frameNums:
    imageFilename = ('cropped/' + imageFileBase + i + '_crop.jpg')

    orig = WTP.imagefile2dat(imageFilename)

    wrapped = WTP.performWTP(wavelet_type = wavelet_type, ridge_alg = ridge_alg, 
                        starting_scale = starting_scale, ending_scale=ending_scale, use_FFT=use_FFT, Morlet_sigma=Morlet_sigma)
    unwrapped = unwrap_phase(wrapped)

    phase = unbias_image(unwrapped)

    masked = remove_glowplug(phase, templateX-templateSlop/2, templateY, template)

    x, y, centered  = center_image_x(masked, templateX + templateWidth/2, templateY, dx)

    r, f_abel, deriv, smoothed  = perform_abel_discontinuous(x, centered)

    delta_n = f_abel*lam / (2*np.pi)
    rho= (n_air - delta_n - 1)/K_air

    fileroot = ('results/' + imageFileBase + i + '_crop')
    np.savetxt(fileroot+"_orig.csv", orig, delimiter=",")
    np.savetxt(fileroot+"_wrapped.csv", wrapped, delimiter=",")
Esempio n. 53
0
def test_unwrap_3d_middle_wrap_around():
    # Segmentation fault in 3D unwrap phase with middle dimension connected
    # GitHub issue #1171
    image = np.zeros((20, 30, 40), dtype=np.float32)
    unwrap = unwrap_phase(image, wrap_around=[False, True, False])
    assert_(np.all(unwrap == 0))
Esempio n. 54
0
def test_unwrap_2d_compressed_mask():
    # ValueError when image is masked array with a compressed mask (no masked
    # elments).  GitHub issue #1346
    image = np.ma.zeros((10, 10))
    unwrap = unwrap_phase(image)
    assert_(np.all(unwrap == 0))