Example #1
0
def Partial_Average_From_File(data_folder,
                              start_frame,
                              stop_frame,
                              graph_type='.tif',
                              LP_Para=False,
                              HP_Para=False,
                              filter_method=False):
    '''
    Average specific part of graphs in the folder.

    Parameters
    ----------
    data_folder : (str)
        Data folder.
    start_frame : (int)
        Start ID of frame selection.
    stop_frame : (int)
        Stop ID of frame selection.
    graph_type : (str), optional
        Frame dtype. The default is '.tif'.
    LP_Para\HP_Para\filter_method : optional
        Filter parameters. The default is False.

    Returns
    -------
    Averaged_Graph : (2D Array)
        Averaged graphs.

    '''
    all_tif_name = np.array(
        OS_Tools.Get_File_Name(data_folder, file_type=graph_type))
    used_tif_name = all_tif_name[start_frame:stop_frame]
    Averaged_Graph = Graph_Tools.Average_From_File(used_tif_name, LP_Para,
                                                   HP_Para, filter_method)
    return Averaged_Graph
Example #2
0
    def After_Align_Average(self):
        """
        This Functin will generate after align average graph of Run and Global, and then save them.
        
        Returns
        -------
        None.

        """
        print('Aligning done. ')
        self.After_Align_Graphs = {} # Initialize a dictionary, will record all aligned graphs averages and graph nums.
        # Fill After Align Graph Dictionary first
        total_graph_num = 0
        for i in range(len(self.Aligned_frame_folders)):
            current_run_names = OS_Tools.Get_File_Name(self.Aligned_frame_folders[i])
            temp_average = Graph_Tools.Average_From_File(current_run_names) # This will generate an average graph with 'f8' formation.
            current_graph_aligned = Graph_Tools.Clip_And_Normalize(temp_average,clip_std = 5)
            Graph_Tools.Show_Graph(current_graph_aligned, 'Run_Average_After_Align', self.all_save_folders[i])
            current_run_Frame_Num = len(current_run_names)
            total_graph_num += current_run_Frame_Num
            self.After_Align_Graphs[i] = (current_graph_aligned,current_run_Frame_Num)
        global_average_after_align = np.zeros(np.shape(current_graph_aligned),dtype = 'f8')
        
        # Then calculate global average in each run.
        for i in range(len(self.all_save_folders)):
            global_average_after_align += self.After_Align_Graphs[i][0].astype('f8')*self.After_Align_Graphs[i][1]/total_graph_num
        global_average_after_align = Graph_Tools.Clip_And_Normalize(global_average_after_align,clip_std = 5)
        
        # Then save global graph into each folder.
        for i in range(len(self.all_save_folders)):
            if i == 0:
                Graph_Tools.Show_Graph(global_average_after_align, 'Global_Average_After_Align', self.all_save_folders[i])
            else:
                Graph_Tools.Show_Graph(global_average_after_align, 'Global_Average_After_Align', self.all_save_folders[i],show_time = 0)
Example #3
0
def Least_Tremble_Average_Graph(data_folder,
                                average_prop=0.1,
                                cut_shape=(9, 9)):
    all_tif_name = np.array(OS_Tools.Get_File_Name(data_folder))
    _, frac_disps = Tremble_Evaluator(data_folder, cut_shape=cut_shape)
    frac_num, frame_num, _ = frac_disps.shape
    # Then calculate average center and least error graph.
    frac_centers = np.zeros(shape=(frac_num, 2), dtype='f8')
    for i in range(frac_num):
        frac_centers[i, 0] = frac_disps[i, :, 0].mean()
        frac_centers[i, 1] = frac_disps[i, :, 1].mean()
    # And all frac_total movings
    total_movings = np.zeros(frame_num, dtype='f8')
    for i in range(frame_num):
        c_dist = 0
        for j in range(frac_num):
            c_dist += (frac_centers[j][0] - frac_disps[j, i, 0])**2 + (
                frac_centers[j][1] - frac_disps[j, i, 1])**2
        total_movings[i] = c_dist
    # Then find least props.
    used_num = int(frame_num * average_prop)
    if used_num < 300:  # least num of average is set to 300 to avoid problem.
        used_num = min(300, frame_num)
    print('Average of most stable ' + str(used_num) + ' Frames.')
    if used_num < 300:  # meaning all frame used
        graph_names = all_tif_name
    else:
        used_frame_ind = np.argpartition(total_movings, used_num)[0:used_num]
        graph_names = all_tif_name[used_frame_ind]
    averaged_graph = Graph_Tools.Average_From_File(graph_names)

    return averaged_graph, graph_names
