for kk in range(1, len(source_extraction_v_array)):
    for ll in range(1, len(component_evaluation_v_array)):
        list1.append(number_cell[kk - 1][ll - 1])
        list2.append(1 - fraction[kk - 1][ll - 1])
        list3.append(number_cell5[kk - 1][ll - 1])
        list4.append(1 - fraction5[kk - 1][ll - 1])

product = np.arange(0, len(list1))
false_positive = np.zeros((len(list1)))
false_positive_next = np.zeros((len(list1)))
for ii in range(len(product) - 1):
    product[ii] = list3[ii] * list2[ii]
    false_positive[ii] = list4[ii]
    false_positive_next[ii] = list4[ii + 1]

file_name_number = '/home/sebastian/Documents/Melisa/calcium_imaging_analysis/data/interim/component_evaluation/session_wise/meta/metrics/' + db.create_file_name(
    5, mouse_row.name) + '_number'
np.save(file_name_number, number_cell5)
file_name_fraction = '/home/sebastian/Documents/Melisa/calcium_imaging_analysis/data/interim/component_evaluation/session_wise/meta/metrics/' + db.create_file_name(
    5, mouse_row.name) + '_fraction'
np.save(file_name_fraction, fraction5)

#%% Working with matching!!!!!!

one_version = 13
selected_rows = db.select(states_df,
                          'source_extraction',
                          56165,
                          cropping_v=1,
                          motion_correction_v=1,
                          source_extraction_v=one_version)
def run_source_extraction(row, parameters, dview, session_wise = False):
    '''
    This is the function for source extraction.
    Its goal is to take in a .mmap file,
    perform source extraction on it using cnmf-e and save the cnmf object as a .pkl file.    
    
    This function is only runnable on the cn76 server because it requires parralel processing. 
    
    Args:
        row: pd.DataFrame object
            The row corresponding to the analysis state to be source extracted. 
            
    Returns:
        row: pd.DataFrame object
            The row corresponding to the source extracted analysis state.   
    '''
    step_index = 4
    row_local = row.copy()
    row_local.loc['source_extraction_parameters'] = str(parameters)
    row_local = db.set_version_analysis('source_extraction',row_local,session_wise)
    index = row_local.name

    # Determine input path
    if parameters['session_wise']:
        input_mmap_file_path = eval(row_local.loc['alignment_output'])['main']
    else: 
        input_mmap_file_path = eval(row_local.loc['motion_correction_output'])['main']
    if not os.path.isfile(input_mmap_file_path):
        logging.error('Input file does not exist. Cancelling.')
        return row_local
    
    # Determine output paths
    file_name = db.create_file_name(step_index, index)
    data_dir = 'data/interim/source_extraction/session_wise/' if parameters['session_wise'] else 'data/interim/source_extraction/trial_wise/'
    output_file_path = data_dir + f'main/{file_name}.hdf5'
   
        
    # Create a dictionary with parameters
    output = {
            'main': output_file_path,
            'meta':{
                'analysis' : {
                        'analyst' : os.environ['ANALYST'],
                        'date' : datetime.datetime.today().strftime("%m-%d-%Y"),
                        'time' : datetime.datetime.today().strftime("%H:%M:%S"),
                        },
                    'duration': {}
                    }
                }
    
    # Load memmory mappable input file
    if os.path.isfile(input_mmap_file_path):
        Yr, dims, T = cm.load_memmap(input_mmap_file_path)
