示例#1
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)
示例#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)
示例#3
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
示例#4
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
示例#5
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()
示例#6
0
    def _run_simulation(self, current_parameters):  # pylint: disable=R0914,R0915
        # xxxxxxxxxx Prepare the scenario for this iteration. xxxxxxxxxxxxx
        # This will create user in random positons and calculate pathloss
        # (if the scenario includes it). After that, it will generate
        # random channels from all transmitters to all receivers.
        self._create_users_channels_according_to_scenario(current_parameters)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxx Input parameters (set in the constructor) xxxxxxxxxxxxxxxxx
        M = self.modulator.M
        NSymbs = current_parameters["NSymbs"]
        K = current_parameters["num_cells"]
        # Nr = current_parameters["Nr"]
        # Nt = current_parameters["Nt"]
        Ns = current_parameters["Ns"]
        SNR = current_parameters["SNR"]

        if current_parameters["scenario"] == "NoPathLoss":
            pt = self._calc_transmit_power(SNR, self.noise_var)
        elif current_parameters["scenario"] == "Random":
            pt = self._calc_transmit_power(SNR, self.noise_var, self._path_loss_border)
        else:
            raise ValueError("Invalid scenario")

        # Store the original (maximum) number of streams for each user for
        # later usage
        if isinstance(Ns, int):
            orig_Ns = np.ones(K, dtype=int) * Ns
        else:
            orig_Ns = Ns.copy()
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxx Calc. precoders and receive filters for IA xxxxxxxxxxxxxxxx
        # We need to perform IA before generating any data so that we know
        # how many streams we need to send (and thus generate data. Note
        # that it is not always equal to Ns. It can be lower for some user
        # if the IA algorithm chooses a precoder that sends zero energy in
        # some stream.
        self.ia_solver.clear()
        self.ia_solver.initialize_with = current_parameters["initialize_with"]
        try:
            self.ia_top_object.solve(Ns=Ns, P=pt)
        except (RuntimeError, LinAlgError):
            raise SkipThisOne("Could not find the IA solution. Skipping this repetition")

        # If any of the Nr, Nt or Ns variables were integers (meaning all
        # users have the same value) we will convert them by numpy arrays
        # with correct size (K).
        # Nr = self.ia_solver.Nr
        # Nt = self.ia_solver.Nt
        Ns = self.ia_solver.Ns

        cumNs = np.cumsum(self.ia_solver.Ns)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxx Input Data xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        # inputData has the data of all users (vertically stacked)
        inputData = self.data_RS.randint(0, M, [np.sum(Ns), NSymbs])
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxx Modulate input data xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        # modulatedData has the data of all users (vertically stacked)
        modulatedData = self.modulator.modulate(inputData)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxxxxxxx Perform the Interference Alignment xxxxxxxxxxxxxxxxxxx
        # Split the data. transmit_signal will be a list and each element
        # is a numpy array with the data of a user
        transmit_signal = np.split(modulatedData, cumNs[:-1])
        transmit_signal_precoded = map(np.dot, self.ia_solver.full_F, transmit_signal)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxx Pass through the channel xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        # noinspection PyProtectedMember
        multi_user_channel = self.ia_solver._multiUserChannel
        # received_data is an array of matrices, one matrix for each receiver.
        received_data = multi_user_channel.corrupt_data(transmit_signal_precoded)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxx Perform the Interference Cancelation xxxxxxxxxxxxxxxxxxxxxx
        received_data_no_interference = map(np.dot, self.ia_solver.full_W_H, received_data)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxx Demodulate Data xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        received_data_no_interference = np.vstack(received_data_no_interference)
        demodulated_data = self.modulator.demodulate(received_data_no_interference)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxx Calculates the symbol and bit error rates xxxxxxxxxxxxxxxxx
        symbolErrors = np.sum(inputData != demodulated_data)
        bitErrors = misc.count_bit_errors(inputData, demodulated_data)
        numSymbols = inputData.size
        numBits = inputData.size * fundamental.level2bits(M)
        ia_cost = self.ia_solver.get_cost()
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxxxxxxx Calculates the Sum Capacity xxxxxxxxxxxxxxxxxxxxxxxxxx
        sirn_all_k = self.ia_solver.calc_SINR()
        calc_capacity = lambda sirn: np.sum(np.log2(1 + sirn))
        # Array with the sum capacity of each user
        sum_capacity = list(map(calc_capacity, sirn_all_k))
        # Total sum capacity
        total_sum_capacity = np.sum(sum_capacity)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxxxxxxx Number of iterations of the IA algorithm xxxxxxxxxxxxx
        ia_runned_iterations = self.ia_solver.runned_iterations
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxx Return the simulation results xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        symbolErrorsResult = Result.create("symbol_errors", Result.SUMTYPE, symbolErrors)

        numSymbolsResult = Result.create("num_symbols", Result.SUMTYPE, numSymbols)

        bitErrorsResult = Result.create("bit_errors", Result.SUMTYPE, bitErrors)

        numBitsResult = Result.create("num_bits", Result.SUMTYPE, numBits)

        berResult = Result.create("ber", Result.RATIOTYPE, bitErrors, numBits, accumulate_values=False)

        serResult = Result.create("ser", Result.RATIOTYPE, symbolErrors, numSymbols, accumulate_values=False)

        ia_costResult = Result.create("ia_cost", Result.RATIOTYPE, ia_cost, 1, accumulate_values=False)

        sum_capacityResult = Result.create(
            "sum_capacity", Result.RATIOTYPE, total_sum_capacity, 1, accumulate_values=False
        )

        ia_runned_iterationsResult = Result.create(
            "ia_runned_iterations", Result.RATIOTYPE, ia_runned_iterations, 1, accumulate_values=False
        )

        # xxxxxxxxxx chosen stream configuration index xxxxxxxxxxxxxxxxxxxx
        # Interpret Ns as a multidimensional index
        stream_index_multi = Ns - 1
        # Convert to a 1D index suitable for storing
        stream_index = int(np.ravel_multi_index(stream_index_multi, orig_Ns))
        num_choices = int(np.prod(orig_Ns))

        stream_statistics = Result.create("stream_statistics", Result.CHOICETYPE, stream_index, num_choices)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        simResults = SimulationResults()
        simResults.add_result(symbolErrorsResult)
        simResults.add_result(numSymbolsResult)
        simResults.add_result(bitErrorsResult)
        simResults.add_result(numBitsResult)
        simResults.add_result(berResult)
        simResults.add_result(serResult)
        simResults.add_result(ia_costResult)
        simResults.add_result(sum_capacityResult)
        simResults.add_result(ia_runned_iterationsResult)
        simResults.add_result(stream_statistics)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        return simResults
