#     curve.append(laplace.pdf(i, loc=location, scale=b))
    #     print(i, ",", curve[-1])

    return curve_x, curve_y


if __name__ == '__main__':

    # Experiment config
    period1 = 33.33
    period2 = 100
    j = 16
    delta = 190
    epsilon = 100

    PlotUtility.config_plot(plt)
    plt.rcParams['figure.figsize'] = 6, 4
    fig, ax = plt.subplots()

    curve1_x, curve1_y = get_epsilon_scheduler_noise_distribution_curve(
        location=period1, epsilon=epsilon, j=j, delta=delta)
    curve2_x, curve2_y = get_epsilon_scheduler_noise_distribution_curve(
        location=period2, epsilon=epsilon, j=j, delta=delta)
    ylim = max(max(curve1_y), max(curve2_y)) * 1.1

    ax.plot(curve1_x,
            curve1_y,
            color=PlotUtility.palletForMany[0],
            linestyle=PlotUtility.line_style_list[0],
            linewidth=2,
            label='$33.3ms$')
def plot_peak_count(show_plot, in_csv_file_list, out_plot_file_list,
                    label_list):
    ''' general plot configurations '''
    PlotUtility.config_plot(plt)
    # plt.rcParams['figure.figsize'] = 8,5.5
    plt.rcParams['figure.figsize'] = 6.5, 5

    plot_labels = [] if label_list is None else label_list
    ''' Data '''
    x_list = []
    y_list = []
    y_mean_list = []
    y_error_list = []
    x_mean = []
    first = True
    for csv_file in in_csv_file_list:
        data_dict = np.genfromtxt(csv_file,
                                  delimiter=',',
                                  unpack=True,
                                  names=True)

        if first:
            first = False
            base_context_switches = data_dict['Context_Switches']
            continue

        # if first:
        #     x = data_dict['Utilization']
        #     first = False

        this_x = data_dict['Utilization']
        x_list.append(this_x)

        this_y = data_dict['Context_Switches'] / base_context_switches
        y_list.append(this_y)

        x_mean = []
        y_mean = []
        y_error = []
        for u in range(10):
            util = u / 10
            matched_values = np.array([])
            for i in range(len(this_y)):
                if util <= this_x[i] < (util + 0.1):
                    matched_values = np.append(matched_values, this_y[i])
            x_mean.append(u / 10 + 0.05)
            y_mean.append(matched_values.mean())
            y_error.append(matched_values.std())

        y_mean_list.append(y_mean)
        y_error_list.append(y_error)

    # plot general config
    # plt.title('Interesting Graph\nCheck it out')
    # plt.legend()
    # plt.grid(True, 'major', 'both', color='0.8', linestyle='--', linewidth=1)

    # x axis config
    plt.xlabel('Task Set Utilization')
    plt.xlim(0, 1)
    plt.xticks([i / 10 for i in range(0, 11, 1)])

    # y axis config
    plt.ylabel(
        'Ratio of the Number of Context Switches\nby the Corresponding Schedulers\nto that by Vanilla EDF'
    )
    # ylimMax = (max(y)/5+1)*5

    # ylimMax = math.ceil(max(y))
    # plt.ylim([0.8, ylimMax])
    # plt.yticks([i*0.5 for i in range(2, (int(ylimMax))*2, 1)])

    # plt.ylim(0, 1.1)
    # plt.yticks([i/10 for i in range(1, 11, 1)])

    # plt.grid(True, 'major', 'y', color='0.8', linestyle='--', linewidth=1)
    # plt.grid(True, 'major', 'x', color='0.8', linestyle='--', linewidth=1)

    # minor_ticks = [tmp / 10 for tmp in range(0, 11)]
    # plt.axes().set_yticks(minor_ticks, minor=True)

    # data points
    markerSize = 30
    for i in range(len(y_list)):
        style_idx = i + 1
        y = y_list[i]
        x = x_list[i]
        y_mean = y_mean_list[i]
        y_error = y_error_list[i]
        plt.scatter(x,
                    y,
                    marker=PlotUtility.pattern_list[style_idx],
                    facecolors=PlotUtility.palletForMany[style_idx],
                    color=PlotUtility.palletForMany[style_idx],
                    alpha=0.5,
                    s=[markerSize for i in range(len(y))],
                    label=plot_labels[i])
        plt.errorbar(x_mean,
                     y_mean,
                     y_error,
                     color="black",
                     marker=PlotUtility.pattern_list[style_idx],
                     linewidth=1)

    # Post plot configurations
    legend = plt.legend(shadow=False)
    legend.get_frame().set_edgecolor('grey')
    ''' Save the plot to files with the specified format '''
    for outFileName in out_plot_file_list:
        print("Exporting the plot ...")

        # if outFileName == "png" or outFileName == "pdf":
        #     outFileName = "{}.{}".format(inFileName.split('.')[0], outFileName)

        outputFormat = outFileName.split('.')[-1]
        if outputFormat == "pdf" or outputFormat == "png" or True:
            print('Saving the plot to "{}" ...'.format(outFileName), end=" ")
            plt.savefig(outFileName, pad_inches=0.02, bbox_inches='tight')
            print("Done")

    if show_plot:
        plt.show()
