Example #1
0
def main(args):

    logfile = args['logfile']
    directory = args[
        'directory']  # directory will be a full path to a func/fictrac folder
    width = 120
    printlog = getattr(brainsss.Printlog(logfile=logfile), 'print_to_log')

    fictrac_raw = load_fictrac(directory)

    #fly = os.path.split(os.path.split(directory)[0])[1]
    #expt = os.path.split(directory)[1]
    full_id = ', '.join(directory.split('/')[-3:-1])

    resolution = 10  #desired resolution in ms
    expt_len = 1000 * 30 * 60
    fps = 50  #of fictrac camera
    behaviors = ['dRotLabY', 'dRotLabZ']
    fictrac = {}
    for behavior in behaviors:
        if behavior == 'dRotLabY': short = 'Y'
        elif behavior == 'dRotLabZ': short = 'Z'
        fictrac[short] = smooth_and_interp_fictrac(fictrac_raw, fps,
                                                   resolution, expt_len,
                                                   behavior)
    xnew = np.arange(0, expt_len, resolution)

    make_2d_hist(fictrac, directory, full_id, save=True, fixed_crop=True)
    make_velocity_trace(fictrac, directory, full_id, xnew, save=True)
Example #2
0
def main(args):

    logfile = args['logfile']
    directory = args[
        'directory']  # directory will be a full path to either an anat/imaging folder or a func/imaging folder
    files = args['files']
    width = 120
    printlog = getattr(brainsss.Printlog(logfile=logfile), 'print_to_log')

    #files = ['functional_channel_1', 'functional_channel_2', 'anatomy_channel_1', 'anatomy_channel_2']
    for file in files:
        try:
            ### make mean ###
            brain = np.asarray(nib.load(os.path.join(directory, file +
                                                     '.nii')).get_data(),
                               dtype='uint16')
            meanbrain = np.mean(brain, axis=-1)

            ### Save ###
            save_file = os.path.join(directory, file + '_mean.nii')
            aff = np.eye(4)
            img = nib.Nifti1Image(meanbrain, aff)
            img.to_filename(save_file)

            fly_func_str = ('|').join(directory.split('/')[-3:-1])
            fly_print = directory.split('/')[-3]
            func_print = directory.split('/')[-2]
            #printlog(f"COMPLETE | {fly_func_str} | {file} | {brain.shape} --> {meanbrain.shape}")
            printlog(
                F"meanbrn | COMPLETED | {fly_print} | {func_print} | {file} | {brain.shape} ===> {meanbrain.shape}"
            )
            print(brain.shape[-1])  ### IMPORTANT: for communication to main
        except FileNotFoundError:
            printlog(F"Not found (skipping){file:.>{width-20}}")
Example #3
0
def main(args):

    logfile = args['logfile']
    directory = args['directory']
    width = 120
    printlog = getattr(brainsss.Printlog(logfile=logfile), 'print_to_log')

    #################
    ### Load Data ###
    #################

    files = ['functional_channel_1', 'functional_channel_2']
    data_mean = {}
    for file in files:
        full_file = os.path.join(directory, file + '.nii')
        if os.path.exists(full_file):
            brain = np.asarray(nib.load(full_file).get_data(), dtype='uint16')
            data_mean[file] = np.mean(brain, axis=(0, 1, 2))
        else:
            printlog(F"Not found (skipping){file:.>{width-20}}")

    ##############################
    ### Output Bleaching Curve ###
    ##############################

    plt.rcParams.update({'font.size': 24})
    fig = plt.figure(figsize=(10, 10))
    signal_loss = {}
    for file in data_mean:
        xs = np.arange(len(data_mean[file]))
        color = 'k'
        if file[-1] == '1': color = 'red'
        if file[-1] == '2': color = 'green'
        plt.plot(data_mean[file], color=color, label=file)
        linear_fit = np.polyfit(xs, data_mean[file], 1)
        plt.plot(np.poly1d(linear_fit)(xs),
                 color='k',
                 linewidth=3,
                 linestyle='--')
        signal_loss[file] = linear_fit[0] * len(
            data_mean[file]) / linear_fit[1] * -100
    plt.xlabel('Frame Num')
    plt.ylabel('Avg signal')
    loss_string = ''
    for file in data_mean:
        loss_string = loss_string + file + ' lost' + F'{int(signal_loss[file])}' + '%\n'
    plt.title(loss_string, ha='center', va='bottom')
    # plt.text(0.5,0.9,
    #          loss_string,
    #          horizontalalignment='center',
    #          verticalalignment='center',
    #          transform=plt.gca().transAxes)

    save_file = os.path.join(directory, 'bleaching.png')
    plt.savefig(save_file, dpi=300, bbox_inches='tight')
