Example #1
0
    def test_replace_dict_values(self):
        name = "something {value1} - {value2} something else {value3}"
        dictionary = {
            'value1': 'bla bla',
            'value2': np.array([15]),
            'value3': 76
        }
        new_name = misc.replace_dict_values(name, dictionary)
        expected_new_name = 'something bla bla - [15] something else 76'
        self.assertEqual(new_name, expected_new_name)

        name = "something {value1} - {value2} something else {value3}"
        dictionary = {
            'value1': 'bla bla',
            'value2': np.array([5, 10, 15, 20, 25, 30]),
            'value3': 76
        }
        new_name = misc.replace_dict_values(name, dictionary, True)
        expected_new_name = 'something bla bla - [5_(5)_30] something else 76'
        self.assertEqual(new_name, expected_new_name)

        # Value2 is not an arithmetic progression
        dictionary2 = {
            'value1': 'bla bla',
            'value2': np.array([5, 10, 18, 20, 25, 30]),
            'value3': 76
        }
        new_name2 = misc.replace_dict_values(name, dictionary2)
        expected_new_name2 \
            = 'something bla bla - [5,10,18,20,25,30] something else 76'
        self.assertEqual(new_name2, expected_new_name2)

        # Value3 has parts that are arithmetic progressions and others that
        # are not an arithmetic progression
        dictionary3 = {
            'value1': 'bla bla',
            'value2': np.array([2, 5, 10, 15, 20, 25, 30, 31, 32, 50]),
            'value3': 76
        }
        new_name3 = misc.replace_dict_values(name, dictionary3, True)
        expected_new_name3 \
            = 'something bla bla - [2,5_(5)_30,31,32,50] something else 76'
        self.assertEqual(new_name3, expected_new_name3)

        # Now we test the same thing, but with the third parameter being False
        new_name4 = misc.replace_dict_values(name, dictionary3, False)
        expected_new_name4 \
            = 'something bla bla - [2,5:5:30,31,32,50] something else 76'
        self.assertEqual(new_name4, expected_new_name4)
Example #2
0
def main():
    """Main function of the script.
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('first',
                        help="The name of the first SimulationResults file.")
    parser.add_argument('second',
                        help="The name of the second SimulationResults file.")
    parser.add_argument('output',
                        help=("The name that will be used to save the combined "
                              "SimulationResults file."),
                        nargs='?')

    args = parser.parse_args()

    first = SimulationResults.load_from_file(args.first)
    second = SimulationResults.load_from_file(args.second)
    union = combine_simulation_results(first, second)

    if args.output is None:
        output = replace_dict_values(first.original_filename,
                                     union.params.parameters,
                                     filename_mode=True)
    else:
        output = args.output

    if output == args.first or output == args.second:
        raise RuntimeError(
            "output filename must be different from the filename of either"
            " of the two SimulationResults.")

    # Finally save to the output file
    union.save_to_file(output)
Example #3
0
def main():
    """Main function of the script.
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('first',
                        help="The name of the first SimulationResults file.")
    parser.add_argument('second',
                        help="The name of the second SimulationResults file.")
    parser.add_argument(
        'output',
        help=("The name that will be used to save the combined "
              "SimulationResults file."),
        nargs='?')

    args = parser.parse_args()

    first = SimulationResults.load_from_file(args.first)
    second = SimulationResults.load_from_file(args.second)
    union = combine_simulation_results(first, second)

    if args.output is None:
        output = replace_dict_values(first.original_filename,
                                     union.params.parameters,
                                     filename_mode=True)
    else:
        output = args.output

    if output == args.first or output == args.second:
        raise RuntimeError(
            "output filename must be different from the filename of either"
            " of the two SimulationResults.")

    # Finally save to the output file
    union.save_to_file(output)