Exemple #3
0
def plot_single_dft_of_stft(show_plot, in_csv_file_list, out_plot_file_list, label_list):

    ### general plot configurations ###
    PlotUtility.config_plot(plt)
    plt.rcParams['figure.figsize'] = 7, 2.5


    # Load .rtstft json
    print("Parsing the json file ...", end =" ")
    try:
        jsonRoot = json.load(open(in_csv_file_list[0], 'r'))
        print("Done")
    except:
        print("Failed to load the rtstft file: {}".format(in_csv_file_list[0]))
        exit()

    # Load task set
    print("Loading the task set ...", end =" ")
    taskSet = LogLoader.loadSingleTaskSetFromJsonObject(jsonRoot)
    print("Done")
    print(taskSet.toString())

    # Time unit
    nsPerTick = jsonRoot['data']['tickUnitInNs']
    tickToMsMultiplier = nsPerTick/1000_000_000

    # How many time bins (x-axis size)?
    lenTimeBins = len(jsonRoot['data']['unevenSpectrum'])
    dftIndx = lenTimeBins-1

    # Extract time bin labels
    timeBinLabels = []
    spectrumData = {}

    xFreq = jsonRoot['data']['unevenSpectrum'][dftIndx]['frequencies']



    # idx_of_freq_upper_limit = findIndexOfFrequency(jsonRoot['data']['unevenSpectrum'][i]['frequencies'],freq_upper_limit)
    # true_top_freq = jsonRoot['data']['unevenSpectrum'][i]['frequencies'][idx_of_freq_upper_limit]
    # print(true_top_freq, idx_of_freq_upper_limit)

    # axx = ax.inset_axes([i * heatmapWidth, 0, heatmapWidth, true_top_freq / freq_upper_limit])
    df = pd.DataFrame(jsonRoot['data']['unevenSpectrum'][dftIndx]['magnitudes'])
    df_max_min_range = 1 if (df.max() - df.min()).max() == 0 else (df.max() - df.min())  # in case if divisor is zero
    yMag = (df - df.min()) / (df_max_min_range)  # min-max normalization
    # yMag = df
    # sns.heatmap(df, cmap='Blues', cbar_kws={'label': 'Amplitude', 'aspect': 0.01}, ax=axx, cbar_ax=ax_cbar)
    # axx.tick_params(top=False, bottom=False, left=False, right=False, labelleft=False, labelbottom=False)
    # axx.set_ylim(-1, idx_of_freq_upper_limit + 1)





    ax = plt.subplot(111)

    # X-axis Settings
    plt.xlabel('Frequency (Hz)')

    # Set X-axis limit based on the largest frequency of all tasks
    X_AXIS_FREQ_LIMIT = 100*(int(taskSet.getLargestFreq()/100)+1)

    X_AXIS_TICK_INTERVAL = 10
    #ax.set_xticks(major_ticks)

    ax.xaxis.set_major_locator(ticker.MultipleLocator(X_AXIS_TICK_INTERVAL))
    ax.set_xlim(0, X_AXIS_FREQ_LIMIT)


    # Y-axis Settings
    ax.set_ylabel(ylabel='Magnitude \n(Normalized)')

    yaxis_limit = 1 # normalized # maxAmplitude if not normalized
    ax.set_ylim([0, yaxis_limit])

    ax.yaxis.labelpad = 3
    ax.xaxis.labelpad = 3

    # get X and Y axis values (trimmed to the desired display range) to be displayed
    # X
    xFreq_limitIndx = findIndexOfFrequency(xFreq, X_AXIS_FREQ_LIMIT)
    displayedFreq = xFreq[:xFreq_limitIndx]
    # Y
    maxAmplitude = max(yMag[:xFreq_limitIndx])
    # displayedAmplitude = [amp / maxAmplitude for amp in yMag[:xFreq_limitIndx]] # Normalized
    displayedAmplitude = yMag[:xFreq_limitIndx]

    # sns.heatmap(yMag, cmap='Blues', cbar_kws={'label': 'Amplitude'}, ax=ax)

    plt.plot(displayedFreq, displayedAmplitude, color='navy', alpha=0.75, linewidth=1.5)
    plt.grid(linestyle=':')

    '''Add ground truth lines'''
    if taskSet is not None:
        for task in taskSet.tasks:
            plt.plot([task.frequency, task.frequency], [0, yaxis_limit], color='maroon', alpha=0.8, linestyle='--', linewidth=1.5)
            ax.arrow(task.frequency, 1, 0, -0.05, head_width=3, head_length=0.03, color='maroon')


    ''' Save the plot to files with the specified format '''
    for outFileName in out_plot_file_list:
        print("Exporting the plot ...")

        # if outFileName == "png" or outFileName == "pdf":
        #     outFileName = "{}.{}".format(inFileName.split('.')[0], outFileName)

        outputFormat = outFileName.split('.')[-1]
        if outputFormat == "pdf" or outputFormat == "png" or True:
            print('Saving the plot to "{}" ...'.format(outFileName), end=" ")
            plt.savefig(outFileName, pad_inches=0.02, bbox_inches='tight')
            print("Done")


    if show_plot:
        plt.show()
        print("Exporting the plot ...")

        # if outFileName == "png" or outFileName == "pdf":
        #     outFileName = "{}.{}".format(inFileName.split('.')[0], outFileName)

        outputFormat = outFileName.split('.')[-1]
        if outputFormat == "pdf" or outputFormat == "png" or True:
            print('Saving the plot to "{}" ...'.format(outFileName), end=" ")
            plt.savefig(outFileName, pad_inches=0.02, bbox_inches='tight')
            print("Done")

    if show_plot:
        plt.show()


