Exemple #1
0
def generate_all_data_two_param(agents_quantities,
                                dic_fun,
                                p_v=None,
                                q_v=None):
    """ Generates data for all agents_quantities in the current as .csv files

    Args:
        agents_quantities (list of ints): list of population sized to be used
        dic_fun (dict): dictionary population size to list of rational functions
        p_v (float/None): value of the first parameter - p
        q_v (float/None): value of the second parameter - q
    """
    # create distribution data, by Tanja, 14.1.2019
    # edited, by xhajnal, 18.1.2019, still name 'a' is not defined
    # edited, by xhajnal, 26.1.2019, a set as [] but does not work
    # totally rewritten to not paste empty line, doc added, by xhajnal, 03.02.2019
    import random

    if p_v is None:
        p_v = random.uniform(0., 1.)
        p_v = round(p_v, 2)
    if q_v is None:
        q_v = random.uniform(0., 1.)
        q_v = round(q_v, 2)
    a = []

    # create the files called "data_n=N.csv" where the first line is
    # "n=5, p_v--q1_v--q2_v--q3_v--q4_v in the multiparam. case, and, e.g.
    # 0.03 -- 0.45 -- 0.002 -- 0.3 (for N=5, there are 4 entries)

    for N in agents_quantities:
        file = open('data_n=' + str(N) + ".csv", "w")
        file.write('n=' + str(N) + ', p_v=' + str(p_v) + ', q_v=' + str(q_v) +
                   "\n")
        second_line = ""

        for polynome in dic_fun[N]:
            parameters = set()
            if len(parameters) < N:
                parameters.update(find_param(polynome))
            parameters = sorted(list(parameters))
            parameter_value = [p_v, q_v]

            for param in range(len(parameters)):
                a.append(parameter_value[param])
                globals()[parameters[param]] = parameter_value[param]

            x = eval(polynome)
            x = round(x, 2)
            second_line = second_line + str(x) + ","

        file.write(second_line[:-1])
        file.close()
Exemple #2
0
def eval_and_show(functions,
                  parameter_value,
                  parameters=False,
                  data=False,
                  data_intervals=False,
                  cumulative=False,
                  debug: bool = False,
                  where=False):
    """ Creates bar plot of evaluation of given functions for given point in parameter space

    Args:
        functions (list of strings): list of rational functions
        parameter_value: (list of floats) array of param values
        parameters (list of strings): parameter names (used for faster eval)
        data (list): Data comparison next to respective function
        data_intervals (list): intervals obtained from the data to check if the function are within the intervals
        cumulative (bool): if True cdf instead of pdf is visualised
        debug (bool): if debug extensive output is provided
        where (tuple/list): output matplotlib sources to output created figure
    """

    ## Convert z3 functions
    for index, function in enumerate(functions):
        if is_this_z3_function(function):
            functions[index] = translate_z3_function(function)

    if not parameters:
        parameters = set()
        for polynome in functions:
            parameters.update(find_param(polynome, debug))
        parameters = sorted(list(parameters))
    if debug:
        print("Parameters: ", parameters)

    title = "Rational functions sampling \n parameter values:"
    values = []
    add = 0
    for param in range(len(parameters)):
        if debug:
            print("Parameters[param]", parameters[param])
            print("Parameter_value[param]", parameter_value[param])
        globals()[parameters[param]] = parameter_value[param]
        title = "{} {}={},".format(title, parameters[param],
                                   parameter_value[param])
    title = title[:-1]

    title = f"{title}\n values: "
    for polynome in functions:
        expression = eval(polynome)
        if debug:
            print(polynome)
            print("Eval ", polynome, expression)
        if cumulative:
            ## Add sum of all values
            add = add + expression
            values.append(add)
            title = f"{title} {add} , "
            del expression
        else:
            values.append(expression)
            title = f"{title} {expression} ,"
    title = title[:-2]
    if data:
        title = f"{title}\n Comparing with the data: \n{data}"
        if cumulative:
            for index in range(1, len(data)):
                data[index] = data[index] + data[index - 1]

    if where:
        fig = where[0]
        ax = where[1]
        plt.autoscale()
        ax.autoscale()
    else:
        fig, ax = plt.subplots()
    width = 0.2
    ax.set_ylabel(f'{("Value", "Cumulative value")[cumulative]}')
    if data:
        ax.set_xlabel(
            'Rational function indices (blue), Data point indices (red)')
        if data_intervals:
            functions_inside_of_intervals = []
            for index in range(len(data)):
                if values[index] in data_intervals[index]:
                    functions_inside_of_intervals.append(True)
                else:
                    functions_inside_of_intervals.append(False)
            title = f"{title} \n Function value within the respective interval:\n {functions_inside_of_intervals} \n Intervals: {data_intervals}"
    else:
        ax.set_xlabel('Rational function indices')
    ax.xaxis.set_major_locator(MaxNLocator(integer=True))
    if debug:
        print("title: \n", title)
    ax.set_title(wraper.fill(title))
    if debug:
        print("Len(fun_list): ", len(functions))
        print("values:", values)
        print("range:", range(1, len(values) + 1))
        print("title", title)
    ax.bar(range(1, len(values) + 1), values, width, color='b')
    if data:
        ax.bar(list(map(lambda x: x + width, range(1,
                                                   len(data) + 1))),
               data,
               width,
               color='r')

    if where:
        return fig, ax
    else:
        plt.show()
    return values