Example #4
0
def main():
    """Main function of the script.
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('name', help="The name of the SimulationResults file.")
    parser.add_argument('folder',
                        help="The name of the second SimulationResults file.",
                        nargs='?')

    args = parser.parse_args()

    name = args.name
    folder = args.folder  # This will be None, if not provided

    results = SimulationResults.load_from_file(name)

    original_filename = results.original_filename

    # xxxxxxxxxx Remove the .pickle file extension xxxxxxxxxxxxxxxxxxxxxxxx
    # If partial_filename has a 'pickle' extension we remove it from the name
    original_filename_no_ext, ext = os.path.splitext(original_filename)
    if ext == '.pickle':
        original_filename = original_filename_no_ext
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    unpacked_params_list = results.params.get_unpacked_params_list()
    all_results_names = results.get_result_names()

    for i, p in enumerate(results.params.get_unpacked_params_list()):
        partial_filename = get_partial_results_filename(
            original_filename, p, folder)
        partial_filename_with_replacements = replace_dict_values(
            partial_filename, results.params.parameters, filename_mode=True)

        if partial_filename_with_replacements == name:
            raise RuntimeError('invalid name')

        partial_param = unpacked_params_list[i]
        partial_result = SimulationResults()
        partial_result.set_parameters(partial_param)

        for result_name in all_results_names:
            partial_result.add_result(results[result_name][i])

        partial_result.current_rep = results.runned_reps[i]

        # Try to save the partial results. If we get an error
        try:
            # If we get an IOError exception here, maybe we are trying to
            # save to a folder and the folder does not exist yet.
            partial_result.save_to_file(partial_filename_with_replacements)
        except IOError as e:
            if folder is not None:
                # Lets create the folder...
                os.mkdir(folder)
                # ... and try to save the file again.
                partial_result.save_to_file(partial_filename_with_replacements)
            else:
                raise e
Example #5
0
    def test_replace_dict_values(self):
        name = "something {value1} - {value2} something else {value3}"
        dictionary = {'value1': 'bla bla',
                      'value2': np.array([15]),
                      'value3': 76}
        new_name = misc.replace_dict_values(name, dictionary)
        expected_new_name = 'something bla bla - [15] something else 76'
        self.assertEqual(new_name, expected_new_name)

        name = "something {value1} - {value2} something else {value3}"
        dictionary = {'value1': 'bla bla',
                      'value2': np.array([5, 10, 15, 20, 25, 30]),
                      'value3': 76}
        new_name = misc.replace_dict_values(name, dictionary, True)
        expected_new_name = 'something bla bla - [5_(5)_30] something else 76'
        self.assertEqual(new_name, expected_new_name)

        # Value2 is not an arithmetic progression
        dictionary2 = {'value1': 'bla bla',
                       'value2': np.array([5, 10, 18, 20, 25, 30]),
                       'value3': 76}
        new_name2 = misc.replace_dict_values(name, dictionary2)
        expected_new_name2 \
            = 'something bla bla - [5,10,18,20,25,30] something else 76'
        self.assertEqual(new_name2, expected_new_name2)

        # Value3 has parts that are arithmetic progressions and others that
        # are not an arithmetic progression
        dictionary3 = {'value1': 'bla bla',
                       'value2': np.array([2, 5, 10, 15, 20, 25,
                                           30, 31, 32, 50]),
                       'value3': 76}
        new_name3 = misc.replace_dict_values(name, dictionary3, True)
        expected_new_name3 \
            = 'something bla bla - [2,5_(5)_30,31,32,50] something else 76'
        self.assertEqual(new_name3, expected_new_name3)

        # Now we test the same thing, but with the third parameter being False
        new_name4 = misc.replace_dict_values(name, dictionary3, False)
        expected_new_name4 \
            = 'something bla bla - [2,5:5:30,31,32,50] something else 76'
        self.assertEqual(new_name4, expected_new_name4)
Example #6
0
def get_result_from_file():
    """
    Load the SimulationResults object from the file and return it.
    """
    config_file = 'greedy_config_file.txt'

    # xxxxxxxxxx Config spec for the config file xxxxxxxxxxxxxxxxxxxxxxxxxx
    spec = """[Grid]
        cell_radius=float(min=0.01, default=1.0)
        num_cells=integer(min=3,default=3)
        num_clusters=integer(min=1,default=1)
        [Scenario]
        NSymbs=integer(min=10, max=1000000, default=200)
        SNR=real_numpy_array(min=-50, max=100, default=0:5:31)
        M=integer(min=4, max=512, default=4)
        modulator=option('QPSK', 'PSK', 'QAM', 'BPSK', default="PSK")
        Nr=integer_scalar_or_integer_numpy_array_check(min=2,default=3)
        Nt=integer_scalar_or_integer_numpy_array_check(min=2,default=3)
        Ns=integer_scalar_or_integer_numpy_array_check(min=1,default=3)
        N0=float(default=-116.4)
        scenario=string_list(default=list('Random', 'NoPathLoss'))
        [IA Algorithm]
        max_iterations=integer(min=1, default=120)
        initialize_with=string_list(default=list('random'))
        stream_sel_method=string_list(default=list('greedy', 'brute'))
        [General]
        rep_max=integer(min=1, default=2000)
        max_bit_errors=integer(min=1, default=3000)
        unpacked_parameters=string_list(default=list('SNR','stream_sel_method','scenario','initialize_with'))
        """.split("\n")

    params = SimulationParameters.load_from_config_file(config_file, spec)

    # xxxxx Results base name xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    base_name = ("IA_stream_sel_results_{SNR}_{M}-{modulator}_{Nr}x{Nt}_({Ns})"
                 "_MaxIter_{max_iterations}_({initialize_with})")
    base_name = misc.replace_dict_values(base_name, params.parameters, True)
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    # xxxxxxxxxx Get the SimulationResults objects xxxxxxxxxxxxxxxxxxxxxxxx
    results = SimulationResults.load_from_file(
        'greedy_{0}.pickle'.format(base_name))
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    return results
Example #7
0
def get_result_from_file():
    """
    Load the SimulationResults object from the file and return it.
    """
    config_file = 'greedy_config_file.txt'

    # xxxxxxxxxx Config spec for the config file xxxxxxxxxxxxxxxxxxxxxxxxxx
    spec = """[Grid]
        cell_radius=float(min=0.01, default=1.0)
        num_cells=integer(min=3,default=3)
        num_clusters=integer(min=1,default=1)
        [Scenario]
        NSymbs=integer(min=10, max=1000000, default=200)
        SNR=real_numpy_array(min=-50, max=100, default=0:5:31)
        M=integer(min=4, max=512, default=4)
        modulator=option('QPSK', 'PSK', 'QAM', 'BPSK', default="PSK")
        Nr=integer_scalar_or_integer_numpy_array_check(min=2,default=3)
        Nt=integer_scalar_or_integer_numpy_array_check(min=2,default=3)
        Ns=integer_scalar_or_integer_numpy_array_check(min=1,default=3)
        N0=float(default=-116.4)
        scenario=string_list(default=list('Random', 'NoPathLoss'))
        [IA Algorithm]
        max_iterations=integer(min=1, default=120)
        initialize_with=string_list(default=list('random'))
        stream_sel_method=string_list(default=list('greedy', 'brute'))
        [General]
        rep_max=integer(min=1, default=2000)
        max_bit_errors=integer(min=1, default=3000)
        unpacked_parameters=string_list(default=list('SNR','stream_sel_method','scenario','initialize_with'))
        """.split("\n")

    params = SimulationParameters.load_from_config_file(config_file, spec)

    # xxxxx Results base name xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    base_name = ("IA_stream_sel_results_{SNR}_{M}-{modulator}_{Nr}x{Nt}_({Ns})"
                 "_MaxIter_{max_iterations}_({initialize_with})")
    base_name = misc.replace_dict_values(base_name, params.parameters, True)
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    # xxxxxxxxxx Get the SimulationResults objects xxxxxxxxxxxxxxxxxxxxxxxx
    results = SimulationResults.load_from_file(
        'greedy_{0}.pickle'.format(base_name))
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    return results
Example #8
0
def main_plot(index=0):  # pylint: disable=R0914,R0915
    """
    Function called to plot the results from a previous simulation.
    """
    from matplotlib import pyplot as plt

    config_file = "greedy_config_file.txt"

    # xxxxxxxxxx Config spec for the config file xxxxxxxxxxxxxxxxxxxxxxxxxx
    spec = """[Grid]
        cell_radius=float(min=0.01, default=1.0)
        num_cells=integer(min=3,default=3)
        num_clusters=integer(min=1,default=1)
        [Scenario]
        NSymbs=integer(min=10, max=1000000, default=200)
        SNR=real_numpy_array(min=-50, max=100, default=0:5:31)
        M=integer(min=4, max=512, default=4)
        modulator=option('QPSK', 'PSK', 'QAM', 'BPSK', default="PSK")
        Nr=integer_scalar_or_integer_numpy_array_check(min=2,default=3)
        Nt=integer_scalar_or_integer_numpy_array_check(min=2,default=3)
        Ns=integer_scalar_or_integer_numpy_array_check(min=1,default=3)
        N0=float(default=-116.4)
        scenario=string_list(default=list('Random', 'NoPathLoss'))
        [IA Algorithm]
        max_iterations=integer(min=1, default=120)
        initialize_with=string_list(default=list('random'))
        stream_sel_method=string_list(default=list('greedy', 'brute'))
        [General]
        rep_max=integer(min=1, default=2000)
        max_bit_errors=integer(min=1, default=3000)
        unpacked_parameters=string_list(default=list('SNR','stream_sel_method','scenario','initialize_with'))
        [Plot]
        max_iterations_plot=integer(default=5)
        initialize_with_plot=option('random', 'alt_min', default='random')
        """.split(
        "\n"
    )
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    # xxxxx Parameters xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    params = SimulationParameters.load_from_config_file(config_file, spec)
    max_iterations = params["max_iterations_plot"]
    # initialize_with = params['initialize_with_plot']
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    # xxxxx Results base name xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    base_name = (
        "IA_stream_sel_results_{SNR}_{M}-{modulator}_{Nr}x{Nt}" "_({Ns})_MaxIter_{max_iterations}_({initialize_with})"
    )
    # base_name = ("results_{SNR}_{M}-{modulator}_{Nr}x{Nt}_({Ns})_MaxIter"
    #              "_{max_iterations}_{initialize_with}")
    base_name = misc.replace_dict_values(base_name, params.parameters, True)
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    fig, ax = plt.subplots(nrows=1, ncols=1)
    fig2, ax2 = plt.subplots(nrows=1, ncols=1)

    # Include results with the Greedy and Brute Force stream selection
    # algorithms
    results = SimulationResults.load_from_file("greedy_{0}.pickle".format(base_name))

    # We only get the parameters from the greedy object, since we use the
    # same parameters for greedy and brute force
    parameters_dict = results.params.parameters
    # Fixed parameters for the Greedy stream selection algorithm in the
    # "NoPathLoss" scenario
    greedy_nopl_fixed_params = {
        "max_iterations": max_iterations,
        "stream_sel_method": "greedy",
        "initialize_with": "random",
        "scenario": "NoPathLoss",
    }
    # Fixed parameters for the Greedy stream selection algorithm in the
    # "Random" scenario (path loss with random positions for the users)
    greedy_random_fixed_params = {
        "max_iterations": max_iterations,
        "stream_sel_method": "greedy",
        "initialize_with": "random",
        "scenario": "Random",
    }
    # Fixed parameters for the Brute Force stream selection algorithm in
    # the "NoPathLoss" scenario
    brute_nopl_fixed_params = {
        "max_iterations": max_iterations,
        "stream_sel_method": "brute",
        "initialize_with": "random",
        "scenario": "NoPathLoss",
    }
    # Fixed parameters for the Brute Force stream selection algorithm in
    # the "Random" scenario (path loss with random positions for the users)
    brute_random_fixed_params = {
        "max_iterations": max_iterations,
        "stream_sel_method": "brute",
        "initialize_with": "random",
        "scenario": "Random",
    }

    _plot_ber(results, greedy_nopl_fixed_params, ax, "Greedy (No PL)", "-b*")
    _plot_ber(results, greedy_random_fixed_params, ax, "Greedy (With PL)", "-r*")

    _plot_sum_capacity(results, greedy_nopl_fixed_params, ax2, "Greedy (No PL)", "-b*")
    _plot_sum_capacity(results, greedy_random_fixed_params, ax2, "Greedy (With PL)", "-r*")

    _plot_ber(results, brute_nopl_fixed_params, ax, "Brute Force (No PL)", "-co")
    _plot_ber(results, brute_random_fixed_params, ax, "Brute Force (With PL)", "-mo")

    _plot_sum_capacity(results, brute_nopl_fixed_params, ax2, "Brute Force (No PL)", "-co")
    _plot_sum_capacity(results, brute_random_fixed_params, ax2, "Brute Force (With PL)", "-mo")

    # Get a dataframe with the results in a well organized way
    results_dataframe = get_dataframe_from_results(results)
    filename = "greedy_results_{M}-{modulator}.csv".format(**results.params.parameters)
    results_dataframe.to_csv(filename, index_label="SNR")

    # xxxxxxxxxx BER Plot Options xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    ax.set_xlabel("SNR")
    ax.set_ylabel("BER")
    title = (
        "BER for Different Algorithms ({max_iterations} Max Iterations)\n"
        "K={num_cells}, Nr={Nr}, Nt={Nt}, Ns={Ns}, {M}-{modulator}"
    )
    title = title.replace("{max_iterations}", str(max_iterations))
    ax.set_title(title.format(**parameters_dict))

    ax.set_yscale("log")
    ax.legend(fancybox=True, shadow=True, loc="best")
    ax.grid(True, which="both", axis="both")

    # plt.show(block=False)
    fig_base_name = "{Nr}x{Nt}_({Ns})_{M}-{modulator}".format(**params.parameters)
    fig.savefig("ber_{0}.pdf".format(fig_base_name))
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    # xxxxxxxxxx Sum Capacity Plot Options xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    ax2.set_xlabel("SNR")
    ax2.set_ylabel("Sum Capacity")
    title = (
        "Sum Capacity for Different Algorithms ({max_iterations} Max "
        "Iterations)\nK={num_cells}, Nr={Nr}, Nt={Nt}, Ns={Ns}, {M}-"
        "{modulator}"
    )
    title = title.replace("{max_iterations}", str(max_iterations))
    ax2.set_title(title.format(**parameters_dict))

    ax2.legend(fancybox=True, shadow=True, loc=2)
    ax2.grid(True, which="both", axis="both")
    # plt.show()
    fig2.savefig("sum_capacity_{0}.pdf".format(fig_base_name))
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    plt.show()
Example #9
0
def main_plot(index=0):  # pylint: disable=R0914,R0915
    """
    Function called to plot the results from a previous simulation.

    Parameters
    ----------
    index : int
    """
    from matplotlib import pyplot as plt

    config_file = 'greedy_config_file.txt'

    # xxxxxxxxxx Config spec for the config file xxxxxxxxxxxxxxxxxxxxxxxxxx
    spec = """[Grid]
        cell_radius=float(min=0.01, default=1.0)
        num_cells=integer(min=3,default=3)
        num_clusters=integer(min=1,default=1)
        [Scenario]
        NSymbs=integer(min=10, max=1000000, default=200)
        SNR=real_numpy_array(min=-50, max=100, default=0:5:31)
        M=integer(min=4, max=512, default=4)
        modulator=option('QPSK', 'PSK', 'QAM', 'BPSK', default="PSK")
        Nr=integer_scalar_or_integer_numpy_array_check(min=2,default=3)
        Nt=integer_scalar_or_integer_numpy_array_check(min=2,default=3)
        Ns=integer_scalar_or_integer_numpy_array_check(min=1,default=3)
        N0=float(default=-116.4)
        scenario=string_list(default=list('Random', 'NoPathLoss'))
        [IA Algorithm]
        max_iterations=integer(min=1, default=120)
        initialize_with=string_list(default=list('random'))
        stream_sel_method=string_list(default=list('greedy', 'brute'))
        [General]
        rep_max=integer(min=1, default=2000)
        max_bit_errors=integer(min=1, default=3000)
        unpacked_parameters=string_list(default=list('SNR','stream_sel_method','scenario','initialize_with'))
        [Plot]
        max_iterations_plot=integer(default=5)
        initialize_with_plot=option('random', 'alt_min', default='random')
        """.split("\n")
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    # xxxxx Parameters xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    params = SimulationParameters.load_from_config_file(config_file, spec)
    max_iterations = params['max_iterations_plot']
    # initialize_with = params['initialize_with_plot']
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    # xxxxx Results base name xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    base_name = ("IA_stream_sel_results_{SNR}_{M}-{modulator}_{Nr}x{Nt}"
                 "_({Ns})_MaxIter_{max_iterations}_({initialize_with})")
    # base_name = ("results_{SNR}_{M}-{modulator}_{Nr}x{Nt}_({Ns})_MaxIter"
    #              "_{max_iterations}_{initialize_with}")
    base_name = misc.replace_dict_values(base_name, params.parameters, True)
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    fig, ax = plt.subplots(nrows=1, ncols=1)
    fig2, ax2 = plt.subplots(nrows=1, ncols=1)

    # Include results with the Greedy and Brute Force stream selection
    # algorithms
    results = SimulationResults.load_from_file(
        'greedy_{0}.pickle'.format(base_name))

    # We only get the parameters from the greedy object, since we use the
    # same parameters for greedy and brute force
    parameters_dict = results.params.parameters
    # Fixed parameters for the Greedy stream selection algorithm in the
    # "NoPathLoss" scenario
    greedy_nopl_fixed_params = {
        'max_iterations': max_iterations,
        'stream_sel_method': 'greedy',
        'initialize_with': 'random',
        'scenario': 'NoPathLoss'
    }
    # Fixed parameters for the Greedy stream selection algorithm in the
    # "Random" scenario (path loss with random positions for the users)
    greedy_random_fixed_params = {
        'max_iterations': max_iterations,
        'stream_sel_method': 'greedy',
        'initialize_with': 'random',
        'scenario': 'Random'
    }
    # Fixed parameters for the Brute Force stream selection algorithm in
    # the "NoPathLoss" scenario
    brute_nopl_fixed_params = {
        'max_iterations': max_iterations,
        'stream_sel_method': 'brute',
        'initialize_with': 'random',
        'scenario': 'NoPathLoss'
    }
    # Fixed parameters for the Brute Force stream selection algorithm in
    # the "Random" scenario (path loss with random positions for the users)
    brute_random_fixed_params = {
        'max_iterations': max_iterations,
        'stream_sel_method': 'brute',
        'initialize_with': 'random',
        'scenario': 'Random'
    }

    _plot_ber(results, greedy_nopl_fixed_params, ax, 'Greedy (No PL)', '-b*')
    _plot_ber(results, greedy_random_fixed_params, ax, 'Greedy (With PL)',
              '-r*')

    _plot_sum_capacity(results, greedy_nopl_fixed_params, ax2,
                       'Greedy (No PL)', '-b*')
    _plot_sum_capacity(results, greedy_random_fixed_params, ax2,
                       'Greedy (With PL)', '-r*')

    _plot_ber(results, brute_nopl_fixed_params, ax, 'Brute Force (No PL)',
              '-co')
    _plot_ber(results, brute_random_fixed_params, ax, 'Brute Force (With PL)',
              '-mo')

    _plot_sum_capacity(results, brute_nopl_fixed_params, ax2,
                       'Brute Force (No PL)', '-co')
    _plot_sum_capacity(results, brute_random_fixed_params, ax2,
                       'Brute Force (With PL)', '-mo')

    # Get a dataframe with the results in a well organized way
    results_dataframe = get_dataframe_from_results(results)
    filename = 'greedy_results_{M}-{modulator}.csv'.format(
        **results.params.parameters)
    results_dataframe.to_csv(filename, index_label='SNR')

    # xxxxxxxxxx BER Plot Options xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    ax.set_xlabel('SNR')
    ax.set_ylabel('BER')
    title = ("BER for Different Algorithms ({max_iterations} Max Iterations)\n"
             "K={num_cells}, Nr={Nr}, Nt={Nt}, Ns={Ns}, {M}-{modulator}")
    title = title.replace("{max_iterations}", str(max_iterations))
    ax.set_title(title.format(**parameters_dict))

    ax.set_yscale('log')
    ax.legend(fancybox=True, shadow=True, loc='best')
    ax.grid(True, which='both', axis='both')

    # plt.show(block=False)
    fig_base_name = "{Nr}x{Nt}_({Ns})_{M}-{modulator}".format(
        **params.parameters)
    fig.savefig('ber_{0}.pdf'.format(fig_base_name))
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    # xxxxxxxxxx Sum Capacity Plot Options xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    ax2.set_xlabel('SNR')
    ax2.set_ylabel('Sum Capacity')
    title = ("Sum Capacity for Different Algorithms ({max_iterations} Max "
             "Iterations)\nK={num_cells}, Nr={Nr}, Nt={Nt}, Ns={Ns}, {M}-"
             "{modulator}")
    title = title.replace("{max_iterations}", str(max_iterations))
    ax2.set_title(title.format(**parameters_dict))

    ax2.legend(fancybox=True, shadow=True, loc=2)
    ax2.grid(True, which='both', axis='both')
    # plt.show()
    fig2.savefig('sum_capacity_{0}.pdf'.format(fig_base_name))
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    plt.show()
Example #10
0
def main_plot(algorithms_to_simulate, index=0):  # pylint: disable=R0914,R0915
    """
    Function called to plot the results from a previous simulation.

    Parameters
    ----------
    algorithms_to_simulate : list[str]
        List of algorithm names to simulate.
    index : int
        The index to simulate.
    """
    from matplotlib import pyplot as plt

    if args.config is None:
        config_file = 'ia_config_file.txt'
    else:
        config_file = args.config

    # xxxxxxxxxx Config spec for the config file xxxxxxxxxxxxxxxxxxxxxxxxxx
    spec = """[Scenario]
        SNR=real_numpy_array(min=-50, max=100, default=0:5:31)
        M=integer(min=4, max=512, default=4)
        modulator=option('QPSK', 'PSK', 'QAM', 'BPSK', default="PSK")
        NSymbs=integer(min=10, max=1000000, default=200)
        K=integer(min=2,default=3)
        Nr=integer_scalar_or_integer_numpy_array_check(min=2,default=2)
        Nt=integer_scalar_or_integer_numpy_array_check(min=2,default=2)
        Ns=integer_scalar_or_integer_numpy_array_check(min=1,default=1)
        [IA Algorithm]
        max_iterations=integer_numpy_array(min=1, default=60)
        [General]
        rep_max=integer(min=1, default=2000)
        max_bit_errors=integer(min=1, default=3000)
        unpacked_parameters=string_list(default=list('SNR'))
        [Plot]
        max_iterations_plot=integer(default=5)
        initialize_with_plot=option('random', 'alt_min', default='random')
        """.split("\n")
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    # xxxxx Parameters xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    params = SimulationParameters.load_from_config_file(config_file, spec)
    max_iterations = params['max_iterations_plot']
    initialize_with = params['initialize_with_plot']
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    # xxxxx Results base name xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    # Base name for all IA algorithms (except the Closed Form)
    base_name = ("results_{M}-{modulator}_{Nr}x{Nt}_({Ns})_MaxIter"
                 "_{max_iterations}")
    base_name = misc.replace_dict_values(base_name, params.parameters)

    base_name2 = ("results_{M}-{modulator}_{Nr}x{Nt}_({Ns})_MaxIter"
                  "_{max_iterations}_{initialize_with}")
    base_name2 = misc.replace_dict_values(base_name2, params.parameters)

    # Base name for the closed form IA algorithm.
    base_name_no_iter = base_name
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    fig, ax = plt.subplots(nrows=1, ncols=1)
    fig2, ax2 = plt.subplots(nrows=1, ncols=1)

    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    if 'Alt Min' in algorithms_to_simulate:
        alt_min_results = SimulationResults.load_from_file(
            'ia_alt_min_{0}.pickle'.format(base_name))
        parameters_dict = alt_min_results.params.parameters
        fixed_params = {'max_iterations': max_iterations}
        _plot_ber(alt_min_results, fixed_params, ax, 'Alt. Min.', '-r*')
        _plot_sum_capacity(
            alt_min_results, fixed_params, ax2, 'Alt. Min.', '-r*')

    if "Closed Form" in algorithms_to_simulate:
        closed_form_results = SimulationResults.load_from_file(
            'ia_closed_form_{0}.pickle'.format(base_name_no_iter))
        parameters_dict = closed_form_results.params.parameters
        fixed_params = {}
        _plot_ber(closed_form_results, fixed_params, ax, 'Closed Form', '-b*')
        _plot_sum_capacity(
            closed_form_results, fixed_params, ax2, 'Closed Form', '-b*')

    if "Max SINR" in algorithms_to_simulate:
        max_sinrn_results = SimulationResults.load_from_file(
            'ia_max_sinr_{0}.pickle'.format(base_name2))
        parameters_dict = max_sinrn_results.params.parameters
        fixed_params = {'max_iterations': max_iterations,
                        'initialize_with': initialize_with}
        _plot_ber(max_sinrn_results, fixed_params, ax, 'Max SINR', '-g*')
        _plot_sum_capacity(
            max_sinrn_results, fixed_params, ax2, 'Max SINR', '-g*')

    if "MMSE" in algorithms_to_simulate:
        mmse_results = SimulationResults.load_from_file(
            'ia_mmse_{0}.pickle'.format(base_name2))
        parameters_dict = mmse_results.params.parameters
        fixed_params = {'max_iterations': max_iterations,
                        'initialize_with': initialize_with}
        _plot_ber(mmse_results, fixed_params, ax, 'MMSE', '-m*')
        _plot_sum_capacity(mmse_results, fixed_params, ax2, 'MMSE', '-m*')
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    # xxxxxxxxxx BER Plot Options xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    ax.set_xlabel('SNR')
    ax.set_ylabel('BER')
    title = ("BER for Different Algorithms ({max_iterations} Max Iterations)\n"
             "K={K}, Nr={Nr}, Nt={Nt}, Ns={Ns}, {M}-{modulator}")
    title = title.replace("{max_iterations}", str(max_iterations))
    # noinspection PyUnboundLocalVariable
    ax.set_title(title.format(**parameters_dict))

    ax.set_yscale('log')
    ax.legend(fancybox=True, shadow=True, loc='best')
    ax.grid(True, which='both', axis='both')

    # plt.show(block=False)
    fig.savefig('ber_all_ia_algorithms.pgf')
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    # xxxxxxxxxx Sum Capacity Plot Options xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    ax2.set_xlabel('SNR')
    ax2.set_ylabel('Sum Capacity')
    title = ("Sum Capacity for Different Algorithms ({max_iterations} Max "
             "Iterations)\nK={K}, Nr={Nr}, Nt={Nt}, Ns={Ns}, {M}-{modulator}")
    title = title.replace("{max_iterations}", str(max_iterations))
    ax2.set_title(title.format(**parameters_dict))

    ax2.legend(fancybox=True, shadow=True, loc=2)
    ax2.grid(True, which='both', axis='both')
    # plt.show()
    fig2.savefig('sum_capacity_all_ia_algorithms.pgf')
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    plt.show()
def main():
    """Main function of the script.
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('name', help="The name of the SimulationResults file.")
    parser.add_argument('folder',
                        help="The name of the second SimulationResults file.",
                        nargs='?')

    args = parser.parse_args()

    name = args.name
    folder = args.folder  # This will be None, if not provided

    results = SimulationResults.load_from_file(name)

    original_filename = results.original_filename

    # xxxxxxxxxx Remove the .pickle file extension xxxxxxxxxxxxxxxxxxxxxxxx
    # If partial_filename has a 'pickle' extension we remove it from the name
    original_filename_no_ext, ext = os.path.splitext(original_filename)
    if ext == '.pickle':
        original_filename = original_filename_no_ext
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    unpacked_params_list = results.params.get_unpacked_params_list()
    all_results_names = results.get_result_names()

    for i, p in enumerate(results.params.get_unpacked_params_list()):
        partial_filename = get_partial_results_filename(
            original_filename, p, folder)
        partial_filename_with_replacements = replace_dict_values(
            partial_filename,
            results.params.parameters,
            filename_mode=True)

        if partial_filename_with_replacements == name:
            raise RuntimeError('invalid name')

        partial_param = unpacked_params_list[i]
        partial_result = SimulationResults()
        partial_result.set_parameters(partial_param)

        for result_name in all_results_names:
            partial_result.add_result(results[result_name][i])

        partial_result.current_rep = results.runned_reps[i]

        # Try to save the partial results. If we get an error
        try:
            # If we get an IOError exception here, maybe we are trying to
            # save to a folder and the folder does not exist yet.
            partial_result.save_to_file(partial_filename_with_replacements)
        except IOError as e:
            if folder is not None:
                # Lets create the folder...
                os.mkdir(folder)
                # ... and try to save the file again.
                partial_result.save_to_file(partial_filename_with_replacements)
            else:
                raise e