示例#1
0
def get_sensitivity(permpar):
    """
    get_sensitivity(permpar)

    Returns p-value sensitivity, i.e., the smallest non zero p-value that can 
    be measured given the number of permutations used and Bonferroni 
    corrections for number of tails and multiple comparisons.
    
    Required args:
        - permpar (PermPar or dict): 
            named tuple containing permutation parameters

    Returns:
        - sensitivity (float): 
            minimum theoretical p-value
    """

    if isinstance(permpar, dict):
        permpar = sess_ntuple_util.init_permpar(**permpar)

    n_tails = 1 if permpar.tails in ["lo", "hi"] else int(permpar.tails)
    sensitivity = n_tails / permpar.n_perms

    if permpar.multcomp:
        sensitivity *= permpar.multcomp


    return sensitivity
示例#2
0
def set_multcomp(permpar, sess_df, CIs=True, pairs=True, factor=1):
    """
    set_multcomp(permpar)

    Returns permpar updated with the number of comparisons computed from the 
    sessions.

    Required args:
        - permpar (PermPar): 
            named tuple containing permutation parameters
        - sess_df (pd.DataFrame):
            dataframe containing session information, including the following 
            keys: "sess_ns", "lines", "planes"
    
    Optional args:
        - CIs (bool):
            include comparisons to CIs comparisons
            default: True
        - pairs (bool):
            include paired comparisons
            default: True
        - factor (int): 
            additional factor by which to multiply the number of comparisons
            default: 1

    Returns:
        - permpar (PermPar): 
            updated permutation parameter named tuple
    """

    if isinstance(permpar, dict):
        permpar = sess_ntuple_util.init_permpar(**permpar)

    n_comps = 0    
    for _, sess_df_grp in sess_df.groupby(["lines", "planes"]):
        n_sess = len(sess_df_grp)

        # sessions compared to CIs
        if CIs:
            n_comps += n_sess

        # session pair comparisons
        if pairs:
            k = 2
            if n_sess >= k:
                fact = np.math.factorial
                n_comps += fact(n_sess) / (fact(k) * fact(n_sess - k))

    # multiplied by specified factor
    n_comps *= factor

    permpar = sess_ntuple_util.get_modif_ntuple(
            permpar, "multcomp", int(n_comps)
        )

    return permpar
示例#3
0
def add_corr_p_vals(df, permpar, raise_multcomp=True):
    """
    add_corr_p_vals(df, permpar)

    Returns dataframe with p-values, corrected for tails and multiple 
    comparisons, added, if permpar.multcomp is True. If any case, original 
    "p_vals" column names are returned as "raw_p_vals" instead.
    
    Required args:
        - df (pd.DataFrame): 
            dataframe with p-value columns ("p_vals" in column names)
        - permpar (PermPar or dict): 
            named tuple containing permutation parameters

    Optional args:
        - raise_multcomp (bool):
            if True, an error is raised if permpar.multcomp is False
            default: True

    Returns:
        - df (pd.DataFrame): 
            dataframe with raw p-value columns names changed to "raw_{}", 
            and corrected p-value columns added, if permpar.multcomp
    """

    if isinstance(permpar, dict):
        permpar = sess_ntuple_util.init_permpar(**permpar)

    p_val_cols = [col for col in df.columns if "p_vals" in col]

    if sum(["raw_p_vals" in col for col in p_val_cols]):
        raise ValueError(
            "Function converts 'p_vals' columns to 'raw_p_vals' columns. "
            "Dataframe should not already contain columns with 'raw_p_vals' "
            "in name.")

    new_col_names = {
        col: col.replace("p_vals", "raw_p_vals") for col in p_val_cols
        }
    df = df.rename(columns=new_col_names)
    # define function with arguments for use with .map()
    correct_p_val_fct = lambda x: get_corrected_p_val(
        x, permpar, raise_multcomp
        )

    for corr_p_val_col in p_val_cols:
        raw_p_val_col = corr_p_val_col.replace("p_vals", "raw_p_vals")
        df[corr_p_val_col] = df[raw_p_val_col].map(correct_p_val_fct)
    
    return df