Example #4
0
 def Before_Run_Average(self):
     """
     Generate global and per run average graph.
     This part is automatic,output averaged graph in folder, return nothing.
     
     Returns
     -------
     None.
     """
     print('Averaging before align...')
     #Get Run Average First
     self.Before_Align_Dics = {}# Define a dictionary to save before align graphs.
     total_graph_num = 0 # counter of graph numbers
     for i in range(len(self.Before_Align_Tif_Name)):
         run_graph_num = len(self.Before_Align_Tif_Name[i])# How many graphs in this run
         total_graph_num += run_graph_num
         current_run_average = Graph_Tools.Average_From_File(self.Before_Align_Tif_Name[i])
         current_run_average = Graph_Tools.Clip_And_Normalize(current_run_average,clip_std = 5)
         self.Before_Align_Dics[i] = (current_run_average,run_graph_num) # Write Current dict as a Tuple.
         Graph_Tools.Show_Graph(current_run_average, 'Run_Average',self.all_save_folders[i])# Show and save Run Average.
         
     # Then Use Weighted average method to generate global tif. This methos can be faster than original ones.
     global_average_graph = np.zeros(shape = np.shape(self.Before_Align_Dics[0][0]),dtype = 'f8')# Base on shape of graph
     for i in range(len(self.Before_Align_Tif_Name)):
         global_average_graph += self.Before_Align_Dics[i][0].astype('f8')*self.Before_Align_Dics[i][1]/total_graph_num
     global_average_graph = Graph_Tools.Clip_And_Normalize(global_average_graph,clip_std = 5)
     
     # At last, save global average graph in every run folders.
     for i in range(len(self.all_save_folders)):
         Graph_Tools.Show_Graph(global_average_graph, 'Global_Average', self.all_save_folders[i],show_time = 0)
     self.Align_Base = global_average_graph # Define Base of Alignment, use this to do the job.
Example #5
0
def Intensity_Selector(data_folder,
                       graph_type='.tif',
                       mode='biggest',
                       propotion=0.05,
                       list_write=True):
    '''
    Select frames have biggest or smallest a.i., and generate average graphs.

    Parameters
    ----------
    data_folder : (str)
        Data folder.
    graph_type : (str), optional
        Data type of . The default is '.tif'.
    mode : ('biggest' or 'smallest'), optional
        Type of frame selection. The default is 'biggest'.
    propotion : (float), optional
        Propotion of graph selection. The default is 0.05.
    list_write : (bool), optional
        Whether we write down graph intensity data. The default is True.

    Returns
    -------
    averaged_graph : (2D Array)
        Averaged graph of selected frames.
    selected_graph_name : (ND List)
        List of selected graph names.

    '''
    all_graph_name = np.array(
        OS_Tools.Get_File_Name(data_folder, file_type=graph_type))
    graph_Num = len(all_graph_name)
    bright_data = np.zeros(graph_Num, dtype='f8')
    for i in range(graph_Num):
        current_graph = cv2.imread(all_graph_name[i], -1)
        bright_data[i] = np.mean(current_graph)
        # write bright data if required.
    if list_write == True:
        OS_Tools.Save_Variable(data_folder, 'brightness_info', bright_data)
    # Then select given mode frames.
    used_graph_num = int(graph_Num * propotion)
    if mode == 'biggest':
        used_graph_id = np.argpartition(bright_data,
                                        -used_graph_num)[-used_graph_num:]
    elif mode == 'smallest':
        used_graph_id = np.argpartition(bright_data,
                                        used_graph_num)[0:used_graph_num]
    selected_graph_name = all_graph_name[used_graph_id]
    averaged_graph = Graph_Tools.Average_From_File(selected_graph_name)
    return averaged_graph, selected_graph_name