if __name__ == '__main__':

    # out_plot_file_list = []
    # csv_file_list = [
    #     '/Users/jjs/Documents/myProject/RTS-Schedule-Simulator/experiments/test_cases/laplace_scheduler/dft_variance/edf-d20000_dftDuration.csv',
    #     '/Users/jjs/Documents/myProject/RTS-Schedule-Simulator/experiments/test_cases/laplace_scheduler/dft_variance/laplace-e1000-d20000_dftDuration.csv',
    #     '/Users/jjs/Documents/myProject/RTS-Schedule-Simulator/experiments/test_cases/laplace_scheduler/dft_variance/laplace-e10-d20000_dftDuration.csv',
    #     # '/Users/jjs/Documents/myProject/RTS-Schedule-Simulator/experiments/test_cases/laplace_scheduler/dft_variance/laplace-e1-d20000_dftDuration.csv'
    # ]
    # label_list = ["EDF", "$\epsilon-Scheduler=1000$", "$\epsilon-Scheduler=10$"]
    # show_plot = True

    show_plot, csv_file_list, out_plot_file_list, label_list = PlotUtility.parse_arguments(
    )

    plot_peak_count(show_plot, csv_file_list, out_plot_file_list, label_list)
def plot_noise_range(show_plot, in_csv_file_list, out_plot_file_list, label_list):
    percentile = 0.95
    delta = 190 # 10 ms
    j_list = [1, 10, 50, 100]

    # Build epsilon list
    epsilon_list = []
    # [0.01, 0.1)
    epsilon_list.extend([i/100 for i in range(1, 10)])
    # [0.1, 1)
    epsilon_list.extend([i/10 for i in range(1, 10)])
    # [1, 1000]
    epsilon_list.extend([i for i in range(1, 1000)])
    # epsilon_list.extned([pow(10, i) for i in range(-2, 5, 1)])

    noise_level_list = []
    for i in range(len(j_list)):
        noise_level_list.append([compute_noise_level_percentile(epsilon, j_list[i], delta, percentile) for epsilon in epsilon_list])


    ### general plot configurations ###
    PlotUtility.config_plot(plt)
    plt.rcParams['figure.figsize'] = 5.5,4.5
    fig, ax = plt.subplots()


    # ax.set_xscale("log")
    plt.xscale('log')
    plt.yscale('log')


    for i in range(len(j_list)):
        plt.plot(epsilon_list, noise_level_list[i], label=j_list[i], linewidth=2, linestyle=PlotUtility.line_style_list[i])


    # Post plot configurations

    # Legend
    legend = plt.legend(shadow=True, loc='lower left', title='$J_i$')
    legend.get_frame().set_edgecolor('grey')

    # Axis Titles
    plt.ylabel('Noise Scale at '+str(100*percentile)[:-2]+'$^{th}$ Percentile ($ms$)')
    plt.xlabel('$\epsilon_i$')

    plt.xlim(0, max(epsilon_list)+1)
    plt.ylim(0, 100000)
    # plt.ylim(bottom=0)

    # Grid
    plt.grid(True, 'major', 'y', color='0.8', linestyle='--', linewidth=1)
    plt.grid(True, 'major', 'x', color='0.8', linestyle='--', linewidth=1)

    title = "$\Delta\eta_i={}$".format(delta)
    ax.text(0.98, 0.98, title, transform=ax.transAxes, fontsize=14,
            verticalalignment='top', horizontalalignment='right')



    ''' Save the plot to files with the specified format '''
    for outFileName in out_plot_file_list:
        print("Exporting the plot ...")

        # if outFileName == "png" or outFileName == "pdf":
        #     outFileName = "{}.{}".format(inFileName.split('.')[0], outFileName)

        outputFormat = outFileName.split('.')[-1]
        if outputFormat == "pdf" or outputFormat == "png" or True:
            print('Saving the plot to "{}" ...'.format(outFileName), end=" ")
            plt.savefig(outFileName, pad_inches=0.02, bbox_inches='tight')
            print("Done")


    if show_plot:
        plt.show()
