def angularIntegrationBackDetector(n_bins=100,center=(265,655),min_bin=40,max_bin=800,threshold=(0.001,10000)):
	    ''' 
	    Does the circular integration and q-calibration on the back
	    detector, with an additional threshold masking
	    '''
	
	    # -- parameters
	    Ldet = 5080. # detector to sample distance 
	    dpix = 0.055 # um (pixel size)
	    energy = 8.4 #keV
	
	    # -- constants
	    h = 4.135667516*1e-18 #kev*sec
	    c = 3*1e8 #m/s
	    lambda_ = h*c/energy*1e10 # wavelength of the X-rays
	
	    # -- calulate q-range
	    width,spacing = float(max_bin-min_bin)/float(n_bins),0
	    edges = roi.ring_edges(min_bin, width, spacing, n_bins)
	    two_theta = utils.radius_to_twotheta(Ldet, edges*dpix)
	    q_val = utils.twotheta_to_q(two_theta, lambda_)
	    q = np.mean(q_val, axis=1)
	
	    # -- apply threshold mask data
	    self.data[data<threshold[0]]=0
	    self.data[data>threshold[1]]=0
	
	    # -- angular average 
	    Iq= circularAverage(self.data,calibrated_center=center,nx=n_bins,min_x=min_bin,max_x=max_bin)
	    print q.shape,Iq[1].shape
	    return Iq[0],Iq[1]
Exemple #2
0
def test_circular_average():
    image = np.zeros((12, 12))
    calib_center = (5, 5)
    inner_radius = 1

    edges = roi.ring_edges(inner_radius, width=1, spacing=1, num_rings=2)
    labels = roi.rings(edges, calib_center, image.shape)
    image[labels == 1] = 10
    image[labels == 2] = 10

    bin_cen, ring_avg = roi.circular_average(image, calib_center, nx=6)

    assert_array_almost_equal(bin_cen, [0.70710678, 2.12132034,
                                        3.53553391,  4.94974747,  6.36396103,
                                        7.77817459], decimal=6)
    assert_array_almost_equal(ring_avg, [8., 2.5, 5.55555556, 0.,
                                         0., 0.], decimal=6)

    bin_cen1, ring_avg1 = roi.circular_average(image, calib_center, min_x=0,
                                               max_x=10, nx=None)
    assert_array_almost_equal(bin_cen1, [0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5,
                                         7.5, 8.5])
    mask = np.ones_like(image)
    mask[4:6, 2:3] = 0

    bin_cen_masked, ring_avg_masked = roi.circular_average(image, calib_center,
                                                           min_x=0, max_x=10,
                                                           nx=6, mask=mask)
    assert_array_almost_equal(bin_cen_masked, [0.83333333,  2.5, 4.16666667,
                              5.83333333,  7.5, 9.16666667])

    assert_array_almost_equal(ring_avg_masked, [8.88888889,  3.84615385,  2.5,
                              0.,  0.,  0.])
Exemple #3
0
def test_segmented_rings():
    center = (75, 75)
    img_dim = (150, 140)
    first_q = 5
    delta_q = 5
    num_rings = 4  # number of Q rings
    slicing = 4

    edges = roi.ring_edges(first_q, width=delta_q, spacing=4,
                           num_rings=num_rings)
    print("edges", edges)

    label_array = roi.segmented_rings(edges, slicing, center,
                                      img_dim, offset_angle=0)
    print("label_array for segmented_rings", label_array)

    # Did we draw the right number of ROIs?
    label_list = np.unique(label_array.ravel())
    actual_num_labels = len(label_list) - 1
    num_labels = num_rings * slicing
    assert_equal(actual_num_labels, num_labels)

    # Did we draw the right ROIs? (1-16 with some zeros around too)
    assert_array_equal(label_list, np.arange(num_labels + 1))

    # A brittle test to make sure the exactly number of pixels per label
    # is never accidentally changed:
    # number of pixels per ROI
    num_pixels = np.bincount(label_array.ravel())
    expected_num_pixels = [18372, 59, 59, 59, 59, 129, 129, 129,
                           129, 200, 200, 200, 200, 269, 269, 269, 269]
    assert_array_equal(num_pixels, expected_num_pixels)
def radial_integration_back_detector(data,n_bins=300,mask=None,center=(265,655),min_bin=-np.pi,max_bin=np.pi,threshold=(0.001,10000)):
    ''' 
    Does the circular integration and q-calibration on the back
    detector, with an additional threshold masking
    '''

    # -- parameters
    Ldet = 5080. # detector to sample distance 
    dpix = 0.055 # um (pixel size)
    energy = 8.4 #keV
    inner_radius,width,spacing,num_rings=180,120,0,1

    # -- constants
    h = 4.135667516*1e-18 #kev*sec
    c = 3*1e8 #m/s
    lambda_ = h*c/energy*1e10 # wavelength of the X-rays

    # -- ring mask
    edges = roi.ring_edges(inner_radius, width, spacing, num_rings)
    ring_mask = roi.rings(edges, center, data.shape)

    # -- apply threshold mask data
    data[data<threshold[0]]=0
    data[data>threshold[1]]=0

    # -- radial average 
    Iphi= radial_average(data,calibrated_center=center,mask=mask*ring_mask,nx=n_bins,min_x=min_bin,max_x=max_bin)

    return Iphi[0]*180./np.pi+180.,Iphi[1]