def Tremble_Calculator_From_File(
        data_folder,
        graph_type='.tif',
        cut_shape=(8, 8),
        boulder=20,
        base_method='former',
        base=[],
):
    '''
    Calculate align tremble from graph. This program is used to evaluate align quality.
    
    Parameters
    ----------
    data_folder : (str)
        Data folder of graphs.
    graph_type : (str),optional
        Extend name of input grahp. The default is '.tif'.
    cut_shape : (turple), optional
        Shape of fracture cut. Proper cut will . The default is (10,5).
    boulder : (int),optional
        Boulder of graph. Cut and not used in following calculation.The default is 20.        
    base_method : ('average'or'former'or'input'), optional
        Method of bais calculation. The default is 'former'. 
        'average' bais use all average; 'former' bais use fomer frame; 'input' bais need to be given.
    base : (2D_NdArray), optional
        If move_method == 'input', base should be given here. The default is [].

    Returns
    -------
    mass_center_maps(Graph)
        A plotted graph, showing movement trace of mass center.
    tremble_plots : (List)
        List of all fracture graph tremble list.
    tremble_information : (Dic)
        Dictionary of tramble informations.
        Data type of tremble_information:
    '''
    all_tif_name = OS_Tools.Get_File_Name(data_folder, file_type=graph_type)
    average_graph = Graph_Tools.Average_From_File(all_tif_name)
    tremble_information = {}
    #1. Get base graph first.
    if base_method == 'input':
        base_graph = base
    elif base_method == 'average':
        base_graph = average_graph
    elif base_method == 'former':
        base_graph = cv2.imread(all_tif_name[0], -1)  # First input graph.
    else:
        raise IOError('Invalid Base Method, check please.\n')
Example #7
0
_,Frame_Stim_Dic = Stim_Frame_Align(stim_folder,frame_thres = frame_thres,jmp_step = jmp_step)
#%% Forth, generate Morpho graph and find cell.
cell_Dic = Cell_Find_And_Plot(save_folder, 'Run_Average_After_Align.tif', 'Morpho_Cell')
cell_mask = (cell_Dic['Cell_Graph'][:,:,0])>0
#%% Fifth, calculate RF reaction.
RF_Data = np.zeros(shape = (5,5,2),dtype = 'f8')# use 5*5 matrix, set 0 are frames, set 1 are cells
loc_ids = np.array([1,26,51,76,101,126,151,176,201,226,251,276])
for i in range(5):# i as vector1
    for j in range(5):# j as vector2
        start_id = i*5+j
        current_keys = loc_ids+start_id
        current_loc_frame_id = []
        for k in range(len(current_keys)):
            current_loc_frame_id.extend(Frame_Stim_Dic[current_keys[k]])
        current_loc_graph_name = aligned_all_tif_name[current_loc_frame_id]
        current_graph = Graph_Tools.Average_From_File(current_loc_graph_name)
        all_cells = current_graph*cell_mask
        RF_Data[i,j,0] = current_graph.mean()
        RF_Data[i,j,1] = all_cells.mean()
