def plot_reversal(res, start_days, end_days, figure_path): ax_args_copy = ax_args.copy() ax_args_copy.update({'ylim': [0, .6]}) res = copy.copy(res) list_of_days = list(zip(start_days, end_days)) start_end_day_res = filter.filter_days_per_mouse( res, days_per_mouse=list_of_days) reversal_res, stats_res = get_reversal_sig(start_end_day_res) filter.assign_composite(reversal_res, loop_keys=['day', 'odor_valence']) import seaborn as sns swarm_args = { 'marker': '.', 'size': 8, 'facecolors': 'none', 'alpha': .5, 'palette': ['green', 'red'], 'jitter': .1 } mean_res = reduce.new_filter_reduce(reversal_res, filter_keys=['day', 'odor_valence'], reduce_key='Fraction') plot.plot_results(mean_res, x_key='day_odor_valence', y_key='Fraction', error_key='Fraction_sem', path=figure_path, plot_function=plt.errorbar, plot_args=error_args, ax_args=ax_args_copy, fig_size=(2, 1.5), save=False) plt.plot([1.5, 1.5], plt.ylim(), '--', color='gray', linewidth=2) plot.plot_results( reversal_res, x_key='day_odor_valence', y_key='Fraction', path=figure_path, colors=['Green', 'Red', 'Green', 'Red'], # plot_function=plt.scatter, plot_args=scatter_args, plot_function=sns.stripplot, plot_args=swarm_args, ax_args=ax_args_copy, fig_size=(2, 1.5), reuse=True, save=True, legend=False) print(mean_res['day_odor_valence']) print(mean_res['Fraction']) from scipy.stats import wilcoxon ix_before_p = reversal_res['day_odor_valence'] == 'Lrn_CS+' ix_after_p = reversal_res['day_odor_valence'] == 'Rev_CS+' ix_before_m = reversal_res['day_odor_valence'] == 'Lrn_CS-' ix_after_m = reversal_res['day_odor_valence'] == 'Rev_CS-' stat_csp = wilcoxon(reversal_res['Fraction'][ix_before_p], reversal_res['Fraction'][ix_after_p]) stat_csm = wilcoxon(reversal_res['Fraction'][ix_before_m], reversal_res['Fraction'][ix_after_m]) print('CS+ to CS-: {}'.format(stat_csp)) print('CS- to CS+: {}'.format(stat_csm)) titles = ['', 'CS+', 'CS-', 'None'] conditions = [['none-p', 'p-m', 'p-none', 'p-p'], ['p-m', 'p-none', 'p-p'], ['m-m', 'm-none', 'm-p'], ['none-m', 'none-none', 'none-p']] labels = [['Added', 'Reversed', 'Lost', 'Retained'], ['Reversed', 'Lost', 'Retained'], ['Retained', 'Lost', 'Reversed'], ['to CS-', 'Retained', 'to CS+']] for i, title in enumerate(titles): mean_stats = reduce.new_filter_reduce(stats_res, filter_keys='condition', reduce_key='Fraction') ax_args_copy.update({ 'ylim': [-.1, 1], 'yticks': [0, .5, 1], 'xticks': [0, 1, 2, 3], 'xticklabels': labels[i] }) plot.plot_results(mean_stats, select_dict={'condition': conditions[i]}, x_key='condition', y_key='Fraction', loop_keys='mouse', error_key='Fraction_sem', sort=True, path=figure_path, colors=['Black'] * 10, plot_function=plt.errorbar, plot_args=error_args, ax_args=ax_args_copy, fig_size=(2, 1.5), save=False) plt.title(title) plot.plot_results(stats_res, select_dict={'condition': conditions[i]}, x_key='condition', y_key='Fraction', loop_keys='mouse', sort=True, path=figure_path, colors=['Black'] * 10, plot_function=plt.scatter, plot_args=scatter_args, ax_args=ax_args_copy, fig_size=(2, 1.5), legend=False, save=True, reuse=True) print(mean_stats['Fraction']) print(mean_res['Fraction'])
def plot_overlap_odor(res, start_days, end_days, delete_non_selective=False, figure_path=None, excitatory=True): ax_args_copy = overlap_ax_args.copy() res = copy.copy(res) res = _get_overlap_odor(res, delete_non_selective) list_of_days = list(zip(start_days, end_days)) mice = np.unique(res['mouse']) start_end_day_res = filter.filter_days_per_mouse( res, days_per_mouse=list_of_days) start_end_day_res = reduce.new_filter_reduce( start_end_day_res, filter_keys=['mouse', 'day', 'condition'], reduce_key='Overlap') add_naive_learned(start_end_day_res, start_days, end_days) filter.assign_composite(start_end_day_res, loop_keys=['condition', 'training_day']) odor_list = ['+:+', '-:-', '+:-'] colors = ['Green', 'Red', 'Gray'] name_str = '_E' if excitatory else '_I' ax_args_copy.update({'xlim': [-1, 6]}) for i, odor in enumerate(odor_list): save_arg = False reuse_arg = True if i == 0: reuse_arg = False if i == len(odor_list) - 1: save_arg = True temp = filter.filter(start_end_day_res, {'condition': odor}) name = ','.join([str(x) for x in start_days]) + '_' + ','.join( [str(x) for x in end_days]) name += name_str plot.plot_results(temp, x_key='condition_training_day', y_key='Overlap', loop_keys='mouse', colors=[colors[i]] * len(mice), path=figure_path, plot_args=line_args, ax_args=ax_args_copy, save=save_arg, reuse=reuse_arg, name_str=name, fig_size=(2, 1.5), legend=False) b = filter.filter(temp, {'training_day': 'Learned'}) print(odor) print(np.mean(b['Overlap'])) start_end_day_res = filter.filter_days_per_mouse( res, days_per_mouse=list_of_days) add_naive_learned(start_end_day_res, start_days, end_days, str1='0', str2='1') start_end_day_res.pop('Overlap_sem', None) summary_res = reduce.new_filter_reduce(start_end_day_res, filter_keys='training_day', reduce_key='Overlap') ax_args_copy.update({ 'xlim': [-1, 2], 'ylim': [0, .5], 'yticks': [0, .1, .2, .3, .4, .5] }) plot.plot_results(summary_res, x_key='training_day', y_key='Overlap', path=figure_path, plot_args=bar_args, ax_args=ax_args_copy, plot_function=plt.bar, fig_size=(2, 1.5), legend=False, reuse=False, save=False) plot.plot_results(summary_res, x_key='training_day', y_key='Overlap', error_key='Overlap_sem', path=figure_path, plot_function=plt.errorbar, plot_args=error_args, ax_args=ax_args, save=True, reuse=True, name_str=name_str) before_odor = filter.filter(start_end_day_res, filter_dict={ 'training_day': '0', 'condition': '+:+' }) after_odor = filter.filter(start_end_day_res, filter_dict={ 'training_day': '1', 'condition': '+:+' }) before_csp = filter.filter(start_end_day_res, filter_dict={ 'training_day': '0', 'condition': '+:-' }) after_csp = filter.filter(start_end_day_res, filter_dict={ 'training_day': '1', 'condition': '+:-' }) before_csm = filter.filter(start_end_day_res, filter_dict={ 'training_day': '0', 'condition': '-:-' }) after_csm = filter.filter(start_end_day_res, filter_dict={ 'training_day': '1', 'condition': '-:-' }) from scipy.stats import ranksums, wilcoxon, kruskal print('Before ++: {}'.format(np.mean(before_odor['Overlap']))) print('After ++: {}'.format(np.mean(after_odor['Overlap']))) print('Wilcoxin:{}'.format( wilcoxon(before_odor['Overlap'], after_odor['Overlap']))) print('Before +-: {}'.format(np.mean(before_csp['Overlap']))) print('After +-: {}'.format(np.mean(after_csp['Overlap']))) print('Wilcoxin:{}'.format( wilcoxon(before_csp['Overlap'], after_csp['Overlap']))) print('Before --: {}'.format(np.mean(before_csm['Overlap']))) print('After --: {}'.format(np.mean(after_csm['Overlap']))) print('Wilcoxin:{}'.format( wilcoxon(before_csm['Overlap'], after_csm['Overlap'])))
def plot_summary_odor(res, start_days, end_days, use_colors=True, figure_path=None, reuse=False, excitatory=True): ax_args_copy = ax_args.copy() res = copy.copy(res) get_responsive_cells(res) list_of_days = list(zip(start_days, end_days)) mice = np.unique(res['mouse']) start_end_day_res = filter.filter_days_per_mouse( res, days_per_mouse=list_of_days) add_naive_learned(start_end_day_res, start_days, end_days, 'a', 'b') filter.assign_composite(start_end_day_res, loop_keys=['odor_valence', 'training_day']) start_end_day_res = reduce.new_filter_reduce( start_end_day_res, filter_keys=['training_day', 'mouse', 'odor_valence'], reduce_key='Fraction Responsive') odor_list = ['CS+', 'CS-'] if use_colors: colors = ['Green', 'Red'] else: colors = ['Black'] * 2 ax_args_copy = ax_args_copy.copy() ax_args_copy.update({ 'xlim': [-1, 8], 'ylim': [0, .4], 'yticks': [0, .1, .2, .3, .4] }) name_str = '_E' if excitatory else '_I' for i, odor in enumerate(odor_list): save_arg = False reuse_arg = True if i == 0 and not reuse: reuse_arg = False if i == len(odor_list) - 1: save_arg = True plot.plot_results(start_end_day_res, select_dict={'odor_valence': odor}, x_key='odor_valence_training_day', y_key='Fraction Responsive', loop_keys='mouse', colors=[colors[i]] * len(mice), path=figure_path, plot_args=line_args, ax_args=ax_args_copy, save=save_arg, reuse=reuse_arg, fig_size=(2.5, 1.5), legend=False, name_str=','.join([str(x) for x in start_days]) + name_str) start_end_day_res = filter.filter_days_per_mouse( res, days_per_mouse=list_of_days) add_naive_learned(start_end_day_res, start_days, end_days, 'a', 'b') filter.assign_composite(start_end_day_res, loop_keys=['odor_valence', 'training_day']) start_end_day_res = reduce.new_filter_reduce( start_end_day_res, filter_keys=['training_day', 'mouse', 'odor_standard'], reduce_key='Fraction Responsive') before_csp = filter.filter(start_end_day_res, filter_dict={ 'training_day': 'a', 'odor_valence': 'CS+' }) after_csp = filter.filter(start_end_day_res, filter_dict={ 'training_day': 'b', 'odor_valence': 'CS+' }) before_csm = filter.filter(start_end_day_res, filter_dict={ 'training_day': 'a', 'odor_valence': 'CS-' }) after_csm = filter.filter(start_end_day_res, filter_dict={ 'training_day': 'b', 'odor_valence': 'CS-' }) try: from scipy.stats import ranksums, wilcoxon, kruskal print('Before CS+: {}'.format( np.mean(before_csp['Fraction Responsive']))) print('After CS+: {}'.format(np.mean( after_csp['Fraction Responsive']))) print('Wilcoxin:{}'.format( wilcoxon(before_csp['Fraction Responsive'], after_csp['Fraction Responsive']))) print('Before CS-: {}'.format( np.mean(before_csm['Fraction Responsive']))) print('After CS-: {}'.format(np.mean( after_csm['Fraction Responsive']))) print('Wilcoxin:{}'.format( wilcoxon(before_csm['Fraction Responsive'], after_csm['Fraction Responsive']))) except: print('stats didnt work')
def plot_summary_odor_pretraining(res, start_days, end_days, arg_naive, figure_path, save, excitatory=True): ax_args_copy = ax_args.copy() res = copy.copy(res) list_of_days = list(zip(start_days, end_days)) mice = np.unique(res['mouse']) start_end_day_res = filter.filter_days_per_mouse( res, days_per_mouse=list_of_days) get_responsive_cells(start_end_day_res) if arg_naive: day_start = filter.filter(start_end_day_res, {'odor_standard': 'PT Naive'}) day_start['odor_standard'] = np.array(['PT CS+'] * len(day_start['odor_standard'])) day_end = filter.filter_days_per_mouse(start_end_day_res, days_per_mouse=end_days) day_end = filter.filter(day_end, {'odor_standard': 'PT CS+'}) reduce.chain_defaultdicts(day_start, day_end) start_end_day_res = day_start else: start_end_day_res = filter.exclude(start_end_day_res, {'odor_standard': 'PT Naive'}) add_naive_learned(start_end_day_res, start_days, end_days, 'a', 'b') filter.assign_composite(start_end_day_res, loop_keys=['odor_standard', 'training_day']) odor_list = ['PT CS+'] colors = ['Orange'] ax_args_copy = ax_args_copy.copy() ax_args_copy.update({ 'xlim': [-1, 10], 'ylim': [0, .4], 'yticks': [0, .1, .2, .3, .4] }) for i, odor in enumerate(odor_list): save_arg = False reuse_arg = True if i == 0: reuse_arg = False if save and i == len(odor_list) - 1: save_arg = True plot.plot_results(start_end_day_res, select_dict={'odor_standard': odor}, x_key='odor_standard_training_day', y_key='Fraction Responsive', loop_keys='mouse', colors=[colors[i]] * len(mice), path=figure_path, plot_args=line_args, ax_args=ax_args_copy, save=save_arg, reuse=reuse_arg, fig_size=(2.5, 1.5), legend=False, name_str='_E' if excitatory else '_I') before_csm = filter.filter(start_end_day_res, filter_dict={ 'training_day': 'a', 'odor_standard': 'PT CS+' }) after_csm = filter.filter(start_end_day_res, filter_dict={ 'training_day': 'b', 'odor_standard': 'PT CS+' }) from scipy.stats import ranksums, wilcoxon, kruskal print('Before PT CS+: {}'.format(np.mean( before_csm['Fraction Responsive']))) print('After PT CS+: {}'.format(np.mean(after_csm['Fraction Responsive']))) from scipy.stats import sem print('After PT CS+ STD: {}'.format(sem(after_csm['Fraction Responsive']))) print('Wilcoxin:{}'.format( wilcoxon(before_csm['Fraction Responsive'], after_csm['Fraction Responsive'])))
def plot_summary_odor_and_water(res, odor_start_days, water_start_days, end_days, use_colors=True, excitatory=True, arg='odor_valence', figure_path=None): include_water = True ax_args_copy = ax_args.copy() res = copy.copy(res) get_responsive_cells(res) mice = np.unique(res['mouse']) list_of_days = list(zip(odor_start_days, end_days)) start_end_day_res = filter.filter_days_per_mouse( res, days_per_mouse=list_of_days) start_end_day_res = filter.exclude(start_end_day_res, {'odor_valence': 'US'}) add_naive_learned(start_end_day_res, odor_start_days, end_days, 'a', 'b') if include_water: list_of_days = list(zip(water_start_days, end_days)) start_end_day_res_water = filter.filter_days_per_mouse( res, days_per_mouse=list_of_days) start_end_day_res_water = filter.filter(start_end_day_res_water, {'odor_valence': 'US'}) add_naive_learned(start_end_day_res_water, water_start_days, end_days, 'a', 'b') reduce.chain_defaultdicts(start_end_day_res, start_end_day_res_water) ax_args_copy = ax_args_copy.copy() if arg == 'odor_valence': start_end_day_res = reduce.new_filter_reduce( start_end_day_res, filter_keys=['training_day', 'mouse', 'odor_valence'], reduce_key='Fraction Responsive') odor_list = ['CS+', 'CS-'] ax_args_copy.update({ 'xlim': [-1, 6], 'ylim': [0, .6], 'yticks': [0, .1, .2, .3, .4, .5] }) colors = ['Green', 'Red'] elif arg == 'naive': arg = 'odor_valence' start_end_day_res = reduce.new_filter_reduce( start_end_day_res, filter_keys=['training_day', 'mouse', 'odor_valence'], reduce_key='Fraction Responsive') odor_list = ['CS+'] ax_args_copy.update({ 'xlim': [-1, 4], 'ylim': [0, .6], 'yticks': [0, .1, .2, .3, .4, .5] }) colors = ['GoldenRod'] else: odor_list = ['CS+1', 'CS+2', 'CS-1', 'CS-2'] colors = ['Green', 'Green', 'Red', 'Red'] ax_args_copy.update({ 'xlim': [-1, 10], 'ylim': [0, .6], 'yticks': [0, .1, .2, .3, .4, .5] }) filter.assign_composite(start_end_day_res, loop_keys=[arg, 'training_day']) if not use_colors: colors = ['Black'] * 4 name_str = '_E' if excitatory else '_I' for i, odor in enumerate(odor_list): reuse_arg = True if i == 0: reuse_arg = False plot.plot_results(start_end_day_res, select_dict={arg: odor}, x_key=arg + '_training_day', y_key='Fraction Responsive', loop_keys='mouse', colors=[colors[i]] * len(mice), path=figure_path, plot_args=line_args, ax_args=ax_args_copy, save=False, reuse=reuse_arg, fig_size=(2.5, 1.5), legend=False, name_str=','.join([str(x) for x in odor_start_days])) plot.plot_results(start_end_day_res, select_dict={'odor_standard': 'US'}, x_key='training_day', y_key='Fraction Responsive', loop_keys='mouse', colors=['Turquoise'] * len(mice), path=figure_path, plot_args=line_args, ax_args=ax_args_copy, fig_size=(1.6, 1.5), legend=False, reuse=True, save=True, name_str=name_str) before_odor = filter.filter(start_end_day_res, filter_dict={ 'training_day': 'a', 'odor_valence': ['CS+', 'CS-'] }) after_odor = filter.filter(start_end_day_res, filter_dict={ 'training_day': 'b', 'odor_valence': ['CS+', 'CS-'] }) before_csp = filter.filter(start_end_day_res, filter_dict={ 'training_day': 'a', 'odor_valence': 'CS+' }) after_csp = filter.filter(start_end_day_res, filter_dict={ 'training_day': 'b', 'odor_valence': 'CS+' }) before_csm = filter.filter(start_end_day_res, filter_dict={ 'training_day': 'a', 'odor_valence': 'CS-' }) after_csm = filter.filter(start_end_day_res, filter_dict={ 'training_day': 'b', 'odor_valence': 'CS-' }) before_water = filter.filter(start_end_day_res, filter_dict={ 'training_day': 'a', 'odor_valence': 'US' }) after_water = filter.filter(start_end_day_res, filter_dict={ 'training_day': 'b', 'odor_valence': 'US' }) try: from scipy.stats import ranksums, wilcoxon, kruskal print('Before Odor: {}'.format( np.mean(before_odor['Fraction Responsive']))) print('After Odor: {}'.format( np.mean(after_odor['Fraction Responsive']))) print('Wilcoxin:{}'.format( wilcoxon(before_odor['Fraction Responsive'], after_odor['Fraction Responsive']))) print('Before CS+: {}'.format( np.mean(before_csp['Fraction Responsive']))) print('After CS+: {}'.format(np.mean( after_csp['Fraction Responsive']))) print('Wilcoxin:{}'.format( wilcoxon(before_csp['Fraction Responsive'], after_csp['Fraction Responsive']))) print('Before CS-: {}'.format( np.mean(before_csm['Fraction Responsive']))) print('After CS-: {}'.format(np.mean( after_csm['Fraction Responsive']))) print('Wilcoxin:{}'.format( wilcoxon(before_csm['Fraction Responsive'], after_csm['Fraction Responsive']))) print('Before US: {}'.format( np.mean(before_water['Fraction Responsive']))) print('After US: {}'.format(np.mean( after_water['Fraction Responsive']))) print('Wilcoxin:{}'.format( wilcoxon(before_water['Fraction Responsive'], after_water['Fraction Responsive']))) except: print('stats didnt work')
def plot_responsive_difference_odor_and_water(res, odor_start_days, water_start_days, end_days, use_colors=True, figure_path=None, include_water=True, normalize=False, pt_start=None, pt_learned=None, average=True, ylim=.22, reuse_arg=False, save_arg=True): key = 'Change in Fraction Responsive' if normalize: key = 'Norm. Fraction Responsive' def _helper(start_end_day_res): combs, list_of_ixs = filter.retrieve_unique_entries( start_end_day_res, ['mouse', 'odor_standard']) for i, comb in enumerate(combs): ixs = list_of_ixs[i] assert len(ixs) == 2 if start_end_day_res['training_day'][0] == 'Naive': ref = ixs[0] test = ixs[1] elif start_end_day_res['training_day'][0] == 'Learned': ref = ixs[1] test = ixs[0] else: raise ValueError('cannot find ref day') if normalize: start_end_day_res[key][test] = start_end_day_res['Fraction Responsive'][test] / \ start_end_day_res['Fraction Responsive'][ref] start_end_day_res[key][ref] = 1 else: start_end_day_res[key][test] = start_end_day_res['Fraction Responsive'][test] - \ start_end_day_res['Fraction Responsive'][ref] start_end_day_res[key][ref] = 0 ax_args_copy = ax_args.copy() res = copy.copy(res) get_responsive_cells(res) list_of_days = list(zip(odor_start_days, end_days)) mice = np.unique(res['mouse']) res[key] = np.zeros_like(res['Fraction Responsive']) start_end_day_res = filter.filter_days_per_mouse( res, days_per_mouse=list_of_days) start_end_day_res = filter.filter( start_end_day_res, {'odor_valence': ['CS+', 'CS-', 'Naive']}) add_naive_learned(start_end_day_res, odor_start_days, end_days) odors = ['CS+', 'CS-', 'Naive'] if 'PT CS+' in np.unique(res['odor_valence']): odors = ['PT CS+'] + odors list_of_days = list(zip(pt_start, pt_learned)) start_end_day_res_pt = filter.filter_days_per_mouse( res, days_per_mouse=list_of_days) start_end_day_res_pt = filter.filter(start_end_day_res_pt, {'odor_valence': 'PT CS+'}) add_naive_learned(start_end_day_res_pt, pt_start, pt_learned) reduce.chain_defaultdicts(start_end_day_res, start_end_day_res_pt) if include_water: odors += ['US'] list_of_days = list(zip(water_start_days, end_days)) start_end_day_res_water = filter.filter_days_per_mouse( res, days_per_mouse=list_of_days) start_end_day_res_water = filter.filter(start_end_day_res_water, {'odor_valence': 'US'}) add_naive_learned(start_end_day_res_water, water_start_days, end_days) reduce.chain_defaultdicts(start_end_day_res, start_end_day_res_water) filter.assign_composite(start_end_day_res, loop_keys=['odor_standard', 'training_day']) if average: start_end_day_res = reduce.new_filter_reduce( start_end_day_res, filter_keys=['odor_valence', 'mouse', 'training_day'], reduce_key=key) start_end_day_res.pop(key + '_sem') _helper(start_end_day_res) start_end_day_res = filter.filter(start_end_day_res, {'training_day': 'Learned'}) summary_res = reduce.new_filter_reduce(start_end_day_res, filter_keys='odor_valence', reduce_key=key) dict = { 'CS+': 'Green', 'CS-': 'Red', 'US': 'Turquoise', 'PT CS+': 'Orange', 'Naive': 'Gray' } if use_colors: colors = [ dict[key] for key in np.unique(start_end_day_res['odor_valence']) ] else: colors = ['Black'] * 6 ax_args_copy = ax_args_copy.copy() n_valence = len(np.unique(summary_res['odor_valence'])) ax_args_copy.update({ 'xlim': [-.5, 3.5], 'ylim': [-ylim, ylim], 'yticks': [-.3, -.2, -.1, 0, .1, .2, .3] }) if normalize: ax_args_copy.update({ 'xlim': [-.5, 3.5], 'ylim': [-.1, 1.5], 'yticks': [0, .5, 1, 1.5] }) error_args_ = { 'fmt': '.', 'capsize': 2, 'elinewidth': 1, 'markersize': 2, 'alpha': .75 } scatter_args_copy = scatter_args.copy() scatter_args_copy.update({'s': 3}) for i, odor in enumerate(odors): reuse = True if i == 0: reuse = reuse_arg plot.plot_results(start_end_day_res, loop_keys='odor_valence', select_dict={'odor_valence': odor}, x_key='odor_valence', y_key=key, colors=[dict[odor]] * len(mice), path=figure_path, plot_args=scatter_args_copy, plot_function=plt.scatter, ax_args=ax_args_copy, save=False, reuse=reuse, fig_size=(2, 1.5), rect=(.25, .2, .6, .6), legend=False, name_str=','.join([str(x) for x in odor_start_days])) if not normalize: plt.plot(plt.xlim(), [0, 0], '--', color='gray', linewidth=1, alpha=.5) plot.plot_results(summary_res, x_key='odor_valence', y_key=key, error_key=key + '_sem', colors='black', path=figure_path, plot_args=error_args_, plot_function=plt.errorbar, ax_args=ax_args_copy, save=save_arg, reuse=True, fig_size=(2, 1.5), legend=False)
res2 = scalpel(res2, keys, mouse, sessions) print(np.unique(res2['session'][-1])) reduce.chain_defaultdicts(res, res1) reduce.chain_defaultdicts(res, res2) print(np.unique(res['mouse'])) if collapse_arg: res1 = filter.filter(res, filter_dict={'experiment': collapse_arg, 'condition':'H'}) res2 = filter.filter(res, filter_dict={'condition': 'Y'}) res = reduce.chain_defaultdicts(res1, res2, copy_dict=True) analysis.analyze(res) analysis.shift_discrimination_index(res) filter.assign_composite(res, ['phase', 'odor_valence']) res = filter.filter(res, {'phase_odor_valence': ['Pretraining_CS+', 'Discrimination_CS+', 'Discrimination_CS-']}) if 'release_of_inhibition' in plotting: trace_args_copy = trace_args.copy() trace_args_copy.update({'alpha': .5, 'linewidth': .75}) line_args_copy = line_args.copy() line_args.update({'marker':',','markersize':0, 'linewidth':.5}) y_key = 'bin_ant_23_smooth' y_key_bool = 'bin_ant_23_boolean' phase_odor_valence = np.unique(res['phase_odor_valence']) conditions = np.unique(res['condition']) ax_args_cur = ax_args_copy.copy()
def plot_consistency_within_day(res, start, end, shuffle, pretraining, figure_path): d = list(zip(start, end)) res_temp = filter.filter_days_per_mouse(res, d) if pretraining: res_temp = filter.filter(res_temp, {'odor_valence': ['PT CS+']}) else: res_temp = filter.filter(res_temp, {'odor_valence': ['CS+', 'CS-']}) corr_res = _correlation(res_temp) corr_res.pop('data') analysis.add_naive_learned(corr_res, start, end, '0', '1') res_ = reduce.new_filter_reduce( corr_res, filter_keys=['mouse', 'odor_standard', 'training_day'], reduce_key='consistency_corrcoef') res_.pop('consistency_corrcoef_sem') filter.assign_composite(res_, loop_keys=['training_day', 'odor_valence']) if shuffle: s = '_shuffled' else: s = '' ax_args_copy = ax_args.copy() ax_args_copy.update({ 'xlim': [-.5, 2.5], 'ylim': [0, .55], 'yticks': np.arange(0, 1.1, .1) }) swarm_args_copy = swarm_args.copy() if pretraining: swarm_args_copy.update({'palette': ['gray', 'orange', 'green', 'red']}) else: swarm_args_copy.update({'palette': ['gray', 'gray', 'green', 'red']}) ix = res_['training_day_odor_valence'] == '1_PT CS+' res_['training_day_odor_valence'][ix] = '1_APT CS+' plot.plot_results(res_, x_key='training_day_odor_valence', y_key='consistency_corrcoef', path=figure_path, plot_args=swarm_args_copy, plot_function=sns.stripplot, ax_args=ax_args_copy, reuse=False, save=False, sort=True, name_str=s) summary = reduce.new_filter_reduce(res_, filter_keys='training_day_odor_valence', reduce_key='consistency_corrcoef') plot.plot_results(summary, x_key='training_day_odor_valence', y_key='consistency_corrcoef', error_key='consistency_corrcoef_sem', colors='black', path=figure_path, plot_args=error_args, plot_function=plt.errorbar, save=True, reuse=True, legend=False, name_str=s) print(summary['consistency_corrcoef']) ix_a = res_['training_day_odor_valence'] == '0_CS+' ix_b = res_['training_day_odor_valence'] == '0_CS-' ix_c = res_['training_day_odor_valence'] == '1_CS+' ix_d = res_['training_day_odor_valence'] == '1_CS-' a = res_['consistency_corrcoef'][ix_a] b = res_['consistency_corrcoef'][ix_b] c = res_['consistency_corrcoef'][ix_c] d = res_['consistency_corrcoef'][ix_d] from scipy.stats import ranksums, wilcoxon, kruskal import scikit_posthocs print(kruskal(a, b, c)) x = scikit_posthocs.posthoc_dunn(a=[a, b, c, d], p_adjust=None) print(x)
def plot_stability_across_days(res, start_days_per_mouse, learned_days_per_mouse, figure_path): strengthen_starting_threshold = .1 strengthen_absolute_threshold = .2 strengthen_relative_threshold = 2 weaken_starting_threshold = .3 weaken_absolute_threshold = .15 weaken_relative_threshold = .5 res = copy.copy(res) res = filter.filter(res, {'odor_valence':['CS+', 'CS-']}) list_odor_on = res['DAQ_O_ON_F'] list_water_on = res['DAQ_W_ON_F'] for i in range(len(list_odor_on)): dff_list = res['dff'][i] dff_max = np.max(dff_list[:,list_odor_on[i]: list_water_on[i]],axis=1) res['dff_max'].append(dff_max) res['dff_max'] = np.array(res['dff_max']) out = defaultdict(list) combinations, ixs = filter.retrieve_unique_entries(res, ['mouse','odor']) for combination, ix in zip(combinations, ixs): odor_valence = np.unique(res['odor_valence'][ix]) mouse = np.unique(res['mouse'][ix]) days = res['day'][ix] assert len(days) == len(np.unique(days)) assert len(mouse) == 1 sort_ix = np.argsort(days) list_of_dff_max = res['dff_max'][ix][sort_ix] list_of_ssig = res['sig'][ix][sort_ix] data = [x * y for x, y in zip(list_of_ssig, list_of_dff_max)] data = np.array(data) strengthen_mask = data[0,:] > strengthen_starting_threshold strengthen_overall_threshold = np.max((data[0,:] * strengthen_relative_threshold, data[0,:] + strengthen_absolute_threshold), axis=0) strengthen_passed_mask = strengthen_overall_threshold < data strengthen_any = np.any(strengthen_passed_mask[1:,:], axis=0) n_strengthen_passed = np.sum(strengthen_any * strengthen_mask) n_strengthen_denom = np.sum(strengthen_mask) new_mask = np.invert(strengthen_mask) n_new_passed = np.sum(strengthen_any * new_mask) n_new_denom = np.sum(new_mask) weaken_mask = data[0,:] > weaken_starting_threshold weaken_overall_threshold = np.min((data[0,:] * weaken_relative_threshold, data[0,:] - weaken_absolute_threshold), axis=0) weaken_passed_mask = weaken_overall_threshold > data weaken_any = np.any(weaken_passed_mask[1:,:], axis=0) n_weaken_passed = np.sum(weaken_any * weaken_mask) n_weaken_denom = np.sum(weaken_mask) strs = ['strengthen_denom', 'strengthen_pass', 'new_denom', 'new_pass','weaken_denom','weaken_pass'] vals = [n_strengthen_denom, n_strengthen_passed, n_new_denom, n_new_passed, n_weaken_denom, n_weaken_passed] for k, v in zip(strs,vals): out['Type'].append(k) out['Count'].append(v) out['mouse'].append(mouse[0]) out['odor_valence'].append(odor_valence[0]) for k, v in out.items(): out[k] = np.array(v) def _helper(res): out = defaultdict(list) strs = [['strengthen_denom', 'strengthen_pass'], ['new_denom', 'new_pass'], ['weaken_denom', 'weaken_pass']] out_strs = ['up', 'new', 'down'] for i, keys in enumerate(strs): ix_denom = res['Type'] == keys[0] ix_numer = res['Type'] == keys[1] numer = np.sum(res['Count'][ix_numer]) denom = np.sum(res['Count'][ix_denom]) fraction = numer/ denom out['Type'].append(out_strs[i]) out['Fraction'].append(fraction) out['numer'].append(numer) out['denom'].append(denom) for k, v in out.items(): out[k] = np.array(v) return out ax_args_copy = ax_args.copy() ax_args_copy.update({'ylim':[0, 0.5], 'yticks':[0, .1, .2, .3, .4, .5]}) overall = copy.copy(out) csm_res = filter.filter(overall, {'odor_valence':'CS-'}) csp_res = filter.filter(overall, {'odor_valence':'CS+'}) csp_stats = _helper(csp_res) csp_stats['Condition'] = np.array(['CS+'] * len(csp_stats['Type'])) csm_stats = _helper(csm_res) csm_stats['Condition'] = np.array(['CS-'] * len(csm_stats['Type'])) overall_stats = reduce.chain_defaultdicts(csp_stats, csm_stats, copy_dict=True) filter.assign_composite(overall_stats, ['Type', 'Condition']) bar_args = {'alpha': 1, 'edgecolor':'black','linewidth':1} colors = ['Green','Red'] save_path, name = plot.plot_results(overall_stats, x_key='Type_Condition', y_key='Fraction', sort=True, colors=colors, path=figure_path, plot_function=plt.bar, plot_args=bar_args, ax_args=ax_args_copy, save=False, reuse=False) strs = ['down','new','up'] fontsize = 4 for i in range(3): ix = csp_stats['Type'] == strs[i] numer = csp_stats['numer'][ix][0] denom = csp_stats['denom'][ix][0] x = i * 2 y = numer/denom y_offset = .025 plt.text(x, y + y_offset, str(numer) + '/' + str(denom), horizontalalignment = 'center', fontsize= fontsize) strs = ['down','new','up'] for i in range(3): ix = csm_stats['Type'] == strs[i] numer = csm_stats['numer'][ix][0] denom = csm_stats['denom'][ix][0] x = i * 2 + 1 y = numer/denom y_offset = .025 plt.text(x, y + y_offset, str(numer) + '/' + str(denom), horizontalalignment = 'center', fontsize= fontsize) plot._easy_save(save_path, name, pdf=True) overall_stats_no_distinction = _helper(overall) save_path, name = plot.plot_results(overall_stats_no_distinction, x_key='Type', y_key='Fraction', sort=True, colors=['Grey']*10, path=figure_path, plot_function=plt.bar, plot_args=bar_args, ax_args=ax_args_copy, save=False, reuse=False) strs = ['down','new','up'] for i in range(3): ix = overall_stats_no_distinction['Type'] == strs[i] numer = overall_stats_no_distinction['numer'][ix][0] denom = overall_stats_no_distinction['denom'][ix][0] x = i y = numer/denom y_offset = .025 plt.text(x, y + y_offset, str(numer) + '/' + str(denom), horizontalalignment = 'center', fontsize= fontsize) plot._easy_save(save_path, name, pdf=True)
else: raise ValueError('wtf') if 'summary_raw' in experiments: line_args_local = line_args.copy() line_args_local.update({ 'marker': '.', 'markersize': .5, 'linewidth': .75, 'alpha': .5 }) all_res_ = filter.filter(all_res, {'odor_valence': ['CS+', 'CS-', 'PT CS+']}) _collapse_conditions(all_res_, control_condition='YFP', str=collapse_arg) filter.assign_composite(all_res_, [collapse_arg, 'odor_valence']) composite_arg = collapse_arg + '_' + 'odor_valence' valences = np.unique(all_res_['odor_valence']) for valence in valences: color = [color_dict_valence[valence]] for i in range(len(color)): color.append('black') if 'PT CS+' in valence or 'PT Naive' in valence: ax_args = ax_args_pt elif 'PT CS+' in all_res_['odor_valence']: ax_args = ax_args_dt else: ax_args = ax_args_mush
def magnitude_histogram(res, learned_days, end_days, use_colors=True, figure_path=None, reuse=False): def _helper(res): list_odor_on = res['DAQ_O_ON_F'] list_water_on = res['DAQ_W_ON_F'] list_of_dff = res['dff'] for i, dff in enumerate(list_of_dff): s = list_odor_on[i] e = list_water_on[i] max = np.max(dff[:, s:e], axis=1) res['max_dff'].append(max) res['max_dff'] = np.array(res['max_dff']) def _helper1(res): for data in res['amplitude']: res['max_dff'].append(data[data > 0]) res['max_dff'] = np.array(res['max_dff']) res = copy.copy(res) # list_of_days = list(zip(learned_days, end_days)) list_of_days = end_days start_end_day_res = filter.filter_days_per_mouse( res, days_per_mouse=list_of_days) _helper(start_end_day_res) add_naive_learned(start_end_day_res, learned_days, end_days) filter.assign_composite(start_end_day_res, loop_keys=['odor_standard', 'training_day']) csp = filter.filter(start_end_day_res, filter_dict={'odor_valence': 'CS+'}) csm = filter.filter(start_end_day_res, filter_dict={'odor_valence': 'CS-'}) csp_data = np.hstack(csp['max_dff'].flat) csm_data = np.hstack(csm['max_dff'].flat) fig = plt.figure(figsize=(3, 2)) ax = fig.add_axes([.2, .2, .7, .7]) x_upper = 1.01 y_upper = .5 bins = 20 xrange = [0, x_upper] yrange = [0, y_upper] xticks = np.arange(0, x_upper, .2) yticks = np.arange(0, y_upper, 3) legends = ['CS+', 'CS-'] colors = ['green', 'red'] for i, data in enumerate([csp_data, csm_data]): plt.hist(data, bins=bins, range=xrange, density=True, color=colors[i], alpha=.5) plt.legend(legends, loc=1, bbox_to_anchor=(1.05, .4), fontsize=5) ax.set_xlabel('DF/F') ax.set_ylabel('Fraction') ax.set_xticks(xticks) # ax.set_yticks(yticks) plt.xlim(xrange) # plt.ylim(yrange) plt.show()