Example #1
0
def plot2D(result,par1,par2, 
           colorMap = getColorMap(), 
            labelSize = 15,
            fontSize = 10,
            axisHandle = None):
    """ 
    This function constructs a 2 dimensional marginal plot of the posterior
    density. This is the same plot as it is displayed in plotBayes in an
    unmodifyable way.

    The result struct is passed as result.
    par1 and par2 should code the two parameters to plot:
        0 = threshold
        1 = width
        2 = lambda
        3 = gamma
        4 = eta
        
    Further plotting options may be passed.
    """
    from utils import strToDim
    # convert strings to dimension number
    par1,label1 = strToDim(str(par1))
    par2,label2 = strToDim(str(par2))

    assert (par1 != par2), 'par1 and par2 must be different numbers to code for the parameters to plot'
    
    if axisHandle == None:
        axisHandle = plt.gca()
        
    try:
        plt.axes(axisHandle)
    except TypeError:
        raise ValueError('Invalid axes handle provided to plot in.')

    plt.set_cmap(colorMap)
    
    marg, _, _ = marginalize(result, np.array([par1, par2]))
    
    if par1 > par2 :
        marg = marg.T


    if 1 in marg.shape:
        if len(result['X1D'][par1])==1:
            plotMarginal(result,par2)
        else:
            plotMarginal(result,par2)
    else:
        e = [result['X1D'][par2][0], result['X1D'][par2][-1], \
             result['X1D'][par1][0], result['X1D'][par1][-1]]
        plt.imshow(marg, extent = e)
        plt.ylabel(label1,fontsize = labelSize)
        plt.xlabel(label2,fontsize = labelSize)
        
    plt.tick_params(direction='out',right='off',top='off')
    for side in ['top','right']: axisHandle.spines[side].set_visible(False)
    plt.ticklabel_format(style='sci',scilimits=(-2,4))
    plt.show()    
Example #2
0
def plot2D(result,
           par1,
           par2,
           colorMap=getColorMap(),
           labelSize=15,
           fontSize=10,
           axisHandle=None,
           showImediate=True):
    """ 
    This function constructs a 2 dimensional marginal plot of the posterior
    density. This is the same plot as it is displayed in plotBayes in an
    unmodifyable way.

    The result struct is passed as result.
    par1 and par2 should code the two parameters to plot:
        0 = threshold
        1 = width
        2 = lambda
        3 = gamma
        4 = eta
        
    Further plotting options may be passed.
    """
    from utils import strToDim
    # convert strings to dimension number
    par1, label1 = strToDim(str(par1))
    par2, label2 = strToDim(str(par2))

    assert (
        par1 != par2
    ), 'par1 and par2 must be different numbers to code for the parameters to plot'

    if axisHandle == None:
        axisHandle = plt.gca()

    try:
        plt.axes(axisHandle)
    except TypeError:
        raise ValueError('Invalid axes handle provided to plot in.')

    plt.set_cmap(colorMap)

    marg, _, _ = marginalize(result, np.array([par1, par2]))

    if par1 > par2:
        marg = marg.T

    if 1 in marg.shape:
        if len(result['X1D'][par1]) == 1:
            plotMarginal(result, par2)
        else:
            plotMarginal(result, par2)
    else:
        e = [result['X1D'][par2][0], result['X1D'][par2][-1], \
             result['X1D'][par1][0], result['X1D'][par1][-1]]
        plt.imshow(marg, extent=e)
        plt.ylabel(label1, fontsize=labelSize)
        plt.xlabel(label2, fontsize=labelSize)

    plt.tick_params(direction='out', right='off', top='off')
    for side in ['top', 'right']:
        axisHandle.spines[side].set_visible(False)
    plt.ticklabel_format(style='sci', scilimits=(-2, 4))
    if (showImediate):
        plt.show()