# then sub average value.
frame_average = RF_Data[:,:,0].min()
cell_average = RF_Data[:,:,1].min()
prop_RF_Data = np.zeros(shape = (5,5,2),dtype = 'f8')
prop_RF_Data[:,:,0] = RF_Data[:,:,0]/frame_average -1
prop_RF_Data[:,:,1] = RF_Data[:,:,1]/cell_average -1
OS_Tools.Save_Variable(save_folder, 'Origin_RF_Data', RF_Data)
#%% Then do Spline interpolation here.
import pylab as pl
# Show graph first.
x = np.array([1,2,3,4,5])
y = np.array([1,2,3,4,5])
Example #8
0
def Translation_Alignment(all_folders,
                          base_mode='global',
                          input_base=np.array([[0, 0], [0, 0]]),
                          align_range=20,
                          align_boulder=20,
                          before_average=True,
                          average_std=5,
                          big_memory_mode=False,
                          save_aligned_data=False,
                          graph_shape=(512, 512),
                          timer=True):
    '''
    
    This function will align all tif graphs in input folders. Only translation transaction here. Affine transformation need further discussion.
    
    Parameters
    ----------
    all_folders:(list)
        List of all tif folders, elements are strs.
    
    base_mode:('global',int,'input',optional. The default is 'global')
        How to select base frame. 'global': use global average as base. int: use average of specific run as base. 'input':Manually input base graph, need to be a 2D-Ndarray.
        
    input_base:(2D-Ndarray,optional. The default is none.)
        If base_mode = 'input', input_base must be given. This will be the base for alignment.
        
    align_range:(int,optional. The default is 20)
        Max pixel of alignment. 
        
    align_boulder:(int,optional. The default is 20)
        boulder cut for align. For different graph size, this variable shall be change.
        
    before_average:(bool,optional. The default is True)
        Whether before average is done. It can be set False to save time, on this case base graph shall be given.
        
    average_std:(float,optional. The default is 5)
        How much std you want for average graph generation. Different std can effect graph effect.
    
    big_memory_mode:(bool,optional. The default is False)
        If memory is big enough, use this mode is faster.
        
    save_aligned_data:(bool,optional. The default is False)
        Can be true only in big memory mode. This will save all aligned graph in a single 4D-Ndarray file.Save folder is the first folder.
        
    graph_shape:(2-element-turple,optional. The default is (512,512))
        Shape of graphs. All input graph must be in same shape.
        
    timer:(bool,optional. The default is True)
        Show runtime of function and each procedures.
    
        
    Returns
    -------
    bool
        Whether new folder is generated.
    
    '''
    time_tic_start = time.time()
    #%% Step1, generate folders and file cycle.
    all_save_folders = List_Op.List_Annex(all_folders, ['Results'])
    Aligned_frame_folders = List_Op.List_Annex(all_save_folders,
                                               ['Aligned_Frames'])
    for i in range(len(all_save_folders)):
        OS_Tools.mkdir(all_save_folders[i])
        OS_Tools.mkdir(Aligned_frame_folders[i])
    Before_Align_Tif_Name = []
    for i in range(len(all_folders)):
        current_run_tif = OS_Tools.Get_File_Name(all_folders[i])
        Before_Align_Tif_Name.append(current_run_tif)

    #%% Step2, Generate average map before align.
    if before_average == True:
        print('Before run averaging ...')
        Before_Align_Dics = {
        }  # This is the dictionary of all run averages. Keys are run id.
        total_graph_num = 0  # Counter of graph numbers.
        for i in range(len(Before_Align_Tif_Name)):
            current_run_graph_num = len(Before_Align_Tif_Name[i])
            total_graph_num += current_run_graph_num
            current_run_average = Graph_Tools.Average_From_File(
                Before_Align_Tif_Name[i])
            current_run_average = Graph_Tools.Clip_And_Normalize(
                current_run_average, clip_std=average_std)
            Before_Align_Dics[i] = (
                current_run_average, current_run_graph_num
            )  # Attention here, data recorded as turple.
            Graph_Tools.Show_Graph(
                current_run_average, 'Run_Average',
                all_save_folders[i])  # Show and save Run Average.
        # Then Use Weighted average method to generate global tif.
        global_average_graph = np.zeros(shape=np.shape(
            Before_Align_Dics[0][0]),
                                        dtype='f8')  # Base on shape of graph
        for i in range(len(Before_Align_Tif_Name)):
            global_average_graph += Before_Align_Dics[i][0].astype(
                'f8') * Before_Align_Dics[i][1] / total_graph_num
        global_average_graph = Graph_Tools.Clip_And_Normalize(
            global_average_graph, clip_std=average_std)
        # Then save global average in each run folder.
        if len(all_folders) > 1:
            for i in range(len(Before_Align_Tif_Name)):
                Graph_Tools.Show_Graph(global_average_graph,
                                       'Global_Average',
                                       all_save_folders[i],
                                       show_time=0)
        else:
            print('Only One run, no global average.')
    else:
        print('Before average Skipped.')
    time_tic_average0 = time.time()

    #%% Step3, Core Align Function.
    print('Aligning...')
    if base_mode == 'global':
        base = global_average_graph
    elif base_mode == 'input':
        base = input_base
    elif type(base_mode) == int:
        base = Before_Align_Dics[base_mode][0]
    else:
        raise IOError('Invalid base mode.')
    # In big memory mode, save aligned_data in a dictionary file.
    if big_memory_mode == True:
        All_Aligned_Frame = {}
        for i in range(len(Before_Align_Tif_Name)):
            All_Aligned_Frame[i] = np.zeros(
                shape=(graph_shape + (len(Before_Align_Tif_Name[i]), )),
                dtype='u2')  # Generate empty graph matrix.
    for i in range(len(Before_Align_Tif_Name)):  # Cycle all runs
        for j in range(len(
                Before_Align_Tif_Name[i])):  # Cycle all graphs in current run
            current_graph = cv2.imread(Before_Align_Tif_Name[i][j],
                                       -1)  # Read in current graph.
            _, _, current_aligned_graph = Alignment(base,
                                                    current_graph,
                                                    boulder=align_boulder,
                                                    align_range=align_range)
            graph_name = Before_Align_Tif_Name[i][j].split(
                '\\')[-1][:-4]  # Ignore extend name'.tif'.
            Graph_Tools.Show_Graph(current_aligned_graph,
                                   graph_name,
                                   Aligned_frame_folders[i],
                                   show_time=0)
            if big_memory_mode == True:
                All_Aligned_Frame[i][:, :, j] = current_aligned_graph
    print('Align Finished, generating average graphs...')
    time_tic_align_finish = time.time()

    #%% Step4, After Align Average
    After_Align_Graphs = {}
    if big_memory_mode == True:  # Average can be faster.
        temp_global_average_after_align = np.zeros(shape=graph_shape,
                                                   dtype='f8')
        for i in range(len(All_Aligned_Frame)):
            current_run_average = Graph_Tools.Clip_And_Normalize(
                np.mean(All_Aligned_Frame[i], axis=2),
                clip_std=average_std)  # Average run graphs, in type 'u2'
            After_Align_Graphs[i] = (current_run_average,
                                     len(All_Aligned_Frame[i][0, 0, :]))
            temp_global_average_after_align += After_Align_Graphs[i][0].astype(
                'f8') * After_Align_Graphs[i][1] / total_graph_num
        global_average_after_align = Graph_Tools.Clip_And_Normalize(
            temp_global_average_after_align, clip_std=average_std)
    else:  # Traditional ways.
        temp_global_average_after_align = np.zeros(shape=graph_shape,
                                                   dtype='f8')
        for i in range(len(Aligned_frame_folders)):
            current_run_names = OS_Tools.Get_File_Name(
                Aligned_frame_folders[i])
            current_run_average = Graph_Tools.Average_From_File(
                current_run_names)
            current_run_average = Graph_Tools.Clip_And_Normalize(
                current_run_average, clip_std=average_std)
            After_Align_Graphs[i] = (current_run_average,
                                     len(current_run_names))
            temp_global_average_after_align += After_Align_Graphs[i][0].astype(
                'f8') * After_Align_Graphs[i][1] / total_graph_num
        global_average_after_align = Graph_Tools.Clip_And_Normalize(
            temp_global_average_after_align, clip_std=average_std)
    # After average, save aligned graph in each save folder.
    for i in range(len(all_save_folders)):
        current_save_folder = all_save_folders[i]
        Graph_Tools.Show_Graph(After_Align_Graphs[i][0],
                               'Run_Average_After_Align', current_save_folder)
        if i == 0:  # Show global average only once.
            global_show_time = 5000
        else:
            global_show_time = 0
        if len(all_folders) > 1:
            Graph_Tools.Show_Graph(global_average_after_align,
                                   'Global_Average_After_Align',
                                   current_save_folder,
                                   show_time=global_show_time)
    time_tic_average1 = time.time()

    #%% Step5, save and timer
    if save_aligned_data == True:
        OS_Tools.Save_Variable(all_save_folders[0], 'All_Aligned_Frame_Data',
                               All_Aligned_Frame)

    if timer == True:
        whole_time = time_tic_average1 - time_tic_start
        before_average_time = time_tic_average0 - time_tic_start
        align_time = time_tic_align_finish - time_tic_average0
        after_average_time = time_tic_average1 - time_tic_align_finish
        print('Total Time = ' + str(whole_time) + ' s.')
        print('Before Average Time = ' + str(before_average_time) + ' s.')
        print('Align Time = ' + str(align_time) + ' s.')
        print('After Average Time = ' + str(after_average_time) + ' s.')

    return True