Exemple #5
0
def test_segmented_rings():
    center = (75, 75)
    img_dim = (150, 140)
    first_q = 5
    delta_q = 5
    num_rings = 4  # number of Q rings
    slicing = 4

    edges = roi.ring_edges(first_q, width=delta_q, spacing=4,
                           num_rings=num_rings)
    print("edges", edges)

    label_array = roi.segmented_rings(edges, slicing, center,
                                      img_dim, offset_angle=0)
    print("label_array for segmented_rings", label_array)

    # Did we draw the right number of ROIs?
    label_list = np.unique(label_array.ravel())
    actual_num_labels = len(label_list) - 1
    num_labels = num_rings * slicing
    assert_equal(actual_num_labels, num_labels)

    # Did we draw the right ROIs? (1-16 with some zeros around too)
    assert_array_equal(label_list, np.arange(num_labels + 1))

    # A brittle test to make sure the exactly number of pixels per label
    # is never accidentally changed:
    # number of pixels per ROI
    num_pixels = np.bincount(label_array.ravel())
    expected_num_pixels = [18372, 59, 59, 59, 59, 129, 129, 129,
                           129, 200, 200, 200, 200, 269, 269, 269, 269]
    assert_array_equal(num_pixels, expected_num_pixels)
Exemple #6
0
def ring_mask(data,center,inner_radius=0,width=1,spacing=0,num_rings=10):
    '''
    Creates a ring mask with cocentric rings of given radius, width and spacing 
    center = (cx, cy)
    '''
    edges = roi.ring_edges(inner_radius, width, spacing, num_rings)
    ring_mask = roi.rings(edges, center, data.shape)

    return ring_mask
def test_construct_circ_avg_image():
    # need to test with center and dims and without
    # and test anisotropic pixels
    image = np.zeros((12, 12))
    calib_center = (2, 2)
    inner_radius = 1

    edges = roi.ring_edges(inner_radius, width=1, spacing=1, num_rings=2)
    labels = roi.rings(edges, calib_center, image.shape)
    image[labels == 1] = 10
    image[labels == 2] = 10

    bin_cen, ring_avg = roi.circular_average(image, calib_center, nx=6)

    # check that the beam center and dims yield the circavg in the right place
    cimg = nimage.construct_circ_avg_image(bin_cen,
                                           ring_avg,
                                           dims=image.shape,
                                           center=calib_center)

    assert_array_almost_equal(
        cimg[2],
        np.array([
            5.0103283, 6.15384615, 6.15384615, 6.15384615, 5.0103283,
            3.79296498, 2.19422113, 0.51063356, 0., 0., 0., 0.
        ]))

    # check that the default values center in the same place
    cimg2 = nimage.construct_circ_avg_image(bin_cen, ring_avg)

    assert_array_almost_equal(
        cimg2[12],
        np.array([
            0., 0., 0., 0., 0., 0., 0., 0.51063356, 2.19422113, 3.79296498,
            5.0103283, 6.15384615, 6.15384615, 6.15384615, 5.0103283,
            3.79296498, 2.19422113, 0.51063356, 0., 0., 0., 0., 0., 0., 0.
        ]))

    # check that anisotropic pixels are treated properly
    cimg3 = nimage.construct_circ_avg_image(bin_cen,
                                            ring_avg,
                                            dims=image.shape,
                                            pixel_size=(2, 1))

    assert_array_almost_equal(
        cimg3[5],
        np.array([
            0., 1.16761618, 2.80022015, 4.16720388, 5.250422, 6.08400137,
            6.08400137, 5.250422, 4.16720388, 2.80022015, 1.16761618, 0.
        ]))

    with assert_raises(ValueError):
        nimage.construct_circ_avg_image(bin_cen,
                                        ring_avg,
                                        center=calib_center,
                                        pixel_size=(2, 1))
Exemple #8
0
    def radialIntegrationBackDetector(self,
                                      n_bins=300,
                                      center=(265, 655),
                                      min_bin=-np.pi,
                                      max_bin=np.pi,
                                      threshold=(0.001, 10000)):
        """
                --------------------------------------------
                Method: SpecklePattern.radialIntegrationBackDetector
                --------------------------------------------
                Wraps radialAverage to perform circular integration and q-calibration on the back
		detector, with an additional threshold masking with parameters
		for Lambda l02 detector at P10, PETRA III
                --------------------------------------------
                Usage: if mySpeckles.radialIntegrationBackDetector()
		--------------------------------------------
		Arguments (optional):
		title - string that contains track title
		        to search for, preferentially unicode
			object with UTF-8 encoding
                --------------------------------------------
                Returns: boolean value if the query was
		         successful (True) or not (False)
                --------------------------------------------
                """

        # -- parameters
        Ldet = 5080.  # detector to sample distance
        dpix = 0.055  # um (pixel size)
        energy = 8.4  #keV
        inner_radius, width, spacing, num_rings = 180, 120, 0, 1

        # -- constants
        h = 4.135667516 * 1e-18  #kev*sec
        c = 3 * 1e8  #m/s
        lambda_ = h * c / energy * 1e10  # wavelength of the X-rays

        # -- ring mask
        edges = roi.ring_edges(inner_radius, width, spacing, num_rings)
        ring_mask = roi.rings(edges, center, data.shape)

        # -- apply threshold mask data
        data[data < threshold[0]] = 0
        data[data > threshold[1]] = 0

        # -- radial average
        Iphi = self.radialAverage(self.data,
                                  calibrated_center=center,
                                  mask=self.mask * ring_mask,
                                  nx=n_bins,
                                  min_x=min_bin,
                                  max_x=max_bin)

        return Iphi[0] * 180. / np.pi + 180., Iphi[1]