Example #3
0
def plotMarginal(result,                  
                 dim        = 0,
                 lineColor  = [0, 105/255, 170/255],
                 lineWidth  = 2,
                 xLabel     = '',
                 yLabel     = 'Marginal Density',
                 labelSize  = 15,
                 tufteAxis  = False,
                 prior      = True,
                 priorColor = [.7, .7, .7],
                 CIpatch    = True,
                 plotPE     = True,
                 axisHandle = None):
    """
    Plots the marginal for a single dimension.
    result       should be a result struct from the main psignifit routine
    dim          is the parameter to plot:
                   1=threshold, 2=width, 3=lambda, 4=gamma, 5=sigma
    """
    from utils import strToDim
    if isinstance(dim,str): dim = strToDim(dim)

    if len(result['marginals'][dim]) <= 1:
        print('Error: The parameter you wanted to plot was fixed in the analysis!')
        return
    if axisHandle == None: axisHandle = plt.gca()
    try:
        plt.axes(axisHandle)
        plt.rc('text', usetex=True)
    except TypeError:
        raise ValueError('Invalid axes handle provided to plot in.')
    if not xLabel:
        if   dim == 0: xLabel = 'Threshold'
        elif dim == 1: xLabel = 'Width'
        elif dim == 2: xLabel = r'$\lambda$'
        elif dim == 3: xLabel = r'$\gamma$'
        elif dim == 4: xLabel = r'$\eta$'
    
    x        = result['marginalsX'][dim]
    marginal = result['marginals'][dim]
    CI       = np.hstack(result['conf_Intervals'][dim].T)
    Fit      = result['Fit'][dim]
    
    holdState = plt.ishold()
    if not holdState: plt.cla()
    plt.hold(True)
    
    # patch for confidence region
    if CIpatch:
        xCI = np.array([CI[0], CI[1], CI[1], CI[0]])
        xCI = np.insert(xCI, 1, x[np.logical_and(x>=CI[0], x<=CI[1])])
        yCI = np.array([np.interp(CI[0], x, marginal), np.interp(CI[1], x, marginal), 0, 0])
        yCI = np.insert(yCI, 1, marginal[np.logical_and(x>=CI[0], x<=CI[1])])
        from matplotlib.patches import Polygon as patch
        color = .5*np.array(lineColor) + .5* np.array([1,1,1])
        axisHandle.add_patch(patch(np.array([xCI,yCI]).T, fc=color, ec=color))
    
    # plot prior
    if prior:
        xprior = np.linspace(min(x), max(x), 1000)
        plt.plot(xprior, result['options']['priors'][dim](xprior), '--', c=priorColor, clip_on=False)
    
    # posterior
    plt.plot(x, marginal, lw=lineWidth, c=lineColor, clip_on=False)
    # point estimate
    if plotPE:
        plt.plot([Fit,Fit], [0, np.interp(Fit, x, marginal)], 'k', clip_on=False)
    
    plt.xlim([min(x), max(x)])
    plt.ylim([0, 1.1*max(marginal)])
    
    plt.xlabel(xLabel, fontsize=labelSize, visible=True)
    # if tufteAxis
    plt.ylabel(yLabel, fontsize=labelSize, visible=True)
    # if tufteAxis
    # else:
    plt.tick_params(direction='out', right='off', top='off')
    for side in ['top','right']: axisHandle.spines[side].set_visible(False)
    plt.ticklabel_format(style='sci', scilimits=(-2,4))
    
    plt.hold(holdState)
    plt.show()
    return axisHandle
Example #4
0
def plotMarginal(result,
                 dim=0,
                 lineColor=[0, 105 / 255, 170 / 255],
                 lineWidth=2,
                 xLabel='',
                 yLabel='Marginal Density',
                 labelSize=15,
                 tufteAxis=False,
                 prior=True,
                 priorColor=[.7, .7, .7],
                 CIpatch=True,
                 plotPE=True,
                 axisHandle=None,
                 showImediate=True):
    """
    Plots the marginal for a single dimension.
    result       should be a result struct from the main psignifit routine
    dim          is the parameter to plot:
                   1=threshold, 2=width, 3=lambda, 4=gamma, 5=sigma
    """
    from utils import strToDim
    if isinstance(dim, str): dim = strToDim(dim)

    if len(result['marginals'][dim]) <= 1:
        print(
            'Error: The parameter you wanted to plot was fixed in the analysis!'
        )
        return
    if axisHandle == None: axisHandle = plt.gca()
    try:
        plt.axes(axisHandle)
        plt.rc('text', usetex=True)
    except TypeError:
        raise ValueError('Invalid axes handle provided to plot in.')
    if not xLabel:
        if dim == 0: xLabel = 'Threshold'
        elif dim == 1: xLabel = 'Width'
        elif dim == 2: xLabel = r'$\lambda$'
        elif dim == 3: xLabel = r'$\gamma$'
        elif dim == 4: xLabel = r'$\eta$'

    x = result['marginalsX'][dim]
    marginal = result['marginals'][dim]
    CI = np.hstack(result['conf_Intervals'][dim].T)
    Fit = result['Fit'][dim]

    holdState = plt.ishold()
    if not holdState: plt.cla()
    plt.hold(True)

    # patch for confidence region
    if CIpatch:
        xCI = np.array([CI[0], CI[1], CI[1], CI[0]])
        xCI = np.insert(xCI, 1, x[np.logical_and(x >= CI[0], x <= CI[1])])
        yCI = np.array([
            np.interp(CI[0], x, marginal),
            np.interp(CI[1], x, marginal), 0, 0
        ])
        yCI = np.insert(yCI, 1,
                        marginal[np.logical_and(x >= CI[0], x <= CI[1])])
        from matplotlib.patches import Polygon as patch
        color = .5 * np.array(lineColor) + .5 * np.array([1, 1, 1])
        axisHandle.add_patch(patch(np.array([xCI, yCI]).T, fc=color, ec=color))

    # plot prior
    if prior:
        xprior = np.linspace(min(x), max(x), 1000)
        plt.plot(xprior,
                 result['options']['priors'][dim](xprior),
                 '--',
                 c=priorColor,
                 clip_on=False)

    # posterior
    plt.plot(x, marginal, lw=lineWidth, c=lineColor, clip_on=False)
    # point estimate
    if plotPE:
        plt.plot([Fit, Fit], [0, np.interp(Fit, x, marginal)],
                 'k',
                 clip_on=False)

    plt.xlabel(xLabel, fontsize=labelSize, visible=True)
    plt.ylabel(yLabel, fontsize=labelSize, visible=True)
    plt.tick_params(direction='out', right='off', top='off')
    for side in ['top', 'right']:
        axisHandle.spines[side].set_visible(False)
    plt.ticklabel_format(style='sci', scilimits=(-2, 4))

    plt.hold(holdState)
    if (showImediate):
        plt.xlim([min(x), max(x)])
        plt.ylim([0, 1.1 * max(marginal)])
        plt.show()
    return axisHandle