Пример #1
0
    def fit(self, output='list', **kw):
        ''' needs scipy.optimize imported as opt
        '''
        # selection of optimizaiton method
        method, options, tol = self.optimization_options(kw)
        # bounds = ((0, None), (0, None), (0, None), (0, 1e3))

        result = opt.minimize(self.chisqfc, self.params, method=method, options=options, tol=tol)  # bounds=bounds
        self.params = np.array(result.x)
        self.results.append(result.x)  # appending results to self.results

        if output == 'list':  # fit will return [params_BM[:], params_d[:]] as a unified list
            return self.params
        elif output == 'split':  # fit will return [[params_BM], [params_d]]
            return parameterSplit(self.params)
        elif output == 'combo':
            split = parameterSplit(self.params)
            return self.params, split[0], split[1]
Пример #2
0
    def chisqfc(self, parameters):
        ''' Calculates the sum of the chisq of all the bands'''
        # preparing inputs
        params_BM, params_d = parameterSplit(parameters)

        chisq_sum = 0
        chisq_log = []
        for index, freq in enumerate(self.freqs):  # iterates through the frequency bands
            # finding the residual
            residual = self.residual(index, freq, params_BM, params_d)
            # finding the error
            d_data = self.measured.d_fitdata[-1][index]
            try:  # checking if d_data exists
                residual/d_data
            except TypeError:  # else assuming 2% error
                d_data = [x/50 for x in self.measured.fitdata[-1][index]]
            # finding the chi-square
            chisq = np.sum((residual/d_data)**2)
            # recording the chi-square
            chisq_log.append(chisq)
            chisq_sum += chisq
        self.chisq.append(np.array(chisq_log))
        return chisq_sum
Пример #3
0
def plotCorrelation(MCData, paramsList, name='MC Parameter Correlations.png'):
    # Finding plot properties
    numParams = len(MCData.params)  # number of parameters
    numRows, numCols = numParams, numParams  # number of columns and rows
    plots_per_row = [numParams-x for x in range(numParams)]  # number of plots per row
    numIterations = len(MCData.results[:, 0])  # number of data points
    if numIterations < 100:  # packaging data points into bins
        binNumber = int(numIterations/10)
    else:
        binNumber = 100

    fig = plt.figure()
    gs = GridSpec(numRows, numCols)
    for row, numPlots in enumerate(plots_per_row):  # rows as indices and number of plots for the columns
        plotStart, plotEnd = row, row+1   # determines the column start and stop point
        for col in range(row, numPlots+row):  # iterates through the parameters
            # making axes
            ax = plt.subplot(gs[row, plotStart:plotEnd])  # placing axes
            plotStart, plotEnd = plotEnd, plotEnd+1  # moving next axes over a column

            # finding x and y data
            xdata = MCData.results[:, row]  # selecting xdata
            ydata = MCData.results[:, col]  # selecting ydata

            # correlation plot
            if row == col:
                histoData = np.histogram(MCData.results[:, row], binNumber)  # *** when MCData packaged by params( not 1 2-D-list) will need different index ***
                histogram  = ax.bar(histoData[1][0:-1], histoData[0], histoData[1][1]-histoData[1][0], label='Hist')
                mean = ax.axvline(x=MCData.params[row], c='g', linestyle='dashed', label='Mean')
                # get right indices
                splitparams = parameterSplit(MCData.params)
                index1, index2 = 0, 0
                for i in range(len(splitparams)):
                    for j in splitparams[i]:
                        if row == (index1+index2):
                            parameter = ax.axvline(x=paramsList[index1][index2], c='r', linestyle='dashed', label='Parameter')
                            plt.title('Parameter {},{}'.format(index1, index2))  # *** FIX THIS ***
                            break
                        index2 += 1
                    index2 = 0
                    index1 += 1
            else:
                correlplot, = ax.plot(xdata, ydata, 'bo', label='correlation')
                # Best Fit Plot
                plotList = np.arange(min(xdata), max(xdata), 0.1)
                fitCoeffs = polyfit(xdata, ydata, 1)
                bestfit, = ax.plot(plotList, [fitCoeffs[0] + fitCoeffs[1]*x for x in plotList], 'r-', label='bestfit')
                # mean plots
                param1mean = ax.axvline(x=np.mean(xdata), c='k', linestyle='dashed', linewidth=1, label='param{} mean: {:.2f}'.format(row, np.mean(xdata)))
                param2mean = ax.axhline(y=np.mean(ydata), c='k', linestyle='dashed', linewidth=1, label='param{} mean: {:.2f}'.format(col+1, np.mean(ydata)))
                plt.title('parameter {},{}'.format(col, row))

            # plot properties
            # plt.xlabel('parameter {}'.format(row+1))
            # plt.ylabel('parameter {}'.format(col+2))
            # handles, labels = ax.get_legend_handles_labels()
            # ax.legend(handles, labels, loc='upper right')
            ax.set_xticklabels([])  # turns off x-tick labels
            ax.set_yticklabels([])  # turns off y-tick labels

    # figure properties
    plt.suptitle("Correlation Plots")
    plt.savefig(name)
    plt.close(fig)
Пример #4
0
    return blackbody_Nu


def blackbody_convert(nu, List, T):
    """ A Plancks Law frequency function to convert the Black Body equation to the right units
        nu,  const = [h, c, k, TVac, TDust]
        TDust=19.6, h=6.62606957*(10**-34), c=299792458, k=1.3806488*(10**-23), TVac = 2.7
        It is the derivative of blackbody_nu
    """
    h, c, k, TVac, TDust = List[:]
    numerator = 2 * (h ** 2) * (nu ** 4) * np.exp((h * nu) / (k * TVac))
    denominator = k * (TVac ** 2) * (c ** 2) * ((np.exp((h * nu) / (k * TVac)) - 1) ** 2)
    return numerator / denominator