Exemple #9
0
def calculate_g2(data,mask=None,g2q=180,center = [265,655]):
    '''
    Calculates the intensity-intensity temporal autocorrelation using
    scikit-beam packages on the back detector
    for a q-range (g2q) and width (width, num_rings,spacing) 
    '''

    # -- parameters
    inner_radius = g2q#180 # radius of the first ring
    width = 1
    spacing = 0
    num_rings = 10
    #center = (273, 723) # center of the speckle pattern
    dpix = 0.055 # The physical size of the pixels
    energy = 8.4 #keV
    h = 4.135667516*1e-18#kev*sec
    c = 3*1e8 #m/s
    lambda_ = h*c/energy*1e10 # wavelength of the X-rays  
    Ldet = 5080. # # detector to sample distance 

    # -- average and mask data
    avg_data = np.average(data,axis=0)#*mask

    # -- ring array
    edges = roi.ring_edges(inner_radius, width, spacing, num_rings)

    # -- convert ring to q
    two_theta = utils.radius_to_twotheta(Ldet, edges*dpix)
    q_val = utils.twotheta_to_q(two_theta, lambda_)
    q_ring = np.mean(q_val, axis=1)
 
    # -- ring mask
    rings = roi.rings(edges, center, data[0].shape)
    ring_mask = rings*mask

    # -- calulate g2
    num_levels = 1#7
    num_bufs = 100#2
    g2, lag_steps = corr.multi_tau_auto_corr(num_levels,num_bufs,ring_mask,mask*data)
    
    # -- average
    g2_avg = np.average(g2,axis=1)
    qt = np.average(q_ring)

    # -- standard error
    g2_err = np.std(g2,axis=1)/np.sqrt(len(g2[0,:]))

    return qt,lag_steps[1:],g2_avg[1:],g2_err[1:]
        def radialIntegrationBackDetector(self, n_bins=300, center=(265,655), min_bin=-np.pi, max_bin=np.pi,threshold=(0.001,10000)):
                """
                --------------------------------------------
                Method: SpecklePattern.radialIntegrationBackDetector
                --------------------------------------------
                Wraps radialAverage to perform circular integration and q-calibration on the back
		detector, with an additional threshold masking with parameters
		for Lambda l02 detector at P10, PETRA III
                --------------------------------------------
                Usage: if mySpeckles.radialIntegrationBackDetector()
		--------------------------------------------
		Arguments (optional):
		title - string that contains track title
		        to search for, preferentially unicode
			object with UTF-8 encoding
                --------------------------------------------
                Returns: boolean value if the query was
		         successful (True) or not (False)
                --------------------------------------------
                """
		
    		# -- parameters
    		Ldet = 5080. # detector to sample distance
    		dpix = 0.055 # um (pixel size)
    		energy = 8.4 #keV
    		inner_radius, width, spacing, num_rings = 180, 120, 0, 1
    		
    		# -- constants
    		h = 4.135667516*1e-18 #kev*sec
    		c = 3*1e8 #m/s
    		lambda_ = h*c/energy*1e10 # wavelength of the X-rays
    		
    		# -- ring mask
    		edges = roi.ring_edges(inner_radius, width, spacing, num_rings)
    		ring_mask = roi.rings(edges, center, data.shape)
    		
    		# -- apply threshold mask data
    		data[data<threshold[0]]=0
    		data[data>threshold[1]]=0
    		
    		# -- radial average
    		Iphi= self.radialAverage(self.data, calibrated_center=center, mask=self.mask*ring_mask, nx=n_bins, min_x=min_bin, max_x=max_bin)
    		
    		return Iphi[0]*180./np.pi+180.,Iphi[1]
Exemple #11
0
def test_construct_circ_avg_image():
    # need to test with center and dims and without
    # and test anisotropic pixels
    image = np.zeros((12, 12))
    calib_center = (2, 2)
    inner_radius = 1

    edges = roi.ring_edges(inner_radius, width=1, spacing=1, num_rings=2)
    labels = roi.rings(edges, calib_center, image.shape)
    image[labels == 1] = 10
    image[labels == 2] = 10

    bin_cen, ring_avg = roi.circular_average(image, calib_center, nx=6)

    # check that the beam center and dims yield the circavg in the right place
    cimg = nimage.construct_circ_avg_image(bin_cen, ring_avg, dims=image.shape,
                                           center=calib_center)

    assert_array_almost_equal(cimg[2], np.array([5.0103283, 6.15384615,
                              6.15384615, 6.15384615, 5.0103283, 3.79296498,
                              2.19422113, 0.51063356, 0., 0., 0., 0.]))

    # check that the default values center in the same place
    cimg2 = nimage.construct_circ_avg_image(bin_cen, ring_avg)

    assert_array_almost_equal(cimg2[12], np.array([0., 0., 0., 0., 0.,
                              0., 0., 0.51063356, 2.19422113, 3.79296498,
                              5.0103283, 6.15384615, 6.15384615, 6.15384615,
                              5.0103283, 3.79296498, 2.19422113, 0.51063356,
                              0., 0., 0., 0., 0., 0., 0.]))

    # check that anisotropic pixels are treated properly
    cimg3 = nimage.construct_circ_avg_image(bin_cen, ring_avg,
                                            dims=image.shape,
                                            pixel_size=(2, 1))

    assert_array_almost_equal(cimg3[5], np.array([0., 1.16761618, 2.80022015,
                              4.16720388, 5.250422, 6.08400137, 6.08400137,
                              5.250422,  4.16720388, 2.80022015,
                              1.16761618,  0.]))

    with assert_raises(ValueError):
        nimage.construct_circ_avg_image(bin_cen, ring_avg, center=calib_center,
                                        pixel_size=(2, 1))