def plot_peak_count(show_plot, in_csv_file_list, out_plot_file_list,
                    label_list):
    ''' general plot configurations '''
    PlotUtility.config_plot(plt)
    # plt.rcParams['figure.figsize'] = 8,5.5
    plt.rcParams['figure.figsize'] = 6.5, 5.5

    AX = gridspec.GridSpec(6, 1)
    AX.update(wspace=0.3, hspace=0.15)

    ax_top = plt.subplot(AX[0, 0])
    ax = plt.subplot(AX[1:, 0])

    plot_labels = [] if label_list is None else label_list
    ''' Data '''
    y_list = []
    y_mean_list = []
    y_error_list = []
    x_mean = []
    first = True
    for csv_file in in_csv_file_list:
        data_dict = np.genfromtxt(csv_file,
                                  delimiter=',',
                                  unpack=True,
                                  names=True)
        if first:
            x = data_dict['Utilization']
            first = False
        this_y = data_dict['ZScore_Based_Peak_Count']
        y_list.append(this_y)

        x_mean = []
        y_mean = []
        y_error = []
        for u in range(10):
            util = u / 10
            matched_values = np.array([])
            for i in range(len(this_y)):
                if x[i] >= util and x[i] < (util + 0.1):
                    matched_values = np.append(matched_values, this_y[i])
            x_mean.append(u / 10 + 0.05)
            y_mean.append(matched_values.mean())
            y_error.append(matched_values.std())

        y_mean_list.append(y_mean)
        y_error_list.append(y_error)
    ''' Deadline Miss Ratio (only for the last CSV) '''
    data_dict = np.genfromtxt(in_csv_file_list[-1],
                              delimiter=',',
                              unpack=True,
                              names=True)
    x_deadline_miss_ratio = data_dict['Utilization']
    y_deadline_miss_ratio = data_dict['Deadline_Miss_Ratio']
    tasksets_with_deadline_misses_count = []
    for i in range(10):
        tasksets_with_deadline_misses_count.append(0)
        for j in range(len(x_deadline_miss_ratio)):
            if i / 10 <= x_deadline_miss_ratio[j] < (i + 1) / 10:
                if y_deadline_miss_ratio[j] > 0.0:
                    tasksets_with_deadline_misses_count[i] += 1
        # print(tasksets_with_deadline_misses_count[-1])

    # plot general config
    # plt.title('Interesting Graph\nCheck it out')
    # plt.legend()
    # plt.grid(True, 'major', 'both', color='0.8', linestyle='--', linewidth=1)

    # x axis config
    plt.xlabel('Task Set Utilization')
    plt.xlim(0, 1)
    plt.xticks([i / 10 for i in range(0, 11, 1)])

    # y axis config
    plt.ylabel('Outstanding Peak Count')
    # ylimMax = (max(y)/5+1)*5

    # ylimMax = math.ceil(max(y))
    # plt.ylim([0.8, ylimMax])
    # plt.yticks([i*0.5 for i in range(2, (int(ylimMax))*2, 1)])

    # plt.ylim(0, 1.1)
    # plt.yticks([i/10 for i in range(1, 11, 1)])

    # plt.grid(True, 'major', 'y', color='0.8', linestyle='--', linewidth=1)
    # plt.grid(True, 'major', 'x', color='0.8', linestyle='--', linewidth=1)

    # minor_ticks = [tmp / 10 for tmp in range(0, 11)]
    # plt.axes().set_yticks(minor_ticks, minor=True)

    # data points
    markerSize = 30
    for i in range(len(y_list)):
        y = y_list[i]
        y_mean = y_mean_list[i]
        y_error = y_error_list[i]
        ax.scatter(x,
                   y,
                   marker=PlotUtility.pattern_list[i],
                   facecolors=PlotUtility.palletForMany[i],
                   color=PlotUtility.palletForMany[i],
                   alpha=0.5,
                   s=[markerSize for i in range(len(y))],
                   label=plot_labels[i])
        ax.errorbar(x_mean,
                    y_mean,
                    y_error,
                    color="black",
                    marker=PlotUtility.pattern_list[i],
                    linewidth=1)

    ax_top.set_xlim(-0.5, 9.5)
    # ax_top_ytop = math.ceil(max(y_deadline_miss_ratio)/0.1)*0.1
    ax_top_ytop = math.ceil(max(tasksets_with_deadline_misses_count) / 50) * 50
    # # ax_top.set_ylim(0, max(y_deadline_miss_ratio))
    ax_top.set_ylim(0, ax_top_ytop)
    # ax_top.get_yaxis().set_major_locator(ticker.LinearLocator(numticks=(ax_top_ytop/0.1)+1))
    ax_top.get_yaxis().set_major_locator(
        ticker.LinearLocator(numticks=(ax_top_ytop / 50) + 1))
    ax_top.yaxis.tick_right()
    ax_top.tick_params(top=False,
                       bottom=False,
                       left=False,
                       right=True,
                       labelleft=False,
                       labelbottom=False,
                       labeltop=False,
                       labelright=False,
                       direction='in')
    ax_top.spines["left"].set_visible(False)
    ax_top.spines["top"].set_visible(False)
    # ax_top.scatter(x_deadline_miss_ratio, y_deadline_miss_ratio, marker='o', facecolors='grey', color='grey', alpha=0.5, s=[5 for i in range(len(y_deadline_miss_ratio))],)

    # ax_top.bar(range(10), tasksets_with_deadline_misses_count)
    ax_top.plot(range(10),
                tasksets_with_deadline_misses_count,
                marker=PlotUtility.pattern_list[len(csv_file_list) - 1],
                markersize=10,
                color='black')
    ax_top.text(
        0,
        1.1,
        "The Number of Task Sets\nthat Have Deadline Misses\nin {}".format(
            label_list[-1]),
        transform=ax_top.transAxes,
        fontsize=14,
        verticalalignment='top',
        horizontalalignment='left')

    for i in range(10):
        if tasksets_with_deadline_misses_count[i] > 0:
            ax_top.text(i,
                        tasksets_with_deadline_misses_count[i] + 10,
                        '$\\frac{' +
                        str(tasksets_with_deadline_misses_count[i]) +
                        '}{600}$',
                        fontsize=12,
                        ha='center',
                        va='bottom')

    # Post plot configurations
    legend = plt.legend(shadow=False, loc='upper right')
    legend.get_frame().set_edgecolor('grey')
    ''' Save the plot to files with the specified format '''
    for outFileName in out_plot_file_list:
        print("Exporting the plot ...")

        # if outFileName == "png" or outFileName == "pdf":
        #     outFileName = "{}.{}".format(inFileName.split('.')[0], outFileName)

        outputFormat = outFileName.split('.')[-1]
        if outputFormat == "pdf" or outputFormat == "png" or True:
            print('Saving the plot to "{}" ...'.format(outFileName), end=" ")
            plt.savefig(outFileName, pad_inches=0.02, bbox_inches='tight')
            print("Done")

    if show_plot:
        plt.show()
