def test_bad_images(): setup() g2, lag_steps = multi_tau_auto_corr(4, num_bufs, rois, img_stack) # introduce bad images bad_img_list = [3, 21, 35, 48] # convert each bad image to np.nan array images = bad_to_nan_gen(img_stack, bad_img_list) # then use new images (including bad images) g2_n, lag_steps_n = multi_tau_auto_corr(4, num_bufs, rois, images) assert_array_almost_equal(g2[:, 0], g2_n[:, 0], decimal=3) assert_array_almost_equal(g2[:, 1], g2_n[:, 1], decimal=3)
def test_lazy_vs_original(): setup() # run the correlation on the full stack full_gen_one = lazy_one_time( img_stack, num_levels, num_bufs, rois) for gen_state_one in full_gen_one: pass g2, lag_steps = multi_tau_auto_corr(num_levels, num_bufs, rois, img_stack) assert np.all(g2 == gen_state_one.g2) assert np.all(lag_steps == gen_state_one.lag_steps) full_gen_two = lazy_two_time(rois, img_stack, stack_size, num_bufs, num_levels) for gen_state_two in full_gen_two: pass final_gen_result_two = two_time_state_to_results(gen_state_two) two_time = two_time_corr(rois, img_stack, stack_size, num_bufs, num_levels) assert np.all(two_time[0] == final_gen_result_two.g2) assert np.all(two_time[1] == final_gen_result_two.lag_steps)
def one_time_correlation(data: np.ndarray, labels: np.ndarray, num_bufs: int = 16, num_levels: int = 8) -> Tuple[da.array, da.array]: g2, tau = corr.multi_tau_auto_corr(num_levels, num_bufs, labels.astype(np.int), np.asarray(data)) g2 = g2.squeeze() return g2, tau
def test_one_time_from_two_time(): np.random.seed(333) num_lev = 1 num_buf = 10 # must be even x_dim = 10 y_dim = 10 stack = 10 imgs = np.random.randint(1, 3, (stack, x_dim, y_dim)) imgs[:, 0, 0] += 5 roi = np.zeros_like(imgs[0]) # make sure that the ROIs can be any integers greater than 1. # They do not have to start at 1 and be continuous roi[0:x_dim // 5, 0:y_dim // 10] = 5 roi[x_dim // 10:x_dim // 5 + 1, y_dim // 10:y_dim // 5] = 3 g2, lag_steps, _state = two_time_corr(roi, imgs, stack, num_buf, num_lev) g2_t, _ = multi_tau_auto_corr(num_lev, num_buf, roi, imgs) one_time, error_one_time = one_time_from_two_time(g2, calc_errors=True) assert_array_almost_equal( one_time, np.array([ [1.02222222, 1.0, 1.0, 1.0, 0.98148148, 1.0, 1.0, 1.0, 1.0, 1.0], [ 1.37103962, 1.3595679, 1.35260377, 1.34863946, 1.36706349, 1.36235828, 1.35813492, 1.37840136, 1.36607143, 1.35714286, ], ]), ) assert_array_almost_equal( one_time[0].mean() / one_time[1].mean(), g2_t.T[0].mean() / g2_t.T[1].mean(), decimal=2, ) assert_array_almost_equal( error_one_time[0][1:], np.array([ np.std(np.diagonal(g2[0], offset=x)) / np.sqrt(x) for x in range(1, g2[0].shape[0]) ]), decimal=2, )
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 one_time_correlation( images: np.ndarray, rois: Iterable[pg.ROI] = None, image_item: pg.ImageItem = None, num_bufs: int = 16, num_levels: int = 8, ) -> Tuple[da.array, da.array, da.array, np.ndarray]: if images.ndim < 3: raise ValueError( f"Cannot compute correlation on data with {images.ndim} dimensions." ) labels = get_label_array(images, rois=rois, image_item=image_item) if labels.max() == 0: msg.notifyMessage( "Please add an ROI over which to calculate one-time correlation.") raise ValueError( "Please add an ROI over which to calculate one-time correlation.") # Trim the image based on labels, and resolve to memory si, se = np.where(np.flipud(labels)) trimmed_images = np.asarray(images[:, si.min():si.max() + 1, se.min():se.max() + 1]) trimmed_labels = np.asarray( np.flipud(labels)[si.min():si.max() + 1, se.min():se.max() + 1]) # trimmed_images[trimmed_images <= 0] = np.NaN # may be necessary to mask values trimmed_images -= np.min(trimmed_images, axis=0) g2, tau = corr.multi_tau_auto_corr(num_levels, num_bufs, trimmed_labels.astype(np.uint8), trimmed_images) g2 = g2[1:].squeeze() # FIXME: is it required to trim the 0th value off the tau and g2 arrays? return g2.T, tau[1:], images, labels
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:]
im = ax.imshow(image, interpolation='none', norm=LogNorm()) im = ax.imshow(tt.reshape(*img_dim), cmap='Paired', interpolation='nearest') roi_names = ['gray', 'orange', 'brown'] tt = np.zeros(img_stack.shape[1:]).ravel() tt[pixel_list] = roi_indices fig, ax = plt.subplots() ax.set_title("NIPA_GEL_250K") overlay_rois(ax, roi_indices, pixel_list, img_stack.shape[1:], img_stack[0]) # g2 one time correlation results for 3 ROI's g2, lag_steps = corr.multi_tau_auto_corr( num_levels, num_bufs, labeled_roi_array, img_stack) # lag_staps are delays for multiple tau analysis lag_time = 0.001 lag_step = lag_steps[:g2.shape[0]] lags = lag_step*lag_time fig, axes = plt.subplots(num_rings, sharex=True, figsize=(5,10)) axes[num_rings-1].set_xlabel("lags") for i, roi_color in zip(range(num_rings), roi_names): axes[i].set_ylabel("g2") axes[i].semilogx(lags, g2[:, i], 'o', markerfacecolor=roi_color, markersize=10) axes[i].set_ylim(bottom=1, top=np.max(g2[1:, i])) plt.show()
def evaluate(self): self.g2.value, self.lag_steps.value = corr.multi_tau_auto_corr(self.num_levels.value, self.num_bufs.value, self.labels.value.astype(np.int), np.asarray(self.data.value))
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:]