from pyphysim.simulations.runner import SimulationRunner, SkipThisOne
from pyphysim.simulations.parameters import SimulationParameters
from pyphysim.simulations.results import SimulationResults, Result
from pyphysim.simulations.simulationhelpers import simulate_do_what_i_mean
from pyphysim.comm import modulators, channels, pathloss
from pyphysim.util.conversion import dB2Linear, dBm2Linear
from pyphysim.util import misc
from pyphysim.ia import algorithms
from pyphysim.cell import cell
# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


if __name__ == '__main__':
    full_results_name = ("greedy_IA_stream_sel_results_[0.0_(5.0)_30.0]_"
                         "4-PSK_3x3_(3)_MaxIter_120_(['random']).pickle")
    full_result = SimulationResults.load_from_file(full_results_name)
    full_params = full_result.params

    name = ("partial_results/greedy_IA_stream_sel_results_[0.0_(5.0)_30.0]_"
            "4-PSK_3x3_(3)_MaxIter_120_(['random'])_unpack_{:0>2d}.pickle")

    for i in range(28):
        result = SimulationResults.load_from_file(name.format(i))
        params = result.params
        stream_sel_method = params['stream_sel_method']
        scenario = params['scenario']
        initialize_with = params['initialize_with']
        SNR = params['SNR']
        # print('Unpacked parameters')
        print('scenario: {0:>10} | stream_sel_method: {1:>6s} | '
              'SNR: {2:>4}').format(scenario, stream_sel_method, SNR)
示例#8
0
#!/usr/bin/env python

from pyphysim.simulations.results import SimulationResults