def angular_integration_back_detector(data,
                                      n_bins=100,
                                      mask=None,
                                      center=(265, 655),
                                      min_bin=40,
                                      max_bin=800,
                                      threshold=(0.001, 10000)):
    ''' 
    Does the circular integration and q-calibration on the back
    detector, with an additional threshold masking
    '''

    # -- parameters
    Ldet = 5080.  # detector to sample distance
    dpix = 0.055  # um (pixel size)
    energy = 8.4  #keV

    # -- constants
    h = 4.135667516 * 1e-18  #kev*sec
    c = 3 * 1e8  #m/s
    lambda_ = h * c / energy * 1e10  # wavelength of the X-rays

    # -- calulate q-range
    width, spacing = float(max_bin - min_bin) / float(n_bins), 0
    edges = roi.ring_edges(min_bin, width, spacing, n_bins)
    two_theta = utils.radius_to_twotheta(Ldet, edges * dpix)
    q_val = utils.twotheta_to_q(two_theta, lambda_)
    q = np.mean(q_val, axis=1)

    # -- apply threshold mask data
    data[data < threshold[0]] = 0
    data[data > threshold[1]] = 0

    # -- angular average
    Iq = circular_average(data,
                          calibrated_center=center,
                          mask=mask,
                          nx=n_bins,
                          min_x=min_bin,
                          max_x=max_bin)
    print q.shape, Iq[1].shape
    return Iq[0], Iq[1]
Exemple #13
0
def test_roi_pixel_values():
    images = morphology.diamond(8)
    # width incompatible with num_rings

    label_array = np.zeros((256, 256))

    # different shapes for the images and labels
    assert_raises(ValueError,
                  lambda: roi.roi_pixel_values(images, label_array))
    # create a label mask
    center = (8., 8.)
    inner_radius = 2.
    width = 1
    spacing = 1
    edges = roi.ring_edges(inner_radius, width, spacing, num_rings=5)
    rings = roi.rings(edges, center, images.shape)

    intensity_data, index = roi.roi_pixel_values(images, rings)
    assert_array_equal(intensity_data[0], ([1, 1, 1, 1, 1, 1, 1, 1,
                                            1, 1, 1, 1, 1, 1, 1, 1]))
    assert_array_equal([1, 2, 3, 4, 5], index)
Exemple #14
0
def test_roi_pixel_values():
    images = morphology.diamond(8)
    # width incompatible with num_rings

    label_array = np.zeros((256, 256))

    # different shapes for the images and labels
    assert_raises(ValueError,
                  lambda: roi.roi_pixel_values(images, label_array))
    # create a label mask
    center = (8., 8.)
    inner_radius = 2.
    width = 1
    spacing = 1
    edges = roi.ring_edges(inner_radius, width, spacing, num_rings=5)
    rings = roi.rings(edges, center, images.shape)

    intensity_data, index = roi.roi_pixel_values(images, rings)
    assert_array_equal(intensity_data[0],
                       ([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]))
    assert_array_equal([1, 2, 3, 4, 5], index)
Exemple #15
0
def test_kymograph():
    calib_center = (25, 25)
    inner_radius = 5

    edges = roi.ring_edges(inner_radius, width=2, num_rings=1)
    labels = roi.rings(edges, calib_center, (50, 50))

    images = []
    num_images = 100
    for i in range(num_images):
        int_array = i * np.ones(labels.shape)
        images.append(int_array)

    kymograph_data = roi.kymograph(np.asarray(images), labels, num=1)
    # make sure the the return array has the expected dimensions
    expected_shape = (num_images, np.sum(labels[labels == 1]))
    assert kymograph_data.shape[0] == expected_shape[0]
    assert kymograph_data.shape[1] == expected_shape[1]
    # make sure we got one element from each image
    assert np.all(kymograph_data[:, 0] == np.arange(num_images))
    # given the input data, every row of kymograph_data should be the same
    # number
    for row in kymograph_data:
        assert np.all(row == row[0])