示例#4
0
def get_comp_info(permpar):
    """
    get_comp_info(permpar)

    Returns p-value correction information.
    
    Required args:
        - permpar (PermPar or dict): 
            named tuple containing permutation parameters

    Returns:
        - full_comp_info (str): 
            string containing tails and multiple comparisons information
    """

    if isinstance(permpar, dict):
        permpar = sess_ntuple_util.init_permpar(**permpar)

    if permpar.tails == "lo":
        comp_info = "one-tailed"
    elif permpar.tails == "hi":
        comp_info = "one-tailed"
    elif int(permpar.tails) == 2:
        comp_info = "two-tailed"
    else:
        gen_util.accepted_values_error(
            "permpar.tails", permpar.tails, ["lo", "hi", 2]
            )

    if permpar.multcomp:
        comp_info = f"{int(permpar.multcomp)} comparisons, {comp_info}"
        corr_str = "Corrected"
    else:
        corr_str = "Raw"
    
    full_comp_info = f"{corr_str} p-values ({comp_info})"

    return full_comp_info
示例#5
0
def get_corrected_p_val(p_val, permpar, raise_multcomp=True):
    """
    get_corrected_p_val(p_val, permpar)

    Returns p-value, Bonferroni corrected for number of tails and multiple 
    comparisons.
    
    Required args:
        - p_val (float): 
            raw p-value
        - permpar (PermPar or dict): 
            named tuple containing permutation parameters

    Optional args:
        - raise_multcomp (bool):
            if True, an error is raised if permpar.multcomp is False
            default: True

    Returns:
        - corr_p_val (float): 
            corrected p-value
    """

    if isinstance(permpar, dict):
        permpar = sess_ntuple_util.init_permpar(**permpar)

    n_tails = 1 if permpar.tails in ["lo", "hi"] else int(permpar.tails)
    corr_p_val = p_val * n_tails 
    
    if permpar.multcomp:
        corr_p_val *= permpar.multcomp
    elif raise_multcomp:
        raise ValueError("permpar.multcomp is set to False.")

    corr_p_val = np.min([corr_p_val, 1])

    return corr_p_val