#        logging.debug(f'{index} Loaded movie. dims = {dims}, T = {T}.')
        images = Yr.T.reshape((T,) + dims, order='F')
    else:
        logging.warning(f'{index} .mmap file does not exist. Cancelling')
        return row_local
    
    # SOURCE EXTRACTION
    # Check if the summary images are already there
    corr_npy_file_path, pnr_npy_file_path = fm.get_corr_pnr_path(index, gSig_abs = parameters['gSig'][0])
    
    if corr_npy_file_path != None and os.path.isfile(corr_npy_file_path):  
        # Already computed summary images
        logging.info(f'{index} Already computed summary images')
        cn_filter = np.load(corr_npy_file_path)
        pnr = np.load(pnr_npy_file_path)
    else:
        # Compute summary images
        t0 = datetime.datetime.today()
        logging.info(f'{index} Computing summary images')
        cn_filter, pnr = cm.summary_images.correlation_pnr(images[::1], gSig = parameters['gSig'][0], swap_dim=False)
        dt = int((datetime.datetime.today() - t0).seconds/60) # timedelta in minutes
        output['meta']['duration']['summary_images'] = dt 
        logging.info(f'{index} Computed summary images. dt = {dt} min')
        # Saving summary images as npy files
        gSig = parameters['gSig'][0]
        corr_npy_file_path = data_dir + f'/meta/corr/{db.create_file_name(3, index)}_gSig_{gSig}.npy'
        pnr_npy_file_path = data_dir + f'/meta/pnr/{db.create_file_name(3, index)}_gSig_{gSig}.npy'
        with open(corr_npy_file_path, 'wb') as f:
            np.save(f, cn_filter)
        with open(pnr_npy_file_path, 'wb') as f:
            np.save(f, pnr)
    
    # Store the paths in the meta dictionary 
    output['meta']['corr'] = {'main': corr_npy_file_path, 'meta': {}}
    output['meta']['pnr'] = {'main': pnr_npy_file_path, 'meta': {}}
    
    # Calculate min, mean, max value for cn_filter and pnr
    corr_min, corr_mean, corr_max = cn_filter.min(), cn_filter.mean(), cn_filter.max()
    output['meta']['corr']['meta'] = {'min': corr_min, 'mean': corr_mean, 'max': corr_max}
    pnr_min, pnr_mean, pnr_max = pnr.min(), pnr.mean(), pnr.max()
    output['meta']['pnr']['meta'] = {'min': pnr_min, 'mean': pnr_mean, 'max': pnr_max}
    
    # If min_corr and min_pnr are specified via a linear equation, calculate 
    # this value 
    if type(parameters['min_corr']) == list:
        min_corr = parameters['min_corr'][0]*corr_mean + parameters['min_corr'][1]
        parameters['min_corr'] = min_corr
        logging.info(f'{index} Automatically setting min_corr = {min_corr}')
    if type(parameters['min_pnr']) == list:
        min_pnr =  parameters['min_pnr'][0]*pnr_mean + parameters['min_pnr'][1]
        parameters['min_pnr'] = min_pnr
        logging.info(f'{index} Automatically setting min_pnr = {min_pnr}')

    # Set the parameters for caiman
    opts = params.CNMFParams(params_dict = parameters)   
    
    # SOURCE EXTRACTION 
    logging.info(f'{index} Performing source extraction')
    t0 = datetime.datetime.today()
    n_processes = psutil.cpu_count()
    logging.info(f'{index} n_processes: {n_processes}')
    cnm = cnmf.CNMF(n_processes = n_processes, dview = dview, params = opts)
    cnm.fit(images)
    cnm.estimates.dims = dims    
    
    # Store the number of neurons
    output['meta']['K'] = len(cnm.estimates.C)
    
    # Calculate the center of masses
    cnm.estimates.center = caiman.base.rois.com(cnm.estimates.A, images.shape[1], images.shape[2])
    
    # Save the cnmf object as a hdf5 file 
    logging.info(f'{index} Saving cnmf object')
    cnm.save(output_file_path)
    dt = int((datetime.datetime.today() - t0).seconds/60) # timedelta in minutes
    output['meta']['duration']['source_extraction'] = dt
    logging.info(f'{index} Source extraction finished. dt = {dt} min')
    
    # Write necessary variables in row and return
    row_local.loc['source_extraction_parameters'] = str(parameters)
    row_local.loc['source_extraction_output'] = str(output)
        
    return row_local