Exemple #16
0
def test_kymograph():
    calib_center = (25, 25)
    inner_radius = 5

    edges = roi.ring_edges(inner_radius, width=2, num_rings=1)
    labels = roi.rings(edges, calib_center, (50, 50))

    images = []
    num_images = 100
    for i in range(num_images):
        int_array = i*np.ones(labels.shape)
        images.append(int_array)

    kymograph_data = roi.kymograph(np.asarray(images), labels, num=1)
    # make sure the the return array has the expected dimensions
    expected_shape = (num_images, np.sum(labels[labels == 1]))
    assert kymograph_data.shape[0] == expected_shape[0]
    assert kymograph_data.shape[1] == expected_shape[1]
    # make sure we got one element from each image
    assert np.all(kymograph_data[:, 0] == np.arange(num_images))
    # given the input data, every row of kymograph_data should be the same
    # number
    for row in kymograph_data:
        assert np.all(row == row[0])
Exemple #17
0
    def calculateG2(self, g2q=180, center=[265, 655]):
        """
		--------------------------------------------
        	Method: SpecklePattern.calculateG2
        	--------------------------------------------
		Calculates the intensity-intensity temporal autocorrelation using
		scikit-beam packages on the back detector
		for a q-range (g2q) and width (width, num_rings,spacing)
        	--------------------------------------------
        	Usage: mySpeckles.calculateG2()
        	--------------------------------------------
                Prerequisites:
		data - data stored as numpy 3D array
                --------------------------------------------
		Arguments: (optional)
		g2q - at which q (pixels) you wanna calculate g2
		center - beam position in the data array (y, x)
		--------------------------------------------
		Returns tuple with:
		qt - q (in Ang-1) at which you calculated g2
		lag_steps[1:] - time array
		g2_avg[1:] - g2 average array
		g2_err[1:] - g2 uncertainty array
		--------------------------------------------
		"""
        # -- parameters
        inner_radius = g2q  #180 # radius of the first ring
        width = 1
        spacing = 0
        num_rings = 10
        #center = (273, 723) # center of the speckle pattern
        dpix = 0.055  # The physical size of the pixels
        energy = 8.4  #keV
        h = 4.135667516 * 1e-18  #kev*sec
        c = 3 * 1e8  #m/s
        lambda_ = h * c / energy * 1e10  # wavelength of the X-rays
        Ldet = 5080.  # # detector to sample distance

        # -- average and mask data
        avg_data = np.average(self.data, axis=0)  #*mask

        # -- ring array
        edges = roi.ring_edges(inner_radius, width, spacing, num_rings)

        # -- convert ring to q
        two_theta = utils.radius_to_twotheta(Ldet, edges * dpix)
        q_val = utils.twotheta_to_q(two_theta, lambda_)
        q_ring = np.mean(q_val, axis=1)

        # -- ring mask
        rings = roi.rings(edges, center, self.data[0].shape)
        ring_mask = rings * mask

        # -- calulate g2
        num_levels = 1  #7
        num_bufs = 100  #2
        g2, lag_steps = corr.multi_tau_auto_corr(num_levels, num_bufs,
                                                 ring_mask,
                                                 self.mask * self.data)

        # -- average
        g2_avg = np.average(g2, axis=1)
        qt = np.average(q_ring)

        # -- standard error
        g2_err = np.std(g2, axis=1) / np.sqrt(len(g2[0, :]))

        return qt, lag_steps[1:], g2_avg[1:], g2_err[1:]
    import skbeam.core.roi as roi
    inner_radius = 3
    width = 1
    spacing = 1
    num_rings = 2
    center = (13, 14)

    num_levels = 5
    num_bufs = 4  # must be even
    xdim = 25
    ydim = 25

    stack_size = 10
    synthetic_data = np.random.randint(1, 10, (stack_size, xdim, ydim))

    edges = roi.ring_edges(inner_radius, width, spacing, num_rings)
    rings = roi.rings(edges, center, (xdim, ydim))

    #(label_array, pixel_list, num_rois, num_pixels, lag_steps, buf,
    # img_per_level, track_level, cur,
    # norm, lev_len) = _validate_and_transform_inputs(num_bufs,
    #                                                 num_levels, rings)
    for i in range(num_rings):
        if rank==i:
            lazy_one_time(synthetic_data, num_levels, num_bufs, rings,
             internal_state=None)