示例#6
0
def init_param_cont(args):
    """
    init_param_cont(args)

    Initializes parameter containers.

    Returns args:
        - in the following nametuples: analyspar, sesspar, stimpar, autocorr, 
                                       permpar, quantpar
        - in the following dictionary: figpar 

    Required args:
        - args (Argument parser): parser with the following attributes:

            visflow_dir (str or list): visual flow direction values to include
                                     ("right", "left", ["right", "left"])
            visflow_size (int or list): visual flow size values to include
                                     (128, 256 or [128, 256])
            closest (bool)         : if False, only exact session number is 
                                     retained, otherwise the closest.
            error (str)            : error statistic parameter ("std" or "sem")
            fontdir (str)          : path to directory containing additional 
                                     fonts
            gabfr (int)            : gabor frame at which sequences start 
                                     (0, 1, 2, 3)
            gabk (int or list)     : gabor kappa values to include 
                                     (4, 16 or [4, 16])
            gab_ori (int or list)  : gabor orientation values to include
                                     ([0, 45, 90, 135, 180, 225])
            incl (str)             : sessions to include ("yes", "no", "all")     
            keepnans (str)         : if True, the original running array is 
                                     used instead of the one where NaNs
                                     are interpolated.
            lag_s (num)            : lag for autocorrelation (in sec)
            line (str)             : line ("L23", "L5", "any")
            min_rois (int)         : min number of ROIs
            n_perms (int)          : nbr of permutations to run
            n_quants (int)         : number of quantiles
            ncols (int)            : number of columns
            no_datetime (bool)     : if True, figures are not saved in a 
                                     subfolder named based on the date and time.
            no_sharey (bool)       : if True, sharey figure parameter is set to 
                                     False.
            not_save_fig (bool)    : if True, figures are not saved
            output (str)           : general directory in which to save output
            overwrite (bool)       : if False, overwriting existing figures 
                                     is prevented by adding suffix numbers.
            pass_fail (str or list): pass/fail values of interest ("P", "F")
            plane (str)            : plane ("soma", "dend", "any")
            plt_bkend (str)        : mpl backend to use
            post (num)             : range of frames to include after each 
                                     reference frame (in s)
            pre (num)              : range of frames to include before each 
                                     reference frame (in s)
            runtype (str or list)  : runtype ("pilot" or "prod")
            scale (bool)           : whether to scale running data
            sess_n (int)           : session number
            stats (str)            : statistic parameter ("mean" or "median")
            stimtype (str)         : stimulus to analyse ("visflow" or "gabors")
            tails (str or int)     : which tail(s) to test ("hi", "lo", 2)

    Returns:
        - analysis_dict (dict): dictionary of analysis parameters
            ["analyspar"] (AnalysPar)    : named tuple of analysis parameters
            ["sesspar"] (SessPar)        : named tuple of session parameters
            ["stimpar"] (StimPar)        : named tuple of stimulus parameters
            ["autocorrpar"] (AutocorrPar): named tuple of autocorrelation 
                                           parameters
            ["permpar"] (PermPar)        : named tuple of permutation parameters
            ["quantpar"] (QuantPar)      : named tuple of quantile parameters
            ["figpar"] (dict)            : dictionary containing following 
                                           subdictionaries:
                ["init"]: dict with following inputs as attributes:
                    ["ncols"] (int)      : number of columns in the figures
                    ["sharex"] (bool)    : if True, x axis lims are shared 
                                           across subplots
                    ["sharey"] (bool)    : if True, y axis lims are shared 
                                           across subplots
                    ["subplot_hei"] (num): height of each subplot (inches)
                    ["subplot_wid"] (num): width of each subplot (inches)

                ["save"]: dict with the following inputs as attributes:
                    ["datetime"] (bool) : if True, figures are saved in a  
                                          subfolder named based on the date and 
                                          time.
                    ["fig_ext"] (str)   : figure extension
                    ["overwrite"] (bool): if True, existing figures can be 
                                          overwritten
                    ["save_fig"] (bool) : if True, figures are saved
                    ["use_dt"] (str)    : datetime folder to use

                ["dirs"]: dict with the following attributes:
                    ["figdir"] (str)   : main folder in which to save figures
                    ["roi"] (str)      : subdirectory name for ROI analyses
                    ["run"] (str)      : subdirectory name for running analyses
                    ["autocorr"] (str) : subdirectory name for autocorrelation 
                                         analyses
                    ["locori"] (str)   : subdirectory name for location and 
                                         orientation responses
                    ["oridir"] (str)   : subdirectory name for 
                                         orientation/direction analyses
                    ["unexp_qu"] (str)  : subdirectory name for unexpected, 
                                         quantile analyses
                    ["tune_curv"] (str): subdirectory name for tuning curves
                    ["grped"] (str)    : subdirectory name for ROI grps data
                    ["mags"] (str)     : subdirectory name for magnitude 
                                         analyses
                
                ["mng"]: dict with the following attributes:
                    ["plt_bkend"] (str): mpl backend to use
                    ["linclab"] (bool) : if True, Linclab mpl defaults are used
                    ["fontdir"] (str)  : path to directory containing 
                                         additional fonts
    """

    args = copy.deepcopy(args)

    analysis_dict = dict()

    # analysis parameters
    analysis_dict["analyspar"] = sess_ntuple_util.init_analyspar(
        "n/a", not (args.keepnans), args.stats, args.error, args.scale)

    # session parameters
    analysis_dict["sesspar"] = sess_ntuple_util.init_sesspar(
        args.sess_n, args.closest, args.plane, args.line, args.min_rois,
        args.pass_fail, args.incl, args.runtype)

    # stimulus parameters
    analysis_dict["stimpar"] = sess_ntuple_util.init_stimpar(
        args.stimtype, args.visflow_dir, args.visflow_size, args.gabfr,
        args.gabk, args.gab_ori, args.pre, args.post)

    # SPECIFIC ANALYSES
    # autocorrelation parameters
    analysis_dict["autocorrpar"] = sess_ntuple_util.init_autocorrpar(
        args.lag_s, byitem=False)

    # permutation parameters
    analysis_dict["permpar"] = sess_ntuple_util.init_permpar(
        args.n_perms, 0.05, args.tails, False)

    # quantile parameters
    analysis_dict["quantpar"] = sess_ntuple_util.init_quantpar(
        args.n_quants, [0, -1])

    # figure parameters
    analysis_dict["figpar"] = sess_plot_util.init_figpar(
        ncols=int(args.ncols),
        datetime=not (args.no_datetime),
        overwrite=args.overwrite,
        save_fig=not (args.not_save_fig),
        runtype=args.runtype,
        output=args.output,
        plt_bkend=args.plt_bkend,
        fontdir=args.fontdir,
        sharey=not (args.no_sharey))

    return analysis_dict