Exemple #7
0
def plot_execution_range_ratio(show_plot, in_csv_file_list, out_plot_file_list,
                               label_list):
    ''' general plot configurations '''
    PlotUtility.config_plot(plt)
    plt.rcParams['figure.figsize'] = 8, 5.5

    # change font to Arial
    plt.rcParams["font.family"] = "Arial"
    plt.rcParams['font.size'] = 22
    plt.rcParams['legend.fontsize'] = 13
    plt.rcParams['axes.titlesize'] = 15
    plt.rcParams['ytick.labelsize'] = 20
    plt.rcParams['xtick.labelsize'] = 20
    plt.rcParams["legend.edgecolor"] = 'black'

    plot_labels = [] if label_list is None else label_list
    ''' Data '''
    data_dict1 = np.genfromtxt(in_csv_file_list[0],
                               delimiter=',',
                               unpack=True,
                               names=True)
    data_dict2 = np.genfromtxt(in_csv_file_list[1],
                               delimiter=',',
                               unpack=True,
                               names=True)
    x = data_dict1['Utilization']
    y1 = data_dict1['Mean_Execution_Range_Ratio_To_Period']
    y2 = data_dict2['Mean_Execution_Range_Ratio_To_Period']

    # plot general config
    # plt.title('Interesting Graph\nCheck it out')
    # plt.legend()
    # plt.grid(True, 'major', 'both', color='0.8', linestyle='--', linewidth=1)

    # x axis config
    plt.xlabel('Task Set Utilization')
    plt.xlim(0, 1)
    plt.xticks([i / 10 for i in range(0, 11, 1)])

    # y axis config
    plt.ylabel('Mean Ratio of Task \n Execution Range to Period')
    # ylimMax = (max(y)/5+1)*5
    # plt.ylim([0, ylimMax])
    # plt.yticks([i for i in range(0, int(ylimMax)+1, 2)])
    plt.ylim(0, 1.1)
    plt.yticks([i / 10 for i in range(1, 11, 1)])

    # plt.grid(True, 'major', 'y', color='0.8', linestyle='--', linewidth=1)
    # plt.grid(True, 'major', 'x', color='0.8', linestyle='--', linewidth=1)

    # minor_ticks = [tmp / 10 for tmp in range(0, 11)]
    # plt.axes().set_yticks(minor_ticks, minor=True)

    # data points
    markerSize = 30
    plt.scatter(x,
                y1,
                marker='+',
                color='grey',
                alpha=0.5,
                s=[markerSize for i in range(len(y1))],
                label=plot_labels[0])
    plt.scatter(x,
                y2,
                marker='x',
                color='DodgerBlue',
                alpha=0.5,
                s=[markerSize for i in range(len(y2))],
                label=plot_labels[1])
    # plt.scatter(x, y1, marker='o', facecolors='none', color='grey', alpha=0.5, s=[markerSize for i in range(len(y1))], label=plot_labels[0])
    # plt.scatter(x, y2, marker='o', facecolors='none', color='DodgerBlue', alpha=0.5, s=[markerSize for i in range(len(y2))], label=plot_labels[1])

    # Post plot configurations
    legend = plt.legend(shadow=False, loc='upper right')
    legend.get_frame().set_edgecolor('grey')
    ''' Save the plot to files with the specified format '''
    for outFileName in out_plot_file_list:
        print("Exporting the plot ...")

        # if outFileName == "png" or outFileName == "pdf":
        #     outFileName = "{}.{}".format(inFileName.split('.')[0], outFileName)

        outputFormat = outFileName.split('.')[-1]
        if outputFormat == "pdf" or outputFormat == "png" or True:
            print('Saving the plot to "{}" ...'.format(outFileName), end=" ")
            plt.savefig(outFileName, pad_inches=0.02, bbox_inches='tight')
            print("Done")

    if show_plot:
        plt.show()