def testCrossCorrelator2d():
    ''' Test the 2D case of the cross correlator.
        With non-binary labels.
    '''
    np.random.seed(123)
    # test 2D data
    Npoints2 = 10
    x2 = np.linspace(-10, 10, Npoints2)
    X, Y = np.meshgrid(x2, x2)
    Z = np.random.random((Npoints2, Npoints2))

    np.random.seed(123)
    sigma = .2
    # purposely have sparsely filled values (with lots of zeros)
    # place peaks in random positions
    peak_positions = (np.random.random((2, 10))-.5)*20
    for peak_position in peak_positions:
        Z += np.exp(-((X - peak_position[0])**2 +
                    (Y - peak_position[1])**2)/2./sigma**2)

    mask_2D = np.ones_like(Z)
    mask_2D[1:2, 1:2] = 0
    mask_2D[7:9, 4:6] = 0
    mask_2D[1:2, 9:] = 0

    # Compute with segmented rings
    edges = ring_edges(1, 3, num_rings=2)
    segments = 5
    x0, y0 = np.array(mask_2D.shape)//2

    maskids = segmented_rings(edges, segments, (y0, x0), mask_2D.shape)

    cc2D_ids = CrossCorrelator(mask_2D.shape, mask=maskids)
    cc2D_ids_symavg = CrossCorrelator(mask_2D.shape, mask=maskids,
                                      normalization='symavg')

    # 10 ids
    assert_equal(cc2D_ids.nids, 10)

    ycorr_ids_2D = cc2D_ids(Z)
    ycorr_ids_2D_symavg = cc2D_ids_symavg(Z)
    index = 0
    ycorr_ids_2D[index][ycorr_ids_2D[index].shape[0]//2]
    assert_array_almost_equal(ycorr_ids_2D[index]
                              [ycorr_ids_2D[index].shape[0]//2],
                              np.array([1.22195059, 1.08685771,
                                        1.43246508, 1.08685771, 1.22195059
                                        ])
                              )

    index = 1
    ycorr_ids_2D[index][ycorr_ids_2D[index].shape[0]//2]
    assert_array_almost_equal(ycorr_ids_2D[index]
                              [ycorr_ids_2D[index].shape[0]//2],
                              np.array([1.24324268, 0.80748997,
                                        1.35790022, 0.80748997, 1.24324268
                                        ])
                              )

    index = 0
    ycorr_ids_2D_symavg[index][ycorr_ids_2D[index].shape[0]//2]
    assert_array_almost_equal(ycorr_ids_2D_symavg[index]
                              [ycorr_ids_2D[index].shape[0]//2],
                              np.array([0.84532695, 1.16405848, 1.43246508,
                                        1.16405848, 0.84532695])
                              )

    index = 1
    ycorr_ids_2D_symavg[index][ycorr_ids_2D[index].shape[0]//2]
    assert_array_almost_equal(ycorr_ids_2D_symavg[index]
                              [ycorr_ids_2D[index].shape[0]//2],
                              np.array([0.94823482, 0.8629459, 1.35790022,
                                        0.8629459, 0.94823482])
                              )
	def calculateG2(self, g2q=180, center=[265,655]):
		"""
		--------------------------------------------
        	Method: SpecklePattern.calculateG2
        	--------------------------------------------
		Calculates the intensity-intensity temporal autocorrelation using
		scikit-beam packages on the back detector
		for a q-range (g2q) and width (width, num_rings,spacing)
        	--------------------------------------------
        	Usage: mySpeckles.calculateG2()
        	--------------------------------------------
                Prerequisites:
		data - data stored as numpy 3D array
                --------------------------------------------
		Arguments: (optional)
		g2q - at which q (pixels) you wanna calculate g2
		center - beam position in the data array (y, x)
		--------------------------------------------
		Returns tuple with:
		qt - q (in Ang-1) at which you calculated g2
		lag_steps[1:] - time array
		g2_avg[1:] - g2 average array
		g2_err[1:] - g2 uncertainty array
		--------------------------------------------
		"""
    		# -- parameters
    		inner_radius = g2q#180 # radius of the first ring
    		width = 1
    		spacing = 0
    		num_rings = 10
    		#center = (273, 723) # center of the speckle pattern
    		dpix = 0.055 # The physical size of the pixels
    		energy = 8.4 #keV
    		h = 4.135667516*1e-18#kev*sec
    		c = 3*1e8 #m/s
    		lambda_ = h*c/energy*1e10 # wavelength of the X-rays
    		Ldet = 5080. # # detector to sample distance
    		
    		# -- average and mask data
    		avg_data = np.average(self.data,axis=0)#*mask
    		
    		# -- ring array
    		edges = roi.ring_edges(inner_radius, width, spacing, num_rings)
    		
    		# -- convert ring to q
    		two_theta = utils.radius_to_twotheta(Ldet, edges*dpix)
    		q_val = utils.twotheta_to_q(two_theta, lambda_)
    		q_ring = np.mean(q_val, axis=1)
    		
    		# -- ring mask
    		rings = roi.rings(edges, center, self.data[0].shape)
    		ring_mask = rings*mask
    		
    		# -- calulate g2
    		num_levels = 1 #7
    		num_bufs = 100 #2
    		g2, lag_steps = corr.multi_tau_auto_corr(num_levels,num_bufs,ring_mask,self.mask*self.data)
    		
    		# -- average
    		g2_avg = np.average(g2,axis=1)
    		qt = np.average(q_ring)
    		
    		# -- standard error
    		g2_err = np.std(g2,axis=1)/np.sqrt(len(g2[0,:]))
    		
    		return qt, lag_steps[1:], g2_avg[1:], g2_err[1:]
Exemple #21
0
def testCrossCorrelator2d():
    ''' Test the 2D case of the cross correlator.
        With non-binary labels.
    '''
    np.random.seed(123)
    # test 2D data
    Npoints2 = 10
    x2 = np.linspace(-10, 10, Npoints2)
    X, Y = np.meshgrid(x2, x2)
    Z = np.random.random((Npoints2, Npoints2))

    np.random.seed(123)
    sigma = .2
    # purposely have sparsely filled values (with lots of zeros)
    # place peaks in random positions
    peak_positions = (np.random.random((2, 10)) - .5) * 20
    for peak_position in peak_positions:
        Z += np.exp(-((X - peak_position[0])**2 + (Y - peak_position[1])**2) /
                    2. / sigma**2)

    mask_2D = np.ones_like(Z)
    mask_2D[1:2, 1:2] = 0
    mask_2D[7:9, 4:6] = 0
    mask_2D[1:2, 9:] = 0

    # Compute with segmented rings
    edges = ring_edges(1, 3, num_rings=2)
    segments = 5
    x0, y0 = np.array(mask_2D.shape) // 2

    maskids = segmented_rings(edges, segments, (y0, x0), mask_2D.shape)

    cc2D_ids = CrossCorrelator(mask_2D.shape, mask=maskids)
    cc2D_ids_symavg = CrossCorrelator(mask_2D.shape,
                                      mask=maskids,
                                      normalization='symavg')

    # 10 ids
    assert_equal(cc2D_ids.nids, 10)

    ycorr_ids_2D = cc2D_ids(Z)
    ycorr_ids_2D_symavg = cc2D_ids_symavg(Z)
    index = 0
    ycorr_ids_2D[index][ycorr_ids_2D[index].shape[0] // 2]
    assert_array_almost_equal(
        ycorr_ids_2D[index][ycorr_ids_2D[index].shape[0] // 2],
        np.array([1.22195059, 1.08685771, 1.43246508, 1.08685771, 1.22195059]))

    index = 1
    ycorr_ids_2D[index][ycorr_ids_2D[index].shape[0] // 2]
    assert_array_almost_equal(
        ycorr_ids_2D[index][ycorr_ids_2D[index].shape[0] // 2],
        np.array([1.24324268, 0.80748997, 1.35790022, 0.80748997, 1.24324268]))

    index = 0
    ycorr_ids_2D_symavg[index][ycorr_ids_2D[index].shape[0] // 2]
    assert_array_almost_equal(
        ycorr_ids_2D_symavg[index][ycorr_ids_2D[index].shape[0] // 2],
        np.array([0.84532695, 1.16405848, 1.43246508, 1.16405848, 0.84532695]))

    index = 1
    ycorr_ids_2D_symavg[index][ycorr_ids_2D[index].shape[0] // 2]
    assert_array_almost_equal(
        ycorr_ids_2D_symavg[index][ycorr_ids_2D[index].shape[0] // 2],
        np.array([0.94823482, 0.8629459, 1.35790022, 0.8629459, 0.94823482]))
Exemple #22
0
# plot the first image to make sure the data loaded correctly
fig, ax = plt.subplots()
ax.imshow(img_stack[0])
ax.set_title("NIPA_GEL_250K")

# define the ROIs
roi_start = 65 # in pixels
roi_width = 9 # in pixels
roi_spacing = (5.0, 4.0)
x_center = 7. # in pixels
y_center = (129.) # in pixels
num_rings = 3

# get the edges of the rings
edges = roi.ring_edges(roi_start, width=roi_width,
                       spacing=roi_spacing, num_rings=num_rings)

# get the label array from the ring shaped 3 region of interests(ROI's)
labeled_roi_array = roi.rings(
    edges, (y_center, x_center), img_stack.shape[1:])

# extarct the ROI's lables and pixel indices corresponding to those labels
roi_indices, pixel_list = roi.extract_label_indices(labeled_roi_array)


# define the ROIs
roi_start = 65 # in pixels
roi_width = 9 # in pixels
roi_spacing = (5.0, 4.0)
x_center = 7. # in pixels
y_center = (129.) # in pixels
Exemple #23
0
def test_rings():
    center = (100., 100.)
    img_dim = (200, 205)
    first_q = 10.
    delta_q = 5.
    num_rings = 7  # number of Q rings
    one_step_q = 5.0
    step_q = [2.5, 3.0, 5.8]

    # test when there is same spacing between rings
    edges = roi.ring_edges(first_q, width=delta_q, spacing=one_step_q,
                           num_rings=num_rings)
    print("edges there is same spacing between rings ", edges)
    label_array = roi.rings(edges, center, img_dim)
    print("label_array there is same spacing between rings", label_array)
    label_mask, pixel_list = roi.extract_label_indices(label_array)
    # number of pixels per ROI
    num_pixels = np.bincount(label_mask, minlength=(np.max(label_mask)+1))
    num_pixels = num_pixels[1:]

    # test when there is same spacing between rings
    edges = roi.ring_edges(first_q, width=delta_q, spacing=2.5,
                           num_rings=num_rings)
    print("edges there is same spacing between rings ", edges)
    label_array = roi.rings(edges, center, img_dim)
    print("label_array there is same spacing between rings", label_array)
    label_mask, pixel_list = roi.extract_label_indices(label_array)
    # number of pixels per ROI
    num_pixels = np.bincount(label_mask, minlength=(np.max(label_mask)+1))
    num_pixels = num_pixels[1:]

    # test when there is different spacing between rings
    edges = roi.ring_edges(first_q, width=delta_q, spacing=step_q,
                           num_rings=4)
    print("edges when there is different spacing between rings", edges)
    label_array = roi.rings(edges, center, img_dim)
    print("label_array there is different spacing between rings", label_array)
    label_mask, pixel_list = roi.extract_label_indices(label_array)
    # number of pixels per ROI
    num_pixels = np.bincount(label_mask, minlength=(np.max(label_mask)+1))
    num_pixels = num_pixels[1:]

    # test when there is no spacing between rings
    edges = roi.ring_edges(first_q, width=delta_q, num_rings=num_rings)
    print("edges", edges)
    label_array = roi.rings(edges, center, img_dim)
    print("label_array", label_array)
    label_mask, pixel_list = roi.extract_label_indices(label_array)
    # number of pixels per ROI
    num_pixels = np.bincount(label_mask, minlength=(np.max(label_mask)+1))
    num_pixels = num_pixels[1:]

    # Did we draw the right number of rings?
    print(np.unique(label_array))
    actual_num_rings = len(np.unique(label_array)) - 1
    assert_equal(actual_num_rings, num_rings)

    # Does each ring have more pixels than the last, being larger?
    ring_areas = np.bincount(label_array.ravel())[1:]
    area_comparison = np.diff(ring_areas)
    print(area_comparison)
    areas_monotonically_increasing = np.all(area_comparison > 0)
    assert_true(areas_monotonically_increasing)

    # Test various illegal inputs
    assert_raises(ValueError,
                  lambda: roi.ring_edges(1, 2))  # need num_rings
    # width incompatible with num_rings
    assert_raises(ValueError,
                  lambda: roi.ring_edges(1, [1, 2, 3], num_rings=2))
    # too few spacings
    assert_raises(ValueError,
                  lambda: roi.ring_edges(1, [1, 2, 3], [1]))
    # too many spacings
    assert_raises(ValueError,
                  lambda: roi.ring_edges(1, [1, 2, 3], [1, 2, 3]))
    # num_rings conflicts with width, spacing
    assert_raises(ValueError,
                  lambda: roi.ring_edges(1, [1, 2, 3], [1, 2], 5))
    w_edges = [[5, 7], [1, 2]]
    assert_raises(ValueError, roi.rings, w_edges, center=(4, 4),
                  shape=(20, 20))
Exemple #24
0
def test_rings():
    center = (100., 100.)
    img_dim = (200, 205)
    first_q = 10.
    delta_q = 5.
    num_rings = 7  # number of Q rings
    one_step_q = 5.0
    step_q = [2.5, 3.0, 5.8]

    # test when there is same spacing between rings
    edges = roi.ring_edges(first_q,
                           width=delta_q,
                           spacing=one_step_q,
                           num_rings=num_rings)
    print("edges there is same spacing between rings ", edges)
    label_array = roi.rings(edges, center, img_dim)
    print("label_array there is same spacing between rings", label_array)
    label_mask, pixel_list = roi.extract_label_indices(label_array)
    # number of pixels per ROI
    num_pixels = np.bincount(label_mask, minlength=(np.max(label_mask) + 1))
    num_pixels = num_pixels[1:]

    # test when there is same spacing between rings
    edges = roi.ring_edges(first_q,
                           width=delta_q,
                           spacing=2.5,
                           num_rings=num_rings)
    print("edges there is same spacing between rings ", edges)
    label_array = roi.rings(edges, center, img_dim)
    print("label_array there is same spacing between rings", label_array)
    label_mask, pixel_list = roi.extract_label_indices(label_array)
    # number of pixels per ROI
    num_pixels = np.bincount(label_mask, minlength=(np.max(label_mask) + 1))
    num_pixels = num_pixels[1:]

    # test when there is different spacing between rings
    edges = roi.ring_edges(first_q, width=delta_q, spacing=step_q, num_rings=4)
    print("edges when there is different spacing between rings", edges)
    label_array = roi.rings(edges, center, img_dim)
    print("label_array there is different spacing between rings", label_array)
    label_mask, pixel_list = roi.extract_label_indices(label_array)
    # number of pixels per ROI
    num_pixels = np.bincount(label_mask, minlength=(np.max(label_mask) + 1))
    num_pixels = num_pixels[1:]

    # test when there is no spacing between rings
    edges = roi.ring_edges(first_q, width=delta_q, num_rings=num_rings)
    print("edges", edges)
    label_array = roi.rings(edges, center, img_dim)
    print("label_array", label_array)
    label_mask, pixel_list = roi.extract_label_indices(label_array)
    # number of pixels per ROI
    num_pixels = np.bincount(label_mask, minlength=(np.max(label_mask) + 1))
    num_pixels = num_pixels[1:]

    # Did we draw the right number of rings?
    print(np.unique(label_array))
    actual_num_rings = len(np.unique(label_array)) - 1
    assert_equal(actual_num_rings, num_rings)

    # Does each ring have more pixels than the last, being larger?
    ring_areas = np.bincount(label_array.ravel())[1:]
    area_comparison = np.diff(ring_areas)
    print(area_comparison)
    areas_monotonically_increasing = np.all(area_comparison > 0)
    assert areas_monotonically_increasing

    # Test various illegal inputs
    assert_raises(ValueError, lambda: roi.ring_edges(1, 2))  # need num_rings
    # width incompatible with num_rings
    assert_raises(ValueError,
                  lambda: roi.ring_edges(1, [1, 2, 3], num_rings=2))
    # too few spacings
    assert_raises(ValueError, lambda: roi.ring_edges(1, [1, 2, 3], [1]))
    # too many spacings
    assert_raises(ValueError, lambda: roi.ring_edges(1, [1, 2, 3], [1, 2, 3]))
    # num_rings conflicts with width, spacing
    assert_raises(ValueError, lambda: roi.ring_edges(1, [1, 2, 3], [1, 2], 5))
    w_edges = [[5, 7], [1, 2]]
    assert_raises(ValueError,
                  roi.rings,
                  w_edges,
                  center=(4, 4),
                  shape=(20, 20))