Ejemplo n.º 3
0
def run_alignmnet(states_df, parameters, dview):
    '''
    This is the main function for the alignment step. It applies methods
    from the CaImAn package used originally in motion correction
    to do alignment.

    Args:
        df: pd.DataFrame
            A dataframe containing the analysis states you want to have aligned.
        parameters: dict
            The alignment parameters.
        dview: object
            The dview object

    Returns:
        df: pd.DataFrame
            A dataframe containing the aligned analysis states.
    '''

    # Sort the dataframe correctly
    df = states_df.copy()
    df = df.sort_values(by=paths.multi_index_structure)

    # Determine the mouse and session of the dataset
    index = df.iloc[0].name
    mouse, session, *r = index
    # alignment_v = index[len(paths.data_structure) + step_index]
    alignment_v = len(df)
    alignment_index = (mouse, session, alignment_v)

    # Determine the output .mmap file name
    file_name = f'mouse_{mouse}_session_{session}_v{alignment_v}'
    output_mmap_file_path = f'data/interim/alignment/main/{file_name}.mmap'

    try:
        df.reset_index()[['trial', 'is_rest']].set_index(['trial', 'is_rest'],
                                                         verify_integrity=True)
    except ValueError:
        logging.error(
            'You passed multiple of the same trial in the dataframe df')
        return df

    output = {
        'meta': {
            'analysis': {
                'analyst': os.environ['ANALYST'],
                'date': datetime.datetime.today().strftime("%m-%d-%Y"),
                'time': datetime.datetime.today().strftime("%H:%M:%S")
            },
            'duration': {}
        }
    }

    # Get necessary parameters
    motion_correction_parameters_list = []
    motion_correction_output_list = []
    input_mmap_file_list = []
    trial_index_list = []
    x_ = []
    _x = []
    y_ = []
    _y = []
    for idx, row in df.iterrows():
        motion_correction_parameters_list.append(
            eval(row.loc['motion_correction_parameters']))
        motion_correction_output = eval(row.loc['motion_correction_output'])
        motion_correction_output_list.append(motion_correction_output)
        input_mmap_file_list.append(motion_correction_output['main'])
        trial_index_list.append(db.get_trial_name(idx[2], idx[3]))
        [x1, x2, y1, y2] = motion_correction_output['meta']['cropping_points']
        x_.append(x1)
        _x.append(x2)
        y_.append(y1)
        _y.append(y2)

    new_x1 = max(x_)
    new_x2 = max(_x)
    new_y1 = max(y_)
    new_y2 = max(_y)
    m_list = []
    for i in range(len(input_mmap_file_list)):
        m = cm.load(input_mmap_file_list[i])
        motion_correction_output = eval(
            df.iloc[i].loc['motion_correction_output'])
        [x1, x2, y1, y2] = motion_correction_output['meta']['cropping_points']
        m = m.crop(new_x1 - x1, new_x2 - x2, new_y1 - y1, new_y2 - y2, 0, 0)
        m_list.append(m)

    # Concatenate them using the concat function
    m_concat = cm.concatenate(m_list, axis=0)
    data_dir = 'data/interim/alignment/main'
    file_name = db.create_file_name(step_index, index)
    fname = m_concat.save(data_dir + '/' + file_name + '_pw_rig' + '.mmap',
                          order='C')

    #meta_pkl_dict['pw_rigid']['cropping_points'] = [x_, _x, y_, _y]
    #output['meta']['cropping_points'] = [x_, _x, y_, _y]
    # Save the movie
    #fname_tot_els  = m_els.save(data_dir + 'main/' + file_name + '_els' + '.mmap',  order='C')
    #logging.info(f'{index} Cropped and saved rigid movie as {fname_tot_els}')

    # MOTION CORRECTING EACH INDIVIDUAL MOVIE WITH RESPECT TO A TEMPLATE MADE OF THE FIRST MOVIE
    logging.info(
        f'{alignment_index} Performing motion correction on all movies with respect to a template made of \
    the first movie.')
    t0 = datetime.datetime.today()

    # Create a template of the first movie
    template_index = trial_index_list.index(
        parameters['make_template_from_trial'])
    m0 = cm.load(input_mmap_file_list[template_index])
    [x1, x2, y1, y2] = motion_correction_output_list[template_index]['meta'][
        'cropping_points']
    m0 = m0.crop(new_x1 - x1, new_x2 - x2, new_y1 - y1, new_y2 - y2, 0, 0)
    m0_filt = cm.movie(
        np.array([
            high_pass_filter_space(m_, parameters['gSig_filt']) for m_ in m0
        ]))
    template0 = cm.motion_correction.bin_median(
        m0_filt.motion_correct(
            5, 5, template=None)[0])  # may be improved in the future

    # Setting the parameters
    opts = params.CNMFParams(params_dict=parameters)

    # Create a motion correction object
    mc = MotionCorrect(fname, dview=dview, **opts.get_group('motion'))

    # Perform non-rigid motion correction
    mc.motion_correct(template=template0, save_movie=True)

    # Cropping borders
    x_ = math.ceil(
        abs(np.array(mc.shifts_rig)[:, 1].max()
            ) if np.array(mc.shifts_rig)[:, 1].max() > 0 else 0)
    _x = math.ceil(
        abs(np.array(mc.shifts_rig)[:, 1].min()
            ) if np.array(mc.shifts_rig)[:, 1].min() < 0 else 0)
    y_ = math.ceil(
        abs(np.array(mc.shifts_rig)[:, 0].max()
            ) if np.array(mc.shifts_rig)[:, 0].max() > 0 else 0)
    _y = math.ceil(
        abs(np.array(mc.shifts_rig)[:, 0].min()
            ) if np.array(mc.shifts_rig)[:, 0].min() < 0 else 0)

    dt = int(
        (datetime.datetime.today() - t0).seconds / 60)  # timedelta in minutes
    output['meta']['duration']['motion_correction'] = dt
    logging.info(
        f'{alignment_index} Performed motion correction. dt = {dt} min.')

    # Create a timeline and store it
    timeline = [[trial_index_list[0], 0]]
    for i in range(1, len(m_list)):
        m = m_list[i]
        timeline.append([trial_index_list[i], timeline[i - 1][1] + m.shape[0]])
    #    timeline_pkl_file_path = f'data/interim/alignment/meta/timeline/{file_name}.pkl'
    #    with open(timeline_pkl_file_path,'wb') as f:
    #        pickle.dump(timeline,f)
    #    output['meta']['timeline'] = timeline_pkl_file_path
    output['meta']['timeline'] = timeline

    # Save the concatenated movie
    output_mmap_file_path_tot = m_concat.save(output_mmap_file_path, order='C')
    output['main'] = output_mmap_file_path_tot

    #    # Delete the motion corrected movies
    #    for fname in mc.fname_tot_rig:
    #        os.remove(fname)

    dt = int(
        (datetime.datetime.today() - t0).seconds / 60)  # timedelta in minutes
    output['meta']['duration']['concatenation'] = dt
    logging.info(f'{alignment_index} Performed concatenation. dt = {dt} min.')

    for idx, row in df.iterrows():
        df.loc[idx, 'alignment_output'] = str(output)
        df.loc[idx, 'alignment_parameters'] = str(parameters)

    return df