Example #4
0
def main(args):

    logfile = args['logfile']
    directory = args[
        'directory']  # directory will be a full path to either an anat folder or a func folder
    start = int(args['start'])
    stop = int(args['stop'])
    printlog = getattr(brainsss.Printlog(logfile=logfile), 'print_to_log')

    moco_dir = os.path.join(directory, 'moco')

    try:
        master_path = os.path.join(directory, 'functional_channel_1.nii')
        moving_path = os.path.join(directory, 'functional_channel_2.nii')
        master_path_mean = os.path.join(directory,
                                        'functional_channel_1_mean.nii')

        # For the sake of memory, load only the part of the brain we will need.
        master_brain = load_partial_brain(master_path, start, stop)
        moving_brain = load_partial_brain(moving_path, start, stop)
        mean_brain = ants.from_numpy(
            np.asarray(nib.load(master_path_mean).get_data(), dtype='float32'))
    except:
        printlog('fuctional data not found; trying anatomical')
        master_path = os.path.join(directory, 'anatomy_channel_1.nii')
        moving_path = os.path.join(directory, 'anatomy_channel_2.nii')
        master_path_mean = os.path.join(directory,
                                        'anatomy_channel_1_mean.nii')

        # For the sake of memory, load only the part of the brain we will need.
        master_brain = load_partial_brain(master_path, start, stop)
        moving_brain = load_partial_brain(moving_path, start, stop)
        mean_brain = ants.from_numpy(
            np.asarray(nib.load(master_path_mean).get_data(), dtype='float32'))

    brainsss.motion_correction(master_brain,
                               moving_brain,
                               moco_dir,
                               printlog,
                               mean_brain,
                               suffix='_' + str(start))
Example #5
0
def main(args):

    logfile = args['logfile']
    directory = args['directory']  # full fly func path
    smooth = args['smooth']
    colors = args['colors']
    printlog = getattr(brainsss.Printlog(logfile=logfile), 'print_to_log')

    #['red', 'green']
    printlog('colors are: {}'.format(colors))
    for color in colors:
        brain_file = os.path.join(directory, 'moco',
                                  'stitched_brain_{}.nii'.format(color))
        if os.path.exists(brain_file):
            t0 = time.time()
            to_print = '/'.join(brain_file.split('/')[-4:])
            printlog(f'Z-scoring{to_print:.>{120-9}}')

            brain = np.asarray(nib.load(brain_file).get_data(), dtype='uint16')

            # printlog("brain load duration: ({})".format(time.time()-t0))
            # t0 = time.time()
            printlog('smooth is {}'.format(smooth))
            if smooth:
                printlog('smoothing')
                smoothed = gaussian_filter1d(brain,
                                             sigma=200,
                                             axis=-1,
                                             truncate=1)
                printlog("brain smoothed duration: ({})".format(time.time() -
                                                                t0))
                t0 = time.time()
                brain = brain - smoothed
                printlog("brain subtracted duration: ({})".format(time.time() -
                                                                  t0))
                t0 = time.time()
                zbrain_file = os.path.join(
                    directory, 'brain_zscored_{}_smooth.nii'.format(color))
            else:
                printlog('not smoothing')
                zbrain_file = os.path.join(
                    directory, 'brain_zscored_{}.nii'.format(color))

            # Z-score brain
            brain_mean = np.mean(brain, axis=3)

            # printlog("brain mean duration: ({})".format(time.time()-t0))
            # t0 = time.time()

            brain_std = np.std(brain, axis=3)

            # printlog("brain std duration: ({})".format(time.time()-t0))
            # t0 = time.time()

            brain = (brain - brain_mean[:, :, :, None]) / brain_std[:, :, :,
                                                                    None]

            # printlog("brain zscored duration: ({})".format(time.time()-t0))
            # t0 = time.time()

            # Save brain

            #printlog('Saving {}'.format(zbrain_file))
            aff = np.eye(4)
            img = nib.Nifti1Image(brain, aff)
            img.to_filename(zbrain_file)