##########################################################################################
# Total Signal


def totalSignal((lList, const, frequency, BMode_data), parameters):  # Change name of inputs
    """ Creates the total theoretical signal
    """
    # creating parameter inputs
    params_BM, params_d = parameterSplit(parameters)
    # getting functions
    BMode = BModeSignal(BMode_data, params_BM)
    Dust = dustSignal((lList, const, frequency), params_d)
    # adding into one signal
    signal = np.array(BMode + Dust)
    return signal
Пример #5
0
    return blackbody_Nu


def blackbody_convert(nu, List, T):
    ''' A Plancks Law frequency function to convert the Black Body equation to the right units
        nu,  const = [h, c, k, TVac, TDust]
        TDust=19.6, h=6.62606957*(10**-34), c=299792458, k=1.3806488*(10**-23), TVac = 2.7
    '''
    h, c, k, TVac, TDust = List[:]
    return 2 * (h**2) * (nu**4) * np.exp(
        (h * nu) / (k * TVac)) / (k * (TVac**2) * (c**2) * ((np.exp(
            (h * nu) / (k * TVac)) - 1)**2))


##########################################################################################
# Total Signal


def totalSignal((lList, const, frequency, BMode_data), parameters
                ):  # Change name of inputs
    ''' Creates the total theoretical signal
    '''
    # creating parameter inputs
    params_BM, params_d = parameterSplit(parameters)
    # getting functions
    BMode = BModeSignal(BMode_data, params_BM)
    dust = dustSignal((lList, const, frequency), params_d)
    # adding into one signal
    signal = dust + BMode
    return np.array(signal)
Пример #6
0
def plotCorrelation(MCData, paramsList, name='MC Parameter Correlations.png'):
    # Finding plot properties
    numParams = len(MCData.params)  # number of parameters
    numRows, numCols = numParams, numParams  # number of columns and rows
    plots_per_row = [numParams - x
                     for x in range(numParams)]  # number of plots per row
    numIterations = len(MCData.params_log[:, 0])  # number of data points
    if numIterations < 100:  # packaging data points into bins
        binNumber = int(numIterations / 10)
    else:
        binNumber = 100

    fig = plt.figure()
    gs = GridSpec(numRows, numCols)
    for row, numPlots in enumerate(
            plots_per_row
    ):  # rows as indices and number of plots for the columns
        plotStart, plotEnd = row, row + 1  # determines the column start and stop point
        for col in range(row,
                         numPlots + row):  # iterates through the parameters
            # making axes
            ax = plt.subplot(gs[row, plotStart:plotEnd])  # placing axes
            plotStart, plotEnd = plotEnd, plotEnd + 1  # moving next axes over a column

            # finding x and y data
            xdata = MCData.params_log[:, row]  # selecting xdata
            ydata = MCData.params_log[:, col]  # selecting ydata

            if row == col:  # histogram plot
                histoData = np.histogram(MCData.params_log[:, row], binNumber)
                histogram = ax.bar(histoData[1][0:-1],
                                   histoData[0],
                                   histoData[1][1] - histoData[1][0],
                                   label='Hist')
                mean = ax.axvline(x=MCData.params[row],
                                  c='g',
                                  linestyle='dashed',
                                  label='Mean')
                # get right indices
                splitparams = parameterSplit(MCData.params)
                index1, index2 = 0, 0
                for i in range(len(splitparams)):
                    for j in splitparams[i]:
                        if row == (index1 + index2):
                            parameter = ax.axvline(
                                x=paramsList[index1][index2],
                                c='r',
                                linestyle='dashed',
                                label='Parameter')
                            plt.title('Parameter {},{}'.format(index1, index2),
                                      fontsize=10)  # *** FIX THIS ***
                            break
                        index2 += 1
                    index2 = 0
                    index1 += 1
            else:  # correlation plot
                correlplot, = ax.plot(xdata, ydata, 'bo', label='correlation')
                # Best Fit Plot
                # plotList = np.arange(min(xdata), max(xdata), 0.1)
                # fitCoeffs = polyfit(xdata, ydata, 1)
                # bestfit, = ax.plot(plotList, [fitCoeffs[0] + fitCoeffs[1]*x for x in plotList], 'r-', label='bestfit')
                # mean plots
                param1mean = ax.axvline(x=np.mean(xdata),
                                        c='k',
                                        linestyle='dashed',
                                        linewidth=1,
                                        label='param{} mean: {:.2f}'.format(
                                            row, np.mean(xdata)))
                param2mean = ax.axhline(y=np.mean(ydata),
                                        c='k',
                                        linestyle='dashed',
                                        linewidth=1,
                                        label='param{} mean: {:.2f}'.format(
                                            col + 1, np.mean(ydata)))
                plt.title('parameter {},{}'.format(col, row), fontsize=10)

            # plot properties
            # plt.xlabel('parameter {}'.format(row+1))
            # plt.ylabel('parameter {}'.format(col+2))
            # handles, labels = ax.get_legend_handles_labels()
            # ax.legend(handles, labels, loc='upper right')
            # ax.set_xticklabels([])  # turns off x-tick labels
            plt.setp(ax.get_xticklabels()[::2], visible=False)
            ax.tick_params(axis='x', labelsize=8)
            plt.setp(ax.get_yticklabels()[::2], visible=False)
            ax.tick_params(axis='y', labelsize=8)

    # figure properties
    plt.suptitle("Correlation Plots")
    plt.savefig(name)
    plt.close(fig)