def run_component_evaluation(row,
                             parameters,
                             set_version=None,
                             session_wise=False):

    step_index = 5
    row_local = row.copy()
    row_local.loc['component_evaluation_parameters'] = str(parameters)
    row_local = db.set_version_analysis('component_evaluation', row_local,
                                        session_wise)
    index = row_local.name

    motion_correction_output = eval(row_local.loc['motion_correction_output'])
    source_extraction_output = eval(row_local.loc['source_extraction_output'])
    source_extraction_parameters = eval(
        row_local.loc['source_extraction_parameters'])
    input_hdf5_file_path = source_extraction_output['main']
    input_mmap_file_path = motion_correction_output['main']
    basename = 'data/interim/component_evaluation/session_wise/' if source_extraction_parameters[
        'session_wise'] else 'data/interim/component_evaluation/trial_wise/'
    file_name = db.create_file_name(step_index, index)
    output_file_path = basename + f'main/{file_name}.hdf5'

    if set_version == None:
        # If the output version is not specified, determine it automatically.
        version = index[4 + step_index] + 1
    index = list(index)
    index[4 + step_index] = version
    index = tuple(index)

    # Create a dictionary with parameters
    output = {
        'main': output_file_path,
        'meta': {
            'analysis': {
                'analyst': os.environ['ANALYST'],
                'date': datetime.datetime.today().strftime("%m-%d-%Y"),
                'time': datetime.datetime.today().strftime("%H:%M:%S"),
            },
            'duration': {}
        }
    }

    # Load CNMF object
    cnm = load_CNMF(input_hdf5_file_path)

    # Load the original movie
    Yr, dims, T = cm.load_memmap(input_mmap_file_path)
    images = Yr.T.reshape((T, ) + dims, order='F')

    # Set the parmeters
    cnm.params.set('quality', parameters)

    # Stop the cluster if one exists
    n_processes = psutil.cpu_count()
    try:
        cm.cluster.stop_server()
    except:
        pass

    # Start a new cluster
    c, dview, n_processes = cm.cluster.setup_cluster(
        backend='local',
        n_processes=
        n_processes,  # number of process to use, if you go out of memory try to reduce this one
        single_thread=False)
    # Evaluate components
    cnm.estimates.evaluate_components(images, cnm.params, dview=dview)

    logging.debug('Number of total components: ', len(cnm.estimates.C))
    logging.debug('Number of accepted components: ',
                  len(cnm.estimates.idx_components))

    # Stop the cluster
    dview.terminate()

    # Save CNMF object
    cnm.save(output_file_path)

    # Write necessary variables to the trial index and row
    row_local.loc['component_evaluation_parameters'] = str(parameters)
    row_local.loc['component_evaluation_output'] = str(output)

    return row_local