示例#7
0
def init_analysis(args):
    """
    init_analysis(args)

    Initializes analysis parameters based on input arguments containers.

    Required args:
        - args (dict): 
            parser argument dictionary

    Returns:
        - analysis_dict (dict): 
            dictionary of analysis parameters
            ["analyspar"] (AnalysPar): named tuple of analysis parameters
            ["sesspar"] (SessPar): named tuple with session parameters
            ["stimpar"] (StimPar): named tuple with stimulus parameters
            ["basepar"] (LatPar): named tuple with latency parameters
            ["idxpar"] (PermPar): named tuple with unexpected event index 
                parameters
            ["logregpar"] (LogRegPar): 
                named tuple with logistic regression parameters
            ["permpar"] (PermPar): named tuple with permutation parameters
            ["figpar"] (dict): dictionary containing subdictionaries 
                (see sess_plot_util.init_figpar), with fig_panel_analysis 
                added under the "fig_panel_analysis" key.
    """

    args = copy.deepcopy(args)

    fig_panel_analysis = paper_organization.FigurePanelAnalysis(
        figure=args.figure,
        panel=args.panel,
        datadir=args.datadir,
        mouse_df_path=args.mouse_df_path,
        output=args.output,
        full_power=args.full_power,
        seed=args.seed,
        parallel=args.parallel,
        plt_bkend=args.plt_bkend,
        fontdir=args.fontdir,
    )

    specific_params = fig_panel_analysis.specific_params
    sess_n = reformat_sess_n(specific_params["sess_n"])

    analysis_dict = dict()

    # analysis parameters
    analysis_dict["analyspar"] = sess_ntuple_util.init_analyspar(
        fluor="dff",  # type of fluorescence data to use (dF/F)
        rem_bad=specific_params[
            "rem_bad"],  # whether to remove bad ROIs OR interpolate bad values in run or pupil data
        stats="mean",  # type of statistic to measure (mean/median)
        error=specific_params["error"],  # type of error to measure (std/SEM)
        scale=specific_params[
            "scale"],  # whether to scale ROIs (robust scaling)
        tracked=specific_params["tracked"],  # whether to use only tracked ROIs
    )

    # session inclusion parameters
    analysis_dict["sesspar"] = sess_ntuple_util.init_sesspar(
        sess_n=sess_n,  # session number(s)
        plane=specific_params["plane"],  # recording plane(s)
        line=specific_params["line"],  # mouse line(s)
        pass_fail="P",  # include sessions that passed QC
        incl="all",  # include all remaining sessions
        runtype="prod",  # production run data
        mouse_n=specific_params["mouse_n"],  # mouse numbers
    )

    # stimulus analysis parameters
    analysis_dict["stimpar"] = sess_ntuple_util.init_stimpar(
        stimtype=specific_params["stimtype"],  # stimulus to analyse
        visflow_dir=specific_params["visflow_dir"],  # visual flow directions
        visflow_size=specific_params[
            "visflow_size"],  # visual flow square sizes
        gabfr=specific_params["gabfr"],  # Gabor frame to center analyses on
        gabk=specific_params["gabk"],  # Gabor orientation kappas
        gab_ori=specific_params["gab_ori"],  # mean Gabor orientations
        pre=specific_params["pre"],  # number of seconds pre reference frame
        post=specific_params["post"]  # number of seconds post reference frame
    )

    # baseline parameters
    analysis_dict["basepar"] = sess_ntuple_util.init_basepar(
        baseline=0,  # sequence baselining (None)
    )

    # USI analysis parameters
    analysis_dict["idxpar"] = sess_ntuple_util.init_idxpar(
        op="d-prime",  # USI measure
        feature=specific_params["idx_feature"],  # how to select sequences
    )

    # logistic regression parameters
    analysis_dict["logregpar"] = sess_ntuple_util.init_logregpar(
        comp=specific_params["comp"],  # classes
        ctrl=True,  # control for dataset size
        n_epochs=1000,  # number of training epochs
        batchsize=200,  # batch size
        lr=0.0001,  # learning rate
        train_p=0.75,  # train:test split
        wd=0,  # weight decay to use (None)
    )

    # permutation analysis parameters
    analysis_dict["permpar"] = sess_ntuple_util.init_permpar(
        n_perms=fig_panel_analysis.n_perms,  # number of permutations to run
        p_val=0.05,  # significance threshold to consider
        tails=specific_params["tails"],  # number of tails
        multcomp=False  # multiple comparisons
    )

    # figure plotting parameters
    analysis_dict["figpar"] = sess_plot_util.init_figpar(
        datetime=False,
        overwrite=args.overwrite,
        runtype="prod",
        output=args.output,
        plt_bkend=args.plt_bkend,
        fontdir=args.fontdir,
        paper=True,
    )

    analysis_dict["figpar"]["fig_panel_analysis"] = fig_panel_analysis

    return analysis_dict