Example #9
0
def Tremble_Calculator_From_File(data_folder,
                                 graph_type='.tif',
                                 cut_shape=(10, 5),
                                 boulder=20,
                                 move_method='former',
                                 base=[],
                                 center_method='weight'):
    '''
    Calculate align tremble from graph. This program is used to evaluate align quality.
    
    Parameters
    ----------
    data_folder : (str)
        Data folder of graphs.
    graph_type : (str),optional
        Extend name of input grahp. The default is '.tif'.
    cut_shape : (turple), optional
        Shape of fracture cut. Proper cut will . The default is (10,5).
    boulder : (int),optional
        Boulder of graph. Cut and not used in following calculation.The default is 20.        
    move_method : ('average'or'former'or'input'), optional
        Method of bais calculation. The default is 'former'. 
        'average' bais use all average; 'former' bais use fomer frame; 'input' bais need to be given.
    base : (2D_NdArray), optional
        If move_method == 'input', base should be given here. The default is [].
    center_method : ('weight' or 'binary'), optional
        Method of center find. Whether we use weighted intense.The default is 'weight'.

    Returns
    -------
    mass_center_maps(Graph)
        A plotted graph, showing movement trace of mass center.
    tremble_plots : (List)
        List of all fracture graph tremble list.
    tremble_information : (Dic)
        Dictionary of tramble informations.
        Data type of tremble_information:
            keys:frame ID
            data are lists, every element in list indicate a fracture grpah, ID in cut graph.
            list elements are turples, each turple[0] are move vector, turple[1] as move distance.
            

    '''
    all_tif_name = OS_Tools.Get_File_Name(data_folder, graph_type)
    average_graph = Graph_Tools.Average_From_File(all_tif_name)
    tremble_information = {}
    # get base of align first.
    if move_method == 'average':
        base_graph = average_graph
    elif move_method == 'input':
        base_graph = base
    elif move_method == 'former':
        base_graph = cv2.imread(all_tif_name[0],
                                -1)  # Use first frame as base.

    # cycle all graph to generate tremble plots.
    for i in range(len(all_tif_name)):
        # Process input graph, get cell
        current_graph = cv2.imread(all_tif_name[i], -1)
        processed_cell_graph = None
        #Cut Graph as described
        _, _, _, cutted_current_graph = Graph_Cutter(processed_cell_graph,
                                                     boulder, cut_shape)
        _, _, _, cutted_base = Graph_Cutter(base_graph, boulder, cut_shape)
        # Renew base if former mode.
        if move_method == 'former':
            base_graph = cv2.imread(all_tif_name[i], -1)
        # Then cycle all cutted_fracture, to calculate movement of every fracture graph.
        current_frame_move_list = []
        for j in range(len(cutted_current_graph)):
            temp_graph_part = cutted_current_graph[j]
            temp_base_part = cutted_base[j]
            temp_graph_center, _ = Graph_Tools.Graph_Center_Calculator(
                temp_graph_part, center_mode=center_method)
            temp_base_center, _ = Graph_Tools.Graph_Center_Calculator(
                temp_base_part, center_mode=center_method)
            temp_tremble_vector, temp_tremble_dist = Calculator.Vector_Calculate(
                temp_base_center, temp_graph_center)
            current_frame_move_list.append(
                (temp_tremble_vector, temp_tremble_dist))
        tremble_information[i] = current_frame_move_list

    # Then, plot mass center plots. This will show change of mass center position.
    if move_method == 'input':
        print('No Mass Center plot Generated.')
        mass_center_maps = False
    elif move_method == 'average':  # If average, use current location
        mass_center_maps = []
        for i in range(len(tremble_information[0])):  # Cycle all fracture
            fig = plt.figure()
            ax = plt.subplot()
            for j in range(len(tremble_information)):  # Cycle all frame
                current_point = tremble_information[j][i][0]
                ax.scatter(current_point[1], current_point[0], alpha=1, s=5)
            mass_center_maps.append(fig)
            plt.close()
    elif move_method == 'former':
        mass_center_maps = []
        for i in range(len(tremble_information[0])):  # Cycle all fracture
            fig = plt.figure()
            ax = plt.subplot()
            current_point = (0, 0)
            for j in range(len(tremble_information)):  # Cycle all frame
                current_point = (current_point[0] +
                                 tremble_information[j][i][0][0],
                                 current_point[1] +
                                 tremble_information[j][i][0][1])
                ax.scatter(current_point[1], current_point[0], alpha=1, s=5)
            mass_center_maps.append(fig)
            plt.close()

    # At last, plot tremble dist plots. Each fracture have a plot.
    tremble_plots = {}
    for i in range(len(tremble_information[0])):  # Cycle all fractures
        current_tremble_plot = []
        for j in range(len(tremble_information)):  # Cycle all frame
            current_dist = tremble_information[j][i][1]
            current_tremble_plot.append(current_dist)
        tremble_plots[i] = np.asarray(current_tremble_plot)
    return mass_center_maps, tremble_plots, tremble_information
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 27 13:41:07 2020