Exemple #3
0
def visualise(dic_fun,
              agents_quantities,
              size_q,
              cumulative=False,
              debug: bool = False,
              show_all_in_one=False,
              where=False):
    """ Creates bar plot of probabilities of i successes for sampled parametrisation

    Args:
        dic_fun (dictionary N -> list of rational functions)
        size_q (int): sample size in each parameter
        agents_quantities (int): pop sizes to be used
        cumulative (bool): if True cdf instead of pdf is visualised
        debug (bool): if debug extensive output is provided
        show_all_in_one (bool): if True all plots are put into one window
        where (tuple/list): output matplotlib sources to output created figure
    """

    for N in agents_quantities:
        parameters = set()
        for index, polynome in enumerate(dic_fun[N]):
            if is_this_z3_function(polynome):
                dic_fun[N][index] = translate_z3_function(polynome)

            if debug:
                print("Polynome: ", polynome)
            parameters.update(find_param(polynome, debug))

            ## THIS THING IS WORKING ONLY FOR THE CASE STUDY
            # if len(parameters) < N:
            #    parameters.update(find_param(polynome, debug))
        if debug:
            print("Parameters: ", parameters)
        parameters = sorted(list(parameters))
        if debug:
            print("Sorted parameters: ", parameters)

        parameter_values = get_param_values(parameters, size_q, debug)

        for parameter_value in parameter_values:
            if debug:
                print("Parameter_value: ", parameter_value)
            add = 0
            a = [N, dic_fun[N].index(polynome)]
            if N == 0:
                title = f"Rational functions sampling \n parameters:"
            else:
                title = f"Rational functions sampling \n N={N}, parameters:"
            for param in range(len(parameters)):
                a.append(parameter_value[param])
                if debug:
                    print("Parameter[param]: ", parameters[param])
                    print("Parameter_value[param]: ", parameter_value[param])
                globals()[parameters[param]] = parameter_value[param]
                title = "{} {}={},".format(title, parameters[param],
                                           parameter_value[param])
            title = title[:-1]
            if debug:
                print("Eval ", polynome, eval(polynome))
            for polynome in dic_fun[N]:
                value = eval(polynome)
                if cumulative:
                    ## Add sum of all values
                    add = add + value
                    a.append(add)
                    del value
                else:
                    a.append(value)

            # print(a)
            fig, ax = plt.subplots()
            width = 0.2
            ax.set_ylabel('Value')
            ax.set_xlabel('Rational function indices')
            ax.set_title(wraper.fill(title))
            # print(title)
            rects1 = ax.bar(range(len(dic_fun[N])),
                            a[len(parameters) + 2:],
                            width,
                            color='b')
            plt.show()