def init_param_cont(args):
    """
    init_param_cont(args)

    Initializes parameter containers.

    Returns args:
        - in the following nametuples: analyspar, sesspar, stimpar, permpar, 
                                       basepar, idxpar, latpar
        - in the following dictionary: figpar 

    Required args:
        - args (Argument parser): parser with the following attributes:

            base (float)             : baseline value to use
            visflow_dir (str or list): visual flow direction values to include
                                       ("right", "left", ["right", "left"])
            visflow_size (int or list): visual flow size values to include
                                       (128, 256 or [128, 256])
            dend (str)               : type of dendrites to use 
                                       ("allen" or "dend")
            error (str)              : error statistic parameter 
                                       ("std" or "sem")
            fluor (str)              : if "raw", raw ROI traces are used. If 
                                       "dff", dF/F ROI traces are used.
            fontdir (str)            : path to directory containing additional 
                                       fonts
            gabfr (int)              : gabor frame at which sequences start 
                                       (0, 1, 2, 3)
            gabk (int or list)       : gabor kappa values to include 
                                       (4, 16 or [4, 16])
            gab_ori (int or list)    : gabor orientation values to include
                                       ([0, 45, 90, 135, 180, 225])
            idx_feature (str)        : feature used to calculate index
                                       ("by_exp", "unexp_lock", "prog_unexp")
            idx_op (str)             : type of index to use 
                                       ("d-prime", "rel_diff", "diff")
            idx_position (int)       : position to use if using a "prog" feature 
                                       to calculate index (e.g., 0)
            incl (str)               : sessions to include ("yes", "no", "all") 
            keepnans (str)           : if True, ROIs with NaN/Inf values are 
                                       kept in the analyses.
            lag_s (num)              : lag for autocorrelation (in sec)
            lat_method (str)         : latency calculation method 
                                       (ratio or ttest)
            lat_not_unexp_resp (bool): if False, only unexpected event 
                                       responsive ROIs are used for latency 
                                       analysis
            lat_p_val_thr (float)    : p-value threshold for ttest latency 
                                       method
            lat_std (float)          : standard deviation threshold for ratio 
                                       latency method
            line (str)               : "L23", "L5", "any"
            min_rois (int)           : min number of ROIs
            n_perms (int)            : nbr of permutations to run
            ncols (int)              : number of columns
            no_datetime (bool)       : if True, figures are not saved in a 
                                       subfolder named based on the date and 
                                       time.
            no_scale (bool)          : if True, data is not scaled
            not_save_fig (bool)      : if True, figures are not saved
            output (str)             : general directory in which to save output
            overwrite (bool)         : if False, overwriting existing figures 
                                       is prevented by adding suffix numbers.
            pass_fail (str or list)  : pass/fail values of interest ("P", "F")
            p_val (float)            : p-value threshold for significane tests
            plane (str)              : plane ("soma", "dend", "any")
            plt_bkend (str)          : mpl backend to use
            post (num)               : range of frames to include after each 
                                        reference frame (in s)
            pre (num)                : range of frames to include before each 
                                       reference frame (in s)
            rel_std (float)          : relative st. dev. threshold for ratio 
                                       latency method
            runtype (str or list)    : runtype ("pilot" or "prod")
            sess_n (int)             : session number
            stats (str)              : statistic parameter ("mean" or "median")
            stimtype (str)           : stimulus to analyse 
                                       ("visflow" or "gabors")
            tails (str or int)       : which tail(s) to test ("hi", "lo", 2)

    Returns:
        - analysis_dict (dict): dictionary of analysis parameters
            ["analyspar"] (AnalysPar): named tuple of analysis parameters
            ["sesspar"] (SessPar)    : named tuple of session parameters
            ["stimpar"] (StimPar)    : named tuple of stimulus parameters
            ["permpar"] (PermPar)    : named tuple of permutation parameters
            ["basepar"] (BasePar)    : named tuple of baseline parameters
            ["idxpar"] (IdxPar)      : named tuple of unexpected index parameters
            ["latpar"] (LatPar)      : named tuple of latency parameters
            ["figpar"] (dict)        : dictionary containing following 
                                       subdictionaries:
                ["init"]: dict with following inputs as attributes:
                    ["ncols"] (int)      : number of columns in the figures
                    ["sharex"] (bool)    : if True, x axis lims are shared 
                                           across subplots
                    ["sharey"] (bool)    : if True, y axis lims are shared 
                                           across subplots
                    ["subplot_hei"] (num): height of each subplot (inches)
                    ["subplot_wid"] (num): width of each subplot (inches)

                ["save"]: dict with the following inputs as attributes:
                    ["datetime"] (bool) : if True, figures are saved in a  
                                          subfolder named based on the date and 
                                          time.
                    ["fig_ext"] (str)   : figure extension
                    ["overwrite"] (bool): if True, existing figures can be 
                                          overwritten
                    ["save_fig"] (bool) : if True, figures are saved
                    ["use_dt"] (str)    : datetime folder to use
                    
                ["dirs"]: dict with the following attributes:
                    ["figdir"] (str)   : main folder in which to save figures
                    ["roi"] (str)      : subdirectory name for ROI analyses
                    ["run"] (str)      : subdirectory name for running analyses
                    ["autocorr"] (str) : subdirectory name for autocorrelation 
                                         analyses
                    ["locori"] (str)   : subdirectory name for location and 
                                         orientation responses
                    ["oridir"] (str)   : subdirectory name for 
                                         orientation/direction analyses
                    ["unexp_qu"] (str) : subdirectory name for unexpected, 
                                         quantile analyses
                    ["tune_curv"] (str): subdirectory name for tuning curves
                    ["grped"] (str)    : subdirectory name for ROI grps data
                    ["mags"] (str)     : subdirectory name for magnitude 
                                         analyses
                
                ["mng"]: dict with the following attributes:
                    ["plt_bkend"] (str): mpl backend to use
                    ["linclab"] (bool) : if True, Linclab mpl defaults are used
                    ["fontdir"] (str)  : path to directory containing 
                                         additional fonts
    """

    args = copy.deepcopy(args)

    analysis_dict = dict()

    # analysis parameters
    analysis_dict["analyspar"] = sess_ntuple_util.init_analyspar(
        args.fluor,
        not (args.keepnans),
        args.stats,
        args.error,
        scale=not (args.no_scale),
        dend=args.dend)

    # session parameters
    analysis_dict["sesspar"] = sess_ntuple_util.init_sesspar(
        args.sess_n, False, args.plane, args.line, args.min_rois,
        args.pass_fail, args.incl, args.runtype, args.mouse_ns)

    # stimulus parameters
    analysis_dict["stimpar"] = sess_ntuple_util.init_stimpar(
        args.stimtype, args.visflow_dir, args.visflow_size, args.gabfr,
        args.gabk, args.gab_ori, args.pre, args.post)

    # SPECIFIC ANALYSES
    analysis_dict["permpar"] = sess_ntuple_util.init_permpar(
        args.n_perms, args.p_val, args.tails, False)

    analysis_dict["basepar"] = sess_ntuple_util.init_basepar(args.base)

    analysis_dict["idxpar"] = sess_ntuple_util.init_idxpar(
        args.idx_op, args.idx_feature, args.idx_position)

    analysis_dict["latpar"] = sess_ntuple_util.init_latpar(
        args.lat_method, args.lat_p_val_thr, args.lat_rel_std,
        not (args.lat_not_unexp_resp))

    # figure parameters
    analysis_dict["figpar"] = sess_plot_util.init_figpar(
        ncols=int(args.ncols),
        datetime=not (args.no_datetime),
        overwrite=args.overwrite,
        save_fig=not (args.not_save_fig),
        runtype=args.runtype,
        output=args.output,
        plt_bkend=args.plt_bkend,
        fontdir=args.fontdir)

    return analysis_dict