Ejemplo n.º 5
0
def run_equalizer(selected_rows, states_df, parameters, session_wise=False):
    '''

    This function is meant to help with differences in contrast in different trials and session, to equalize general
    brightness or reduce photobleaching. It corrects the video and saves them in the corrected version. It can be run
    with the already aligned videos or trial by trial. for trial by trial, a template is required.

    params selected_rows: pd.DataFrame ->  A dataframe containing the analysis states you want to have equalized
    params states_df: pd.DataFrame -> A dataframe containing all the analysis data base
    params parameters: dict -> contains parameters concerning equalization

    returns : None
    '''

    # Sort the dataframe correctly
    df = selected_rows.sort_values(by=paths.multi_index_structure)
    # Determine the output path
    output_tif_file_path = f'data/interim/equalizer/main/'
    mouse, session, init_trial, *r = df.iloc[0].name

    histogram_name = f'mouse_{mouse}_session_{session}_init_trial_{init_trial}'
    output_steps_file_path = f'data/interim/equalizer/meta/figures/histograms/' + histogram_name

    try:
        df.reset_index()[['trial', 'is_rest']].set_index(['trial', 'is_rest'],
                                                         verify_integrity=True)
    except ValueError:
        logging.error(
            'You passed multiple of the same trial in the dataframe df')
        return df

    #creates an output dictionary for the data base
    output = {
        'main': {},
        'meta': {
            'analysis': {
                'analyst': os.environ['ANALYST'],
                'date': datetime.datetime.today().strftime("%m-%d-%Y"),
                'time': datetime.datetime.today().strftime("%H:%M:%S")
            },
            'duration': {}
        }
    }

    if session_wise:  ## UNDER DEVELOPMENT
        row_local = df.iloc[0]
        input_tif_file_list = eval(row_local['alignment_output'])['main']
        movie_original = cm.load(
            input_tif_file_list)  # load video as 3d array already concatenated
        movie_equalized = np.empty_like(movie_original)
        source = movie_original[0:100, :, :]
        # equalize all the videos loads in m_list_reshape with the histogram of source
        for j in range(int(movie_original.shape[0] / 100)):
            want_to_equalize = movie_original[j * 100:(j + 1) * 100, :, :]
            movie_equalized[j * 100:(j + 1) * 100, :, :] = do_equalization(
                reference=want_to_equalize, source=source)
        # Save the movie
        index = row_local.name
        new_index = db.replace_at_index1(index, 4 + 3, 2)
        row_local.name = new_index

        output['main'] = output_tif_file_path + db.create_file_name(
            0, row_local.name) + '.mmap'
        auxiliar = eval(row_local.loc['alignment_output'])
        auxiliar.update({'equalizing_output': output})
        row_local.loc['decoding_output'] = str(auxiliar)
        movie_equalized.save(output_tif_file_path +
                             db.create_file_name(0, row_local.name) + '.mmap')
        states_df = db.append_to_or_merge_with_states_df(states_df, row_local)

    else:
        # Get necessary parameters and create a list with the paths to the relevant files
        decoding_output_list = []
        input_tif_file_list = []
        trial_index_list = []
        for idx, row in df.iterrows():
            decoding_output = eval(row.loc['decoding_output'])
            decoding_output_list.append(decoding_output)
            input_tif_file_list.append(decoding_output['main'])
            trial_index_list.append(db.get_trial_name(idx[2], idx[3]))

        # this was something for ploting while testing, can be removed
        #colors = []
        #for i in range(len(df)):
        #    colors.append('#%06X' % randint(0, 0xFFFFFF))

        #load the videos as np.array to be able to manipulate them
        m_list = []
        legend = []
        shape_list = []
        h_step = parameters['histogram_step']
        for i in range(len(input_tif_file_list)):
            im = io.imread(input_tif_file_list[i])  #load video as 3d array
            m_list.append(im)  # and adds all the videos to a list
            shape_list.append(
                im.shape
            )  # list of sizes to cut the videos in time for making all of them having the same length
            #legend.append('trial = ' + f'{df.iloc[i].name[2]}')

        min_shape = min(shape_list)
        new_shape = (100 * int(min_shape[0] / 100), min_shape[1], min_shape[2]
                     )  # new videos shape
        m_list_reshape = []
        m_list_equalized = []
        source = m_list[0][0:100, :, :]
        #equalize all the videos loades in m_list_reshape with the histogram of source

        for i in range(len(input_tif_file_list)):
            video = m_list[i]
            m_list_reshape.append(video[:new_shape[0], :, :])
            equalized_video = np.empty_like(video[:new_shape[0], :, :])
            for j in range(int(min_shape[0] / 100)):
                want_to_equalize = m_list_reshape[i][j * 100:(j + 1) *
                                                     100, :, :]
                equalized_video[j * 100:(j + 1) * 100, :, :] = do_equalization(
                    reference=want_to_equalize, source=source)
            m_list_equalized.append(equalized_video)

    #convert the 3d np.array to a caiman movie and save it as a tif file, so it can be read by motion correction script.
    for i in range(len(input_tif_file_list)):
        # Save the movie
        row_local = df.iloc[i]
        movie_original = cm.movie(m_list_reshape[i])
        movie_equalized = cm.movie(m_list_equalized[i])
        # Write necessary variables to the trial index and row_local
        index = row_local.name
        new_index = db.replace_at_index1(index, 4 + 0, 2)
        row_local.name = new_index
        output['main'] = output_tif_file_path + db.create_file_name(
            0, row_local.name) + '.tif'
        auxiliar = eval(row_local.loc['decoding_output'])
        auxiliar.update({'equalizing_output': output})
        row_local.loc['decoding_output'] = str(auxiliar)
        movie_equalized.save(output_tif_file_path +
                             db.create_file_name(0, row_local.name) + '.tif')
        states_df = db.append_to_or_merge_with_states_df(states_df, row_local)

    db.save_analysis_states_database(states_df,
                                     paths.analysis_states_database_path,
                                     paths.backup_path)

    #ALL OF THIS IS FOR PLOTTING AND SHOULD BE MOVED AND CREATE A FUNCTION IN FIGURES FOR PLOTTING THIS THINGS. (LATER)
    #aligned_video_original = np.zeros((new_shape[0]*5,5))
    #aligned_video = np.zeros((new_shape[0]*5,5))
    #for i in range(len(input_tif_file_list)):
    #   aligned_video_original[i*new_shape[0]:(i+1)*new_shape[0],1] = m_list_reshape[i][:,600,500]
    #  aligned_video[i*new_shape[0]:(i+1)*new_shape[0],1] = m_list_equalized[i][:,600,500]

    #figure, axes = plt.subplots(1)
    #axes.plot(np.linspace(0, len(aligned_video_original), len(aligned_video_original)), aligned_video_original[:, 1])
    #axes.plot(np.linspace(0, len(aligned_video_original), len(aligned_video_original)), aligned_video[:, 1])
    #axes.set_xlabel('Frames')
    #axes.set_ylabel('Pixel value (gray scale)')
    #axes.legend(['Original aligned signal', 'Histogram matching aligned signal'])
    #figure.savefig('Example_histogram_matching_3')

    #m_list_equalized = do_equalization(source=m_list_reshape[0][0:100,:,:], reference=m_list_reshape[i][0:100,:,:])

    #hist_template_video, bins_template = np.histogram(m_list_reshape[0][0:100,:,:].flatten(),bins=np.linspace(0,2**10), density= True)
    #hist_source_video, bins_source = np.histogram(m_list_reshape[i][0:100,:,:].flatten(),bins = np.linspace(0,2**10),density=True)
    #hist_equalized_video, bins_equalized = np.histogram(m_list_equalized[i][0:100,:,:].flatten(),bins = np.linspace(0,2**10),density=True)

    #figure, axes = plt.subplots(2,2)
    #axes[0,0].imshow(m_list[0][0,:,:], cmap = 'gray')
    #axes[1,0].imshow(m_list[i][0,:,:], cmap = 'gray')
    #axes[1,1].imshow(m_list_equalized[0,:,:], 'gray')
    #axes[0,1].plot(bins_template[:-1],hist_template_video, color = 'r')
    #axes[0,1].plot(bins_source[:-1],hist_source_video,'--', color = 'b')
    #axes[0,1].plot(bins_equalized[:-1],hist_equalized_video, '*', color = 'g')
    #axes[0,1].legend(['Template','Source','Equalized_Video'])
    #axes[0,1].set_xlabel('Pixel Intensity (gray scale)')
    #axes[0,1].set_ylabel('Density')
    #axes[0, 0].set_title('Template')
    #axes[1, 0].set_title('Source')
    #axes[1, 1].set_title('Equalized')

    return