if __name__ == '__main__':
    full_results_name = ("greedy_IA_stream_sel_results_[0.0_(5.0)_30.0]_"
                         "4-PSK_3x3_(3)_MaxIter_120_(['random']).pickle")
    full_result = SimulationResults.load_from_file(full_results_name)
    full_params = full_result.params

    name = ("partial_results/greedy_IA_stream_sel_results_[0.0_(5.0)_30.0]_"
            "4-PSK_3x3_(3)_MaxIter_120_(['random'])_unpack_{:0>2d}.pickle")

    for i in range(28):
        result = SimulationResults.load_from_file(name.format(i))
        params = result.params
        stream_sel_method = params['stream_sel_method']
        scenario = params['scenario']
        initialize_with = params['initialize_with']
        SNR = params['SNR']
        # print('Unpacked parameters')
        print(('scenario: {0:>10} | stream_sel_method: {1:>6s} | '
               'SNR: {2:>4}').format(scenario, stream_sel_method, SNR))

        # if scenario == 'NoPathLoss' and stream_sel_method == 'brute':
        #     print "SNR {0}: Ber {1}".format(SNR, result['ber'])

        # SNR 0.0: Ber [Result -> ber: 192516/6502400 -> 0.0296069143701]
        # SNR 5.0: Ber [Result -> ber: 32498/7090800 -> 0.00458312179162]
        # SNR 10.0: Ber [Result -> ber: 2108/10665200 -> 0.000197652177174]
        # SNR 15.0: Ber [Result -> ber: 11/11884000 -> 9.25614271289e-07]
示例#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()
示例#10
0
    def _run_simulation(
            self,  # pylint: disable=R0914,R0915
            current_parameters):
        # xxxxxxxxxx Prepare the scenario for this iteration. xxxxxxxxxxxxx
        # This will create user in random positions and calculate pathloss
        # (if the scenario includes it). After that, it will generate
        # random channels from all transmitters to all receivers.
        self._create_users_channels_according_to_scenario(current_parameters)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxx Input parameters (set in the constructor) xxxxxxxxxxxxxxxxx
        M = self.modulator.M
        NSymbs = current_parameters["NSymbs"]
        K = current_parameters["num_cells"]
        # Nr = current_parameters["Nr"]
        # Nt = current_parameters["Nt"]
        Ns = current_parameters["Ns"]
        SNR = current_parameters["SNR"]

        if current_parameters['scenario'] == 'NoPathLoss':
            pt = self._calc_transmit_power(SNR, self.noise_var)
        elif current_parameters['scenario'] == 'Random':
            pt = self._calc_transmit_power(SNR, self.noise_var,
                                           self._path_loss_border)
        else:
            raise ValueError('Invalid scenario')

        # Store the original (maximum) number of streams for each user for
        # later usage
        if isinstance(Ns, int):
            orig_Ns = np.ones(K, dtype=int) * Ns
        else:
            orig_Ns = Ns.copy()
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxx Calc. precoders and receive filters for IA xxxxxxxxxxxxxxxx
        # We need to perform IA before generating any data so that we know
        # how many streams we need to send (and thus generate data. Note
        # that it is not always equal to Ns. It can be lower for some user
        # if the IA algorithm chooses a precoder that sends zero energy in
        # some stream.
        self.ia_solver.clear()
        self.ia_solver.initialize_with = current_parameters['initialize_with']
        try:
            self.ia_top_object.solve(Ns=Ns, P=pt)
        except (RuntimeError, LinAlgError):
            raise SkipThisOne(
                "Could not find the IA solution. Skipping this repetition")

        # If any of the Nr, Nt or Ns variables were integers (meaning all
        # users have the same value) we will convert them by numpy arrays
        # with correct size (K).
        # Nr = self.ia_solver.Nr
        # Nt = self.ia_solver.Nt
        Ns = self.ia_solver.Ns

        cumNs = np.cumsum(self.ia_solver.Ns)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxx Input Data xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        # inputData has the data of all users (vertically stacked)
        inputData = self.data_RS.randint(0, M, [np.sum(Ns), NSymbs])
        ":type: np.ndarray"
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxx Modulate input data xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        # modulatedData has the data of all users (vertically stacked)
        modulatedData = self.modulator.modulate(inputData)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxxxxxxx Perform the Interference Alignment xxxxxxxxxxxxxxxxxxx
        # Split the data. transmit_signal will be a list and each element
        # is a numpy array with the data of a user
        transmit_signal = np.split(modulatedData, cumNs[:-1])
        transmit_signal_precoded = map(np.dot, self.ia_solver.full_F,
                                       transmit_signal)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxx Pass through the channel xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        # noinspection PyProtectedMember
        multi_user_channel = self.ia_solver._multiUserChannel
        # received_data is an array of matrices, one matrix for each receiver.
        received_data = multi_user_channel.corrupt_data(
            transmit_signal_precoded)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxx Perform the Interference Cancellation xxxxxxxxxxxxxxxxxxxxx
        received_data_no_interference = map(np.dot, self.ia_solver.full_W_H,
                                            received_data)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxx Demodulate Data xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        received_data_no_interference = np.vstack(
            received_data_no_interference)
        demodulated_data = self.modulator.demodulate(
            received_data_no_interference)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxx Calculates the symbol and bit error rates xxxxxxxxxxxxxxxxx
        symbolErrors = np.sum(inputData != demodulated_data)
        bitErrors = misc.count_bit_errors(inputData, demodulated_data)
        numSymbols = inputData.size
        numBits = inputData.size * fundamental.level2bits(M)
        ia_cost = self.ia_solver.get_cost()
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxxxxxxx Calculates the Sum Capacity xxxxxxxxxxxxxxxxxxxxxxxxxx
        sirn_all_k = self.ia_solver.calc_SINR()
        calc_capacity = lambda sirn: np.sum(np.log2(1 + sirn))
        # Array with the sum capacity of each user
        sum_capacity = list(map(calc_capacity, sirn_all_k))
        # Total sum capacity
        total_sum_capacity = np.sum(sum_capacity)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxxxxxxx Number of iterations of the IA algorithm xxxxxxxxxxxxx
        ia_runned_iterations = self.ia_solver.runned_iterations
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxx Return the simulation results xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        symbolErrorsResult = Result.create("symbol_errors", Result.SUMTYPE,
                                           symbolErrors)

        numSymbolsResult = Result.create("num_symbols", Result.SUMTYPE,
                                         numSymbols)

        bitErrorsResult = Result.create("bit_errors", Result.SUMTYPE,
                                        bitErrors)

        numBitsResult = Result.create("num_bits", Result.SUMTYPE, numBits)

        berResult = Result.create("ber",
                                  Result.RATIOTYPE,
                                  bitErrors,
                                  numBits,
                                  accumulate_values=False)

        serResult = Result.create("ser",
                                  Result.RATIOTYPE,
                                  symbolErrors,
                                  numSymbols,
                                  accumulate_values=False)

        ia_costResult = Result.create("ia_cost",
                                      Result.RATIOTYPE,
                                      ia_cost,
                                      1,
                                      accumulate_values=False)

        sum_capacityResult = Result.create("sum_capacity",
                                           Result.RATIOTYPE,
                                           total_sum_capacity,
                                           1,
                                           accumulate_values=False)

        ia_runned_iterationsResult = Result.create("ia_runned_iterations",
                                                   Result.RATIOTYPE,
                                                   ia_runned_iterations,
                                                   1,
                                                   accumulate_values=False)

        # xxxxxxxxxx chosen stream configuration index xxxxxxxxxxxxxxxxxxxx
        # Interpret Ns as a multidimensional index
        stream_index_multi = Ns - 1
        # Convert to a 1D index suitable for storing
        stream_index = int(np.ravel_multi_index(stream_index_multi, orig_Ns))
        num_choices = int(np.prod(orig_Ns))

        stream_statistics = Result.create("stream_statistics",
                                          Result.CHOICETYPE, stream_index,
                                          num_choices)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        simResults = SimulationResults()
        simResults.add_result(symbolErrorsResult)
        simResults.add_result(numSymbolsResult)
        simResults.add_result(bitErrorsResult)
        simResults.add_result(numBitsResult)
        simResults.add_result(berResult)
        simResults.add_result(serResult)
        simResults.add_result(ia_costResult)
        simResults.add_result(sum_capacityResult)
        simResults.add_result(ia_runned_iterationsResult)
        simResults.add_result(stream_statistics)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        return simResults
示例#11
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
示例#12
0
        # xxxxx Results base name xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        base_name = ('results_{M}-{modulator}_'
                     '{Nr}x{Nt}_({Ns})_MaxIter_[5_(5)_60]').format(
                         M=M, modulator=modulator, Nr=Nr, Nt=Nt, Ns=Ns)
        # Used only for the closed form algorithm, which is not iterative
        base_name_no_iter = ('results_{M}-{modulator}_{Nr}x{Nt}_({Ns})'
                             '_MaxIter_[5_(5)_60]').format(M=M,
                                                           modulator=modulator,
                                                           Nr=Nr,
                                                           Nt=Nt,
                                                           Ns=Ns)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        alt_min_results = SimulationResults.load_from_file(
            'ia_alt_min_{0}.pickle'.format(base_name))
        closed_form_results = SimulationResults.load_from_file(
            'ia_closed_form_{0}.pickle'.format(base_name_no_iter))
        # closed_form_first_results = SimulationResults.load_from_file(
        #     'ia_closed_form_first_init_{0}.pickle'.format(base_name))
        max_sinrn_results = SimulationResults.load_from_file(
            'ia_max_sinr_{0}.pickle'.format(base_name))
        # min_leakage_results = SimulationResults.load_from_file(
        #     'ia_min_leakage_{0}.pickle'.format(base_name))
        mmse_results = SimulationResults.load_from_file(
            'ia_mmse_{0}.pickle'.format(base_name))
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        initialized = True

    # xxxxxxxxxx SNR variables xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
示例#13
0
        max_iterations = '60'
        modulator = "PSK"
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxx Results base name xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        base_name = ('results_{M}-{modulator}_'
                     '{Nr}x{Nt}_({Ns})_MaxIter_[5_(5)_60]').format(
                         M=M, modulator=modulator, Nr=Nr, Nt=Nt, Ns=Ns)
        # Used only for the closed form algorithm, which is not iterative
        base_name_no_iter = ('results_{M}-{modulator}_{Nr}x{Nt}_({Ns})'
                             '_MaxIter_[5_(5)_60]').format(
                                 M=M, modulator=modulator, Nr=Nr, Nt=Nt, Ns=Ns)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        alt_min_results = SimulationResults.load_from_file(
            'ia_alt_min_{0}.pickle'.format(base_name))
        closed_form_results = SimulationResults.load_from_file(
            'ia_closed_form_{0}.pickle'.format(base_name_no_iter))
        # closed_form_first_results = SimulationResults.load_from_file(
        #     'ia_closed_form_first_init_{0}.pickle'.format(base_name))
        max_sinrn_results = SimulationResults.load_from_file(
            'ia_max_sinr_{0}.pickle'.format(base_name))
        # min_leakage_results = SimulationResults.load_from_file(
        #     'ia_min_leakage_{0}.pickle'.format(base_name))
        mmse_results = SimulationResults.load_from_file(
            'ia_mmse_{0}.pickle'.format(base_name))
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        initialized = True

    ## xxxxxxxxxx SNR variables xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
示例#14
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()
示例#15
0
    def _run_simulation(self,   # pylint: disable=R0914,R0915
                        current_parameters):
        # xxxxx Input parameters (set in the constructor) xxxxxxxxxxxxxxxxx
        M = self.modulator.M
        NSymbs = current_parameters["NSymbs"]
        K = current_parameters["K"]
        Nr = current_parameters["Nr"]
        Nt = current_parameters["Nt"]
        Ns = current_parameters["Ns"]
        SNR = current_parameters["SNR"]

        # Dependent parameters
        noise_var = 1 / dB2Linear(SNR)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxx Calc. precoders and receive filters for IA xxxxxxxxxxxxxxxx
        # We need to perform IA before generating any data so that we know
        # how many streams we need to send (and thus generate data. Note
        # that it is not always equal to Ns. It can be lower for some user
        # if the IA algorithm chooses a precoder that sends zero energy in
        # some stream.
        self.multiUserChannel.randomize(Nr, Nt, K)
        self.multiUserChannel.noise_var = noise_var

        self.ia_solver.clear()
        self.ia_solver.solve(Ns)

        # If any of the Nr, Nt or Ns variables were integers (meaning all
        # users have the same value) we will convert them by numpy arrays
        # with correct size (K).
        # Nr = self.ia_solver.Nr
        # Nt = self.ia_solver.Nt
        Ns = self.ia_solver.Ns

        cumNs = np.cumsum(self.ia_solver.Ns)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxx Input Data xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        # inputData has the data of all users (vertically stacked)
        inputData = np.random.randint(0, M, [np.sum(Ns), NSymbs])
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxx Modulate input data xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        # modulatedData has the data of all users (vertically stacked)
        modulatedData = self.modulator.modulate(inputData)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxxxxxxx Perform the Interference Alignment xxxxxxxxxxxxxxxxxxx
        # Split the data. transmit_signal will be a list and each element
        # is a numpy array with the data of a user
        transmit_signal = np.split(modulatedData, cumNs[:-1])
        transmit_signal_precoded = map(
            np.dot, self.ia_solver.full_F, transmit_signal)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxx Pass through the channel xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        # noinspection PyProtectedMember
        multi_user_channel = self.ia_solver._multiUserChannel
        # received_data is an array of matrices, one matrix for each receiver.
        received_data = multi_user_channel.corrupt_data(
            transmit_signal_precoded)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxx Perform the Interference Cancellation xxxxxxxxxxxxxxxxxxxxx
        received_data_no_interference = map(
            np.dot, self.ia_solver.full_W_H, received_data)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxx Demodulate Data xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        received_data_no_interference = np.vstack(
            received_data_no_interference)
        demodulated_data = self.modulator.demodulate(
            received_data_no_interference)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxx Calculates the symbol and bit error rates xxxxxxxxxxxxxxxxx
        symbolErrors = np.sum(inputData != demodulated_data)
        bitErrors = misc.count_bit_errors(inputData, demodulated_data)
        numSymbols = inputData.size
        numBits = inputData.size * fundamental.level2bits(M)
        ia_cost = self.ia_solver.get_cost()
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxxxxxxx Calculates the Sum Capacity xxxxxxxxxxxxxxxxxxxxxxxxxx
        sirn_all_k = self.ia_solver.calc_SINR()
        calc_capacity = lambda sirn: np.sum(np.log2(1 + sirn))
        # Array with the sum capacity of each user
        sum_capacity = np.array(list(map(calc_capacity, sirn_all_k)))
        # Total sum capacity
        total_sum_capacity = np.sum(sum_capacity)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxxxxxxx Number of iterations of the IA algorithm xxxxxxxxxxxxx
        ia_runned_iterations = self.ia_solver.runned_iterations
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        # xxxxx Return the simulation results xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        symbolErrorsResult = Result.create(
            "symbol_errors", Result.SUMTYPE, symbolErrors)

        numSymbolsResult = Result.create(
            "num_symbols", Result.SUMTYPE, numSymbols)

        bitErrorsResult = Result.create(
            "bit_errors", Result.SUMTYPE, bitErrors)

        numBitsResult = Result.create("num_bits", Result.SUMTYPE, numBits)

        berResult = Result.create("ber", Result.RATIOTYPE, bitErrors, numBits,
                                  accumulate_values=False)

        serResult = Result.create("ser", Result.RATIOTYPE, symbolErrors,
                                  numSymbols, accumulate_values=False)

        ia_costResult = Result.create(
            "ia_cost", Result.RATIOTYPE, ia_cost, 1, accumulate_values=False)

        sum_capacityResult = Result.create(
            "sum_capacity", Result.RATIOTYPE, total_sum_capacity, 1,
            accumulate_values=False)

        ia_runned_iterationsResult = Result.create(
            "ia_runned_iterations", Result.RATIOTYPE, ia_runned_iterations, 1,
            accumulate_values=False)

        simResults = SimulationResults()
        simResults.add_result(symbolErrorsResult)
        simResults.add_result(numSymbolsResult)
        simResults.add_result(bitErrorsResult)
        simResults.add_result(numBitsResult)
        simResults.add_result(berResult)
        simResults.add_result(serResult)
        simResults.add_result(ia_costResult)
        simResults.add_result(sum_capacityResult)
        simResults.add_result(ia_runned_iterationsResult)
        # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        return simResults
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