@author: ZR
Codes to process L76 Data
"""

import My_Wheels.Graph_Operation_Kit as Graph_Tools
import My_Wheels.OS_Tools_Kit as OS_Tools
#%% Cell1, Average Graph.
graph_folder = r'I:\Test_Data\201023_L76_LM\1-003'
save_path = graph_folder + r'\Results'
OS_Tools.mkdir(save_path)
all_tif_name = OS_Tools.Get_File_Name(graph_folder)
average_graph = Graph_Tools.Average_From_File(all_tif_name)
norm_average_graph = Graph_Tools.Clip_And_Normalize(average_graph, clip_std=3)
Graph_Tools.Show_Graph(norm_average_graph, 'Average_Graph', save_path)
#%% Then Calculate Runs
graph_folder = r'I:\Test_Data\201023_L76_LM\1-013'
import My_Wheels.Translation_Align_Function as Align
Align.Translation_Alignment([graph_folder])
#%% Align Stim and Frame
import My_Wheels.Stim_Frame_Align as Stim_Frame_Align
stim_folder = r'I:\Test_Data\201023_L76_LM\201023_L76_LM_Stimulus\Run13_RGLum4'
Frame_Stim_Sequence, Frame_Stim_Dictionary = Stim_Frame_Align.Stim_Frame_Align(
    stim_folder)
aligned_tif_name = OS_Tools.Get_File_Name(
    r'I:\Test_Data\201023_L76_LM\1-013\Results\Aligned_Frames')
#%% Generate On-Off Map
on_id = []
def Single_Subgraph_Generator(all_tif_name,
                              A_IDs,
                              B_IDs,
                              filter_method='Gaussian',
                              LP_Para=((5, 5), 1.5),
                              HP_Para=False,
                              t_map=True,
                              t_sig=1):
    '''
    Generate single subtraction map of 2P data. A-B graph is generated.

    Parameters
    ----------
    all_tif_name : (list or nparray)
        All graph name. Usually aligned tif name.
    A_IDs : (list)
        List of A ID.
    B_IDs : (list)
        List of B ID.
    filter_method : (str), optional
        Can be set False to skip. Filter used before and after subtraction. The default is 'Gaussian'.
    LP_Para: (turple),optional
        Can be set False to skip. Low pass filter parameter. The default is ((5,5),1.5).
    HP_Para: (turple),optional
        Can be set False to skip. High pass filter parameter. The default is False.
    t_map : (bool), optional
        Whether t map is generated. The default is True.
    t_sig:(0~1),optional.
        Threshold of significant t map. The default is 1.

    Returns
    -------
    sub_graph : (2D array)
        Subtraction dF/F graph. Origin data, clip and normalize shall be done before plot.
    t_graph : (2D array)
        T test graph.0-1 value normalized array. If t_map == False, this will be None.
    F_info_Dics : (Dic)
        Information dictionary. Including origin F & dF/F information of input graph.

    '''
    warnings.filterwarnings('ignore')
    F_info_Dics = {}
    all_tif_name = np.array(all_tif_name)  # Change into nparray to slice.
    A_Set_Graph_names = all_tif_name[A_IDs]
    B_Set_Graph_names = all_tif_name[B_IDs]
    # Calculate sub graph.
    F_info_Dics['Graph_Shape'] = np.shape(cv2.imread(all_tif_name[0], -1))
    F_info_Dics['Origin_Data_Type'] = str((cv2.imread(all_tif_name[0],
                                                      -1)).dtype)
    F_info_Dics['Average_A_Graph'] = Graph_Tools.Average_From_File(
        A_Set_Graph_names, LP_Para, HP_Para, filter_method)
    F_info_Dics['Average_B_Graph'] = Graph_Tools.Average_From_File(
        B_Set_Graph_names, LP_Para, HP_Para, filter_method)
    F_info_Dics['dF_Map'] = (F_info_Dics['Average_A_Graph'].astype('f8') -
                             F_info_Dics['Average_B_Graph'].astype('f8'))
    F_info_Dics['Average_dF_value'] = abs(
        F_info_Dics['dF_Map']).mean()  # Average dF value.
    F_info_Dics['Average_dF/F_value'] = F_info_Dics['Average_dF_value'] / (
        F_info_Dics['Average_B_Graph'].mean())
    F_info_Dics['dF/F_Graph'] = np.nan_to_num(
        F_info_Dics['dF_Map'] / F_info_Dics['Average_B_Graph'].astype('f8'))
    sub_graph = F_info_Dics['dF_Map']

    # Then calculate F value graph.
    if t_map == False:
        F_info_Dics['t_value_map'] = None
        F_info_Dics['p_value_map'] = None
        t_graph = None
    else:
        import random
        sample_size = min(len(A_Set_Graph_names), len(B_Set_Graph_names))
        selected_A_name = np.array(
            random.sample(list(A_Set_Graph_names), sample_size))
        selected_B_name = np.array(
            random.sample(list(B_Set_Graph_names), sample_size))
        A_graph_arrays = np.zeros(shape=(F_info_Dics['Graph_Shape'] +
                                         (sample_size, )),
                                  dtype='f8')
        B_graph_arrays = np.zeros(shape=(F_info_Dics['Graph_Shape'] +
                                         (sample_size, )),
                                  dtype='f8')
        # Then we will fill filtered data into graph.
        # First, we will read in AB graphs together.
        for i in range(sample_size):
            current_a_graph = cv2.imread(selected_A_name[i], -1)
            current_b_graph = cv2.imread(selected_B_name[i], -1)
            if filter_method != False:
                A_graph_arrays[:, :, i] = My_Filter.Filter_2D(
                    current_a_graph, LP_Para, HP_Para, filter_method)
                B_graph_arrays[:, :, i] = My_Filter.Filter_2D(
                    current_b_graph, LP_Para, HP_Para, filter_method)
        # After that, we calculate t and p value pix by pix.
        t_value_graph = np.zeros(shape=F_info_Dics['Graph_Shape'], dtype='f8')
        p_value_graph = np.zeros(shape=F_info_Dics['Graph_Shape'], dtype='f8')
        from scipy.stats import ttest_rel
        for i in range(F_info_Dics['Graph_Shape'][0]):
            for j in range(F_info_Dics['Graph_Shape'][1]):
                t_value_graph[i, j], p_value_graph[i, j] = ttest_rel(
                    A_graph_arrays[i, j, :], B_graph_arrays[i, j, :])
        # avoid nan
        t_graph_origin = np.nan_to_num(t_value_graph)
        p_value_graph = np.nan_to_num(p_value_graph)
        F_info_Dics['t_graph_origin'] = t_graph_origin
        F_info_Dics['p_value_of_t_test'] = p_value_graph
        t_graph = t_graph_origin * (p_value_graph < t_sig)
        F_info_Dics['t_graph'] = t_graph

    return sub_graph, t_graph, F_info_Dics