Exemple #8
0
def plot_context_switch_increase_ratio(show_plot, in_csv_file_list,
                                       out_plot_file_list, label_list):
    ''' general plot configurations '''
    PlotUtility.config_plot(plt)
    plt.rcParams['figure.figsize'] = 8, 5.5

    # change font to Arial
    plt.rcParams["font.family"] = "Arial"
    plt.rcParams['font.size'] = 22
    plt.rcParams['legend.fontsize'] = 13
    plt.rcParams['axes.titlesize'] = 15
    plt.rcParams['ytick.labelsize'] = 20
    plt.rcParams['xtick.labelsize'] = 20
    plt.rcParams["legend.edgecolor"] = 'black'

    plot_labels = [] if label_list is None else label_list
    ''' Data '''
    data_dict1 = np.genfromtxt(in_csv_file_list[0],
                               delimiter=',',
                               unpack=True,
                               names=True)
    data_dict2 = np.genfromtxt(in_csv_file_list[1],
                               delimiter=',',
                               unpack=True,
                               names=True)
    x = data_dict1['Utilization']
    y = data_dict2['Context_Switches'] / data_dict1[
        'Context_Switches']  # context switch ratio

    x_mean = []
    y_mean = []
    y_error = []
    for u in range(10):
        util = u / 10
        matched_values = np.array([])
        for i in range(len(y)):
            if x[i] >= util and x[i] < (util + 0.1):
                matched_values = np.append(matched_values, y[i])
        x_mean.append(u / 10 + 0.05)
        y_mean.append(matched_values.mean())
        y_error.append(matched_values.std())

    # plot general config
    # plt.title('Interesting Graph\nCheck it out')
    # plt.legend()
    # plt.grid(True, 'major', 'both', color='0.8', linestyle='--', linewidth=1)

    # x axis config
    plt.xlabel('Task Set Utilization')
    plt.xlim(0, 1)
    plt.xticks([i / 10 for i in range(0, 11, 1)])

    # y axis config
    plt.ylabel('Context Switch Ratio \n (TaskShuffler/RM)')
    # ylimMax = (max(y)/5+1)*5
    ylimMax = math.ceil(max(y))
    plt.ylim([0.8, ylimMax])
    plt.yticks([i * 0.5 for i in range(2, (int(ylimMax)) * 2, 1)])
    # plt.ylim(0, 1.1)
    # plt.yticks([i/10 for i in range(1, 11, 1)])

    # plt.grid(True, 'major', 'y', color='0.8', linestyle='--', linewidth=1)
    # plt.grid(True, 'major', 'x', color='0.8', linestyle='--', linewidth=1)

    # minor_ticks = [tmp / 10 for tmp in range(0, 11)]
    # plt.axes().set_yticks(minor_ticks, minor=True)

    # data points
    markerSize = 30
    plt.scatter(x,
                y,
                marker='o',
                facecolors='none',
                color='DodgerBlue',
                alpha=0.7,
                s=[markerSize for i in range(len(y))])

    plt.errorbar(x_mean, y_mean, y_error, color="black", marker='o')

    # Post plot configurations
    # legend = plt.legend(shadow=False, loc='upper right')
    # legend.get_frame().set_edgecolor('grey')
    ''' Save the plot to files with the specified format '''
    for outFileName in out_plot_file_list:
        print("Exporting the plot ...")

        # if outFileName == "png" or outFileName == "pdf":
        #     outFileName = "{}.{}".format(inFileName.split('.')[0], outFileName)

        outputFormat = outFileName.split('.')[-1]
        if outputFormat == "pdf" or outputFormat == "png" or True:
            print('Saving the plot to "{}" ...'.format(outFileName), end=" ")
            plt.savefig(outFileName, pad_inches=0.02, bbox_inches='tight')
            print("Done")

    if show_plot:
        plt.show()