Example #6
0
#########################
### Setup preferences ###
#########################

width = 120 # width of print log
flies = ['fly_001'] # set to None, or a list of fly dirs in dataset_path
nodes = 2 # 1 or 2
nice = True # true to lower priority of jobs. ie, other users jobs go first

#####################
### Setup logging ###
#####################

logfile = './logs/' + time.strftime("%Y%m%d-%H%M%S") + '.txt'
printlog = getattr(brainsss.Printlog(logfile=logfile), 'print_to_log')
sys.stderr = brainsss.Logger_stderr_sherlock(logfile)

###################
### Setup paths ###
###################

#CHANGE THESE PATHS
scripts_path = "/home/users/brezovec/projects/brainsss/scripts"
com_path = "/home/users/brezovec/projects/brainsss/scripts/com"

#change this path to your oak directory, something like /oak/stanford/groups/trc/data/Brezovec/data
dataset_path = "/home/users/brezovec/projects/brainsss/demo_data"

###################
### Print Title ###
Example #7
0
def main(args):

    logfile = args['logfile']
    directory = args['directory'] # moco full path
    dirtype = 'func'
    printlog = getattr(brainsss.Printlog(logfile=logfile), 'print_to_log')
    printlog('\nStitcher started for {}'.format(directory))

    ######################
    ### Get file names ###
    ######################

    colors = ['red', 'green']
    files = {}
    for color in colors:
        files[color] = []
        for file in os.listdir(directory):
            if '.nii' in file and color in file:
                files[color].append(os.path.join(directory, file))
        brainsss.sort_nicely(files[color])

    #####################
    ### Stitch brains ###
    #####################

    for color in colors:
        if len(files[color]) > 0:
            brains = []
            for brain_file in files[color]:
                brain = np.asarray(nib.load(brain_file).get_data(), dtype=np.uint16)

                # Handle edgecase of single volume brain
                if len(np.shape(brain)) == 3:
                    brain = brain[:,:,:,np.newaxis]
                #print('shape of partial brain: {}'.format(np.shape(brain)))
                brains.append(brain)

            #print('brains len: {}'.format(len(brains)))
            stitched_brain = np.concatenate(brains, axis=-1)
            printlog('Stitched brain shape: {}'.format(np.shape(stitched_brain)))

            save_file = os.path.join(directory, 'stitched_brain_{}.nii'.format(color))
            printlog(f'Saving {save_file}')
            aff = np.eye(4)
            img = nib.Nifti1Image(stitched_brain, aff)
            img.to_filename(save_file)
            stitched_brain = None

            # delete partial brains
            [os.remove(file) for file in files[color]]

    ##########################
    ### Stitch moco params ###
    ##########################

    motcorr_param_files = []
    for item in os.listdir(directory):
        if '.npy' in item:
            file = os.path.join(directory, item)
            motcorr_param_files.append(file)
    brainsss.sort_nicely(motcorr_param_files)
    
    motcorr_params = []
    for file in motcorr_param_files:
        motcorr_params.append(np.load(file))

    if len(motcorr_params) > 0:
        stitched_params = np.concatenate(motcorr_params, axis=0)
        save_file = os.path.join(directory, 'motcorr_params_stitched')
        np.save(save_file, stitched_params)
        [os.remove(file) for file in motcorr_param_files]
        xml_dir = os.path.join(os.path.split(directory)[0], 'imaging')
        #save_motion_figure(stitched_params, xml_dir, directory, dirtype)
    else:
        printlog('Empty motcorr params - skipping saving moco figure.')