Ejemplo n.º 6
0
    axes = np.empty((1, 5), dtype='object')
    axes[0, 0] = plt.axes([0.07, cont_height, 0.2, 0.4])
    im_corr_cont = axes[0, 0].imshow(np.clip(cn_filter, min_corr_init,
                                             max_corr_init),
                                     cmap=cmap)
    axes[0, 0].set_title('correlation')
    axes[0, 1] = plt.axes([0.30, cont_height + 0.025, 0.01, 0.35])
    plt.colorbar(im_corr_cont, cax=axes[0, 1])
    axes[0, 2] = plt.axes([0.40, cont_height, 0.2, 0.4])
    im_pnr_cont = axes[0, 2].imshow(np.clip(pnr, min_pnr_init, max_pnr_init),
                                    cmap=cmap)
    axes[0, 2].set_title('pnr')
    axes[0, 3] = plt.axes([0.63, cont_height + 0.025, 0.01, 0.35])
    plt.colorbar(im_pnr_cont, cax=axes[0, 3])

    corr_pnr_plot_path = 'data/interim/source_extraction/trial_wise/meta/figures/corr_pnr/' + db.create_file_name(
        4, index) + '.png'
    fig.savefig(corr_pnr_plot_path)

    cnm_file_path = source_extraction_output['main']
    cnm = load_CNMF(db.get_file(cnm_file_path))
    fig2 = cnm.estimates.plot_contours(img=cn_filter,
                                       idx=cnm.estimates.idx_components)
    cnm_contours_plot_path = 'data/interim/source_extraction/trial_wise/meta/figures/corr_pnr/' + db.create_file_name(
        4, index) + '_contours.png'
    fig2.savefig(corr_pnr_plot_path)

    idx_array = np.arange(cnm.estimates.C.shape[0])
    #plot components (non deconvolved)
    fig3 = get_fig_C_stacked(cnm.estimates.C, idx_components=idx_array)
    cnm_activity_plot_path = 'data/interim/source_extraction/trial_wise/meta/figures/corr_pnr/' + db.create_file_name(
        4, index) + '_activity.png'