示例#9
0
def init_param_cont(args):
    """
    init_param_cont(args)

    Initializes parameter containers.

    Returns args:
        - in the following nametuples: analyspar, sesspar, stimpar, autocorr, 
                                       permpar, quantpar, roigrppar, tcurvpar
        - in the following dictionary: figpar 

    Required args:
        - args (Argument parser): parser with the following attributes:

            visflow_dir (str or list): visual flow direction values to include
                                     ("right", "left", ["right", "left"])
            visflow_size (int or list): visual flow size values to include
                                     (128, 256 or [128, 256])
            closest (bool)         : if False, only exact session number is 
                                     retained, otherwise the closest.
            dend (str)             : type of dendrites to use ("allen" or "dend")
            error (str)            : error statistic parameter ("std" or "sem")
            fluor (str)            : if "raw", raw ROI traces are used. If 
                                     "dff", dF/F ROI traces are used.
            fontdir (str)          : path to directory containing additional 
                                     fonts
            gabfr (int)            : gabor frame at which sequences start 
                                     (0, 1, 2, 3)
            gabk (int or list)     : gabor kappa values to include 
                                     (4, 16 or [4, 16])
            gab_ori (int or list)  : gabor orientation values to include
                                     ([0, 45, 90, 135, 180, 225])
            grps (str or list)     : set or sets of groups to return, 
                                     ("all", "change", "no_change", "reduc", 
                                     "incr".)
            incl (str)             : sessions to include ("yes", "no", "all") 
            keepnans (str)         : if True, ROIs with NaN/Inf values are 
                                     kept in the analyses.
            lag_s (num)            : lag for autocorrelation (in sec)
            line (str)             : "L23", "L5", "any"
            min_rois (int)         : min number of ROIs
            n_perms (int)          : nbr of permutations to run
            n_quants (int)         : number of quantiles
            ncols (int)            : number of columns
            no_add_exp (bool)      : if True, the group of ROIs showing no 
                                     significance in either is not added to   
                                     the groups returned
            no_datetime (bool)     : if True, figures are not saved in a 
                                     subfolder named based on the date and time.
            not_byitem (bool)      : if True, autocorrelation statistics are
                                     taken across items (e.g., ROIs)
            not_save_fig (bool)    : if True, figures are not saved
            op (str)               : operation on values, if plotvals if "both" 
                                     ("ratio" or "diff") 
            output (str)           : general directory in which to save output
            overwrite (bool)       : if False, overwriting existing figures 
                                     is prevented by adding suffix numbers.
            pass_fail (str or list): pass/fail values of interest ("P", "F")
            plot_vals (str)        : values to plot ("unexp", "exp", "both")
            plane (str)            : plane ("soma", "dend", "any")
            plt_bkend (str)        : mpl backend to use
            post (num)             : range of frames to include after each 
                                     reference frame (in s)
            pre (num)              : range of frames to include before each 
                                     reference frame (in s)
            runtype (str or list)  : runtype ("pilot" or "prod")
            scale (bool)           : whether to scale ROI data
            sess_n (int)           : session number
            stats (str)            : statistic parameter ("mean" or "median")
            stimtype (str)         : stimulus to analyse ("visflow" or "gabors")
            tails (str or int)     : which tail(s) to test ("hi", "lo", 2)
            tc_gabfr (int or str)  : gabor frame at which sequences start 
                                     (0, 1, 2, 3) for tuning curve analysis
                                     (x_x, interpreted as 2 gabfrs)
            tc_grp2 (str)          : second group: either unexp, exp or rand 
                                     (random subsample of exp, the size of 
                                     unexp)
            tc_post (num)          : range of frames to include after each 
                                     reference frame (in s) for tuning curve 
                                     analysis
            tc_vm_estim (bool)     : runs analysis using von Mises parameter 
                                     estimation method
            tc_test (bool)         : if True, tuning curve analysis is run on a 
                                     small subset of ROIs and gabors

    Returns:
        - analysis_dict (dict): dictionary of analysis parameters
            ["analyspar"] (AnalysPar)    : named tuple of analysis parameters
            ["sesspar"] (SessPar)        : named tuple of session parameters
            ["stimpar"] (StimPar)        : named tuple of stimulus parameters
            ["autocorrpar"] (AutocorrPar): named tuple of autocorrelation 
                                           parameters
            ["permpar"] (PermPar)        : named tuple of permutation parameters
            ["quantpar"] (QuantPar)      : named tuple of quantile parameters
            ["roigrppar"] (RoiGrpPar)    : named tuple of roi grp parameters
            ["tcurvpar"] (TCurvPar)      : named tuple of tuning curve 
                                           parameters
            ["figpar"] (dict)            : dictionary containing following 
                                           subdictionaries:
                ["init"]: dict with following inputs as attributes:
                    ["ncols"] (int)      : number of columns in the figures
                    ["sharex"] (bool)    : if True, x axis lims are shared 
                                           across subplots
                    ["sharey"] (bool)    : if True, y axis lims are shared 
                                           across subplots
                    ["subplot_hei"] (num): height of each subplot (inches)
                    ["subplot_wid"] (num): width of each subplot (inches)

                ["save"]: dict with the following inputs as attributes:
                    ["datetime"] (bool) : if True, figures are saved in a  
                                          subfolder named based on the date and 
                                          time.
                    ["fig_ext"] (str)   : figure extension
                    ["overwrite"] (bool): if True, existing figures can be 
                                          overwritten
                    ["save_fig"] (bool) : if True, figures are saved
                    ["use_dt"] (str)    : datetime folder to use

                ["dirs"]: dict with the following attributes:
                    ["figdir"] (str)   : main folder in which to save figures
                    ["roi"] (str)      : subdirectory name for ROI analyses
                    ["run"] (str)      : subdirectory name for running analyses
                    ["autocorr"] (str) : subdirectory name for autocorrelation 
                                         analyses
                    ["locori"] (str)   : subdirectory name for location and 
                                         orientation responses
                    ["oridir"] (str)   : subdirectory name for 
                                         orientation/direction analyses
                    ["unexp_qu"] (str)  : subdirectory name for unexpected, 
                                         quantile analyses
                    ["tune_curv"] (str): subdirectory name for tuning curves
                    ["grped"] (str)    : subdirectory name for ROI grps data
                    ["mags"] (str)     : subdirectory name for magnitude 
                                         analyses
                
                ["mng"]: dict with the following attributes:
                    ["plt_bkend"] (str): mpl backend to use
                    ["linclab"] (bool) : if True, Linclab mpl defaults are used
                    ["fontdir"] (str)  : path to directory containing 
                                         additional fonts
    """

    args = copy.deepcopy(args)

    analysis_dict = dict()

    # analysis parameters
    analysis_dict["analyspar"] = sess_ntuple_util.init_analyspar(
        args.fluor, not(args.keepnans), args.stats, args.error, args.scale, 
        dend=args.dend)

    # session parameters
    analysis_dict["sesspar"] = sess_ntuple_util.init_sesspar(
        args.sess_n, args.closest, args.plane, args.line, args.min_rois, 
        args.pass_fail, args.incl, args.runtype)
    
    # stimulus parameters
    analysis_dict["stimpar"] = sess_ntuple_util.init_stimpar(
        args.stimtype, args.visflow_dir, args.visflow_size, args.gabfr, args.gabk, 
        args.gab_ori, args.pre, args.post)

    # SPECIFIC ANALYSES    
    # autocorrelation parameters
    analysis_dict["autocorrpar"] = sess_ntuple_util.init_autocorrpar(
        args.lag_s, not(args.not_byitem))
    
    # permutation parameters
    analysis_dict["permpar"] = sess_ntuple_util.init_permpar(
        args.n_perms, 0.05, args.tails)
    
    # quantile parameters
    analysis_dict["quantpar"] = sess_ntuple_util.init_quantpar(
        args.n_quants, [0, -1])

    # roi grp parameters
    analysis_dict["roigrppar"] = sess_ntuple_util.init_roigrppar(
        args.grps, not(args.no_add_exp), args.op, args.plot_vals)

    # tuning curve parameters
    analysis_dict["tcurvpar"] = sess_ntuple_util.init_tcurvpar(
        args.tc_gabfr, 0, args.tc_post, args.tc_grp2, args.tc_test, 
        args.tc_vm_estim)

    # figure parameters
    analysis_dict["figpar"] = sess_plot_util.init_figpar(
        ncols=int(args.ncols), datetime=not(args.no_datetime), 
        overwrite=args.overwrite, save_fig=not(args.not_save_fig), 
        runtype=args.runtype, output=args.output, plt_bkend=args.plt_bkend, 
        fontdir=args.fontdir)

    return analysis_dict