Exemple #4
0
def heatmap(function,
            region,
            sampling_sizes,
            posttitle="",
            where=False,
            parameters=False):
    """ Creates 2D heatmap plot of sampled points of given function

    Args:
        function (string): function to be analysed
        region (list of intervals): boundaries of parameter space to be sampled
        sampling_sizes (int): tuple of sample size of respective parameter
        posttitle (string): A string to be put after the title
        where (tuple/list): output matplotlib sources to output created figure
        parameters (list):: list of parameters

    Example:
        heatmap("p+q",[[0,1],[3,4]],[5,5])
    """

    ## Convert z3 function
    if is_this_z3_function(function):
        function = translate_z3_function(function)

    if not parameters:
        parameters = sorted(list(find_param(function)))
    # print(parameters)
    if len(parameters) != 2:
        raise Exception(
            f"Number of parameters of given function is not equal to 2 but {len(parameters)}"
        )

    arr = np.zeros((sampling_sizes[0] * sampling_sizes[1], 3))

    # f = lambda locals()[parameters[0]),locals()[parameters[1]): fun

    ii = -1
    jj = -1
    for i in np.linspace(region[0][0],
                         region[0][1],
                         sampling_sizes[0],
                         endpoint=True):
        ii += 1
        # print("ii: ",ii)
        locals()[parameters[0]] = i
        for j in np.linspace(region[1][0],
                             region[1][1],
                             sampling_sizes[1],
                             endpoint=True):
            jj += 1
            # print("jj: ",jj)
            locals()[parameters[1]] = j
            arr[jj, 0] = round(i, 2)
            arr[jj, 1] = round(j, 2)
            arr[jj, 2] = eval(function)
    # print(arr)
    # d = pd.DataFrame(arr, columns=["p","q","E"])
    heatmap_data = pd.DataFrame(arr,
                                columns=[parameters[0], parameters[1], "E"])
    # d = d.pivot("p", "q", "E")
    heatmap_data = heatmap_data.pivot(parameters[0], parameters[1], "E")

    if where:
        f, ax = plt.subplots()
        ax = sns.heatmap(heatmap_data)
        title = f"Heatmap \n{posttitle}"
        ax.set_title(wraper.fill(title))
        ax.invert_yaxis()
        return f
    else:
        ax = sns.heatmap(heatmap_data)
        title = f"Heatmap of the parameter space \n function: {function}"
        ax.set_title(wraper.fill(title))
        ax.invert_yaxis()
        plt.show()
Exemple #5
0
def sample_list_funs(functions,
                     size_q,
                     parameters=False,
                     intervals=False,
                     silent: bool = False,
                     debug: bool = False):
    """ Returns a list of function values for sampled parametrisations

    Args:
        functions: (list of functions) to be sampled
        size_q (int): sample size in each parameter
        parameters (list of strings): parameter names (used for faster eval)
        intervals (list of pairs of numbers): intervals of parameters
        silent (bool): if silent command line output is set to minimum
        debug (bool): if debug extensive output is provided

    Returns:
        (array): [function index, [parameter values], function value]

    """
    arr = []
    if debug:
        print("Inside of sample_n_visualise.sample_list_funs()")
        print("List_fun: ", functions)
        print("Intervals: ", intervals)

    for index, polynome in enumerate(functions):
        if is_this_z3_function(polynome):
            functions[index] = translate_z3_function(polynome)
        if debug:
            print("Polynome: ", polynome)

        if parameters:
            fun_parameters = parameters
        else:
            fun_parameters = set()
            fun_parameters.update(find_param(polynome, debug))

            ## THIS THING IS WORKING ONLY FOR THE CASE STUDY
            # if len(parameters) < N:
            #     parameters.update(find_param(polynome, debug))
            if debug:
                print("Parameters: ", fun_parameters)
            fun_parameters = sorted(list(fun_parameters))

        if debug:
            print("Sorted parameters: ", fun_parameters)

        parameter_values = get_param_values(fun_parameters,
                                            size_q,
                                            intervals=intervals,
                                            debug=debug)

        for parameter_value in parameter_values:
            if debug:
                print("Parameter_value: ", parameter_value)
            a = [functions.index(polynome)]
            for param_index in range(len(fun_parameters)):
                a.append(parameter_value[param_index])
                if debug:
                    print("Parameter[param]: ", fun_parameters[param_index])
                    print("Parameter_value[param]: ",
                          parameter_value[param_index])
                locals()[fun_parameters[param_index]] = float(
                    parameter_value[param_index])

            print("polynome", polynome)

            value = eval(polynome)
            if debug:
                print("Eval ", polynome, value)
            a.append(value)
            arr.append(a)
    return arr