Пример #1
0
def create_plots(begin, end, stride):
    """ 
    Plot the function double, square, and exp
    from beginning to end using the provided stride (step)
    
    The x-coordinates of the plotted points start
    at begin, terminate at end and are spaced by 
    distance stride, similar to range(start, stop, step) function
    """
    
    # generate x coordinates for plot points
    x_coords = []
    current_x = begin
    while current_x < end:
        x_coords.append(current_x)
        current_x += stride
        
    # compute list of tuples, (x, y) coordinates, for each function
    # y coordinate can be thought of as f(x)
    double_plot = [(x_val, double(x_val)) for x_val in x_coords]
    square_plot = [(x_val, square(x_val)) for x_val in x_coords]
    exp_plot = [(x_val, exp(x_val)) for x_val in x_coords]
    
    # plot the list of points
    # arguments: simpleplot.plot_lines(framename, width, height, xlabel, ylabel, datasets, points, legends)
    simpleplot.plot_lines("Plots of three functions", 600, 400, "x", "f(x)",
                         [double_plot, square_plot, exp_plot], 
                         True, ["double", "square", "exp"])
Пример #2
0
def run_strategy(strategy_name, time, strategy):
    """
    Run a simulation for the given time with one strategy.
    :param strategy_name:
    :param time:
    :param strategy:
    """
    state = simulate_clicker(provided.BuildInfo(), time, strategy)
    print strategy_name, ":", state
    print state._total_num_cookies

    # Plot total cookies over time

    # Uncomment out the lines below to see a plot of total cookies vs. time
    # Be sure to allow popups, if you do want to see it

    history = state.get_history()
    history = [(item[0], item[3]) for item in history]
    simpleplot.plot_lines(strategy_name,
                          1000,
                          500,
                          'Time',
                          'Total Cookies', [history],
                          True,
                          _block=True)
def create_plots(begin, end, stride):
    """ 
    Plot the function double, square, and exp
    from beginning to end using the provided stride
    
    The x-coordinates of the plotted points start
    at begin, terminate at end and are spaced by 
    distance stride
    """
    
    # generate x coordinates for plot points
    x_coords = []
    current_x = begin
    while current_x < end:
        x_coords.append(current_x)
        current_x += stride
        
    # compute list of (x, y) coordinates for each function
    double_plot = [(x_val, double(x_val)) for x_val in x_coords]
    square_plot = [(x_val, square(x_val)) for x_val in x_coords]
    exp_plot = [(x_val, exp(x_val)) for x_val in x_coords]
    
    # plot the list of points
    simpleplot.plot_lines("Plots of three functions", 600, 400, "x", "f(x)",
                         [double_plot, square_plot, exp_plot], 
                         True, ["double", "square", "exp"])
Пример #4
0
def create_plots(begin, end, stride):
    """ 
    Plot the function double, square, and exp
    from beginning to end using the provided stride

    The x-coordinates of the plotted points start
    at begin, terminate at end and are spaced by 
    distance stride
    """

    # generate x coordinates for plot points
    x_coords = []
    current_x = begin
    while current_x < end:
        x_coords.append(current_x)
        current_x += stride

    # compute list of (x, y) coordinates for each function
    exp1_plot = [(x_val, exp1(x_val)) for x_val in x_coords]
    log1_plot = [(x_val, log1(x_val)) for x_val in x_coords]

    for (x, y) in log1_plot:
        if y > 0: print '(' + str(x) + ',' + str(y) + ')'
    # plot the list of points
    simpleplot.plot_lines("Plots of three functions", 600, 400, "x", "f(x)",
                         [exp1_plot, log1_plot], 
                         True, ["exp1", "log1"])
Пример #5
0
def create_plots(begin, end, stride):
    """ 
    Plot the function double, square, and exp
    from beginning to end using the provided stride
    
    The x-coordinates of the plotted points start
    at begin, terminate at end and are spaced by 
    distance stride
    """

    # generate x coordinates for plot points
    x_coords = []
    current_x = begin
    while current_x < end:
        x_coords.append(current_x)
        current_x += stride

    # compute list of (x, y) coordinates for each function
    double_plot = [(x_val, double(x_val)) for x_val in x_coords]
    square_plot = [(x_val, square(x_val)) for x_val in x_coords]
    exp_plot = [(x_val, exp(x_val)) for x_val in x_coords]

    # plot the list of points
    simpleplot.plot_lines("Plots of three functions", 600, 400, "x", "f(x)",
                          [double_plot, square_plot, exp_plot], True,
                          ["double", "square", "exp"])
Пример #6
0
def run_simulations():
    """
    Run simulations for several possible bribe increments

    The plot of the resulting graph approaches a straight line as the number of days
    increase. This observation signals that the function might be a polynomial function.
    
    Compute the slope of this line and round it to the nearest integer to estimate
    the degree of this polynomial.

    Use two of those points with the formula above (m = rise/run = (y2-y1)/(x2-x1))

    >>> y=8.699514748210191-8.006367567650246
    >>> y
    0.6931471805599454
    >>> x=3.4011973816621555-2.995732273553991
    >>> x
    0.4054651081081646
    >>> 0.6931471805599454/0.4054651081081646
    1.709511291351454
    >>>round(1.709511291351454) ~ 2

    """
    plot_type = LOGLOG
    days = 35
    inc_1000 = greedy_boss(days, 1000, plot_type)
    print inc_1000
    simpleplot.plot_lines("Greedy boss", 600, 600, "days", "total earnings",
                          [inc_1000], False, ["Bribe increment = 1000"])
Пример #7
0
def q1_legend(low, high):
    xvals = []
    slow = []
    fast = []
    for num_clusters in range(low, high, 100):
        xvals.append(num_clusters)
        cluster_list = gen_random_clusters(num_clusters)

        time1 = time.time()
        slow_closest_pair(cluster_list)
        time2 = time.time()
        slow.append(time2 - time1)

        time1 = time.time()
        fast_closest_pair(cluster_list)
        time2 = time.time()
        fast.append(time2 - time1)

    yvals1 = slow
    yvals2 = fast
    curve1 = [[xvals[idx], yvals1[idx]] for idx in range(len(xvals))]
    curve2 = [[xvals[idx], yvals2[idx]] for idx in range(len(xvals))]
    print curve1
    print curve2
    simpleplot.plot_lines("The running times of closest-pair-find functions",
                          800, 600, "the number of initial clusters",
                          "the running time of the function in seconds",
                          [curve1, curve2], True,
                          ["slow_closest_pair", "fast_closest_pair"])
Пример #8
0
def q10_legend(DATA_URL):
    data_table = load_data_table(DATA_URL)
    singleton_list = []
    hierarchical_cluster_list = []
    for line in data_table:
        singleton_list.append(
            alg_cluster.Cluster(set([line[0]]), line[1], line[2], line[3],
                                line[4]))
        hierarchical_cluster_list.append(
            alg_cluster.Cluster(set([line[0]]), line[1], line[2], line[3],
                                line[4]))

    xvals = []
    yvals1 = []
    yvals2 = []
    for num_clusters in range(20, 5, -1):
        xvals.append(num_clusters)
        hierarchical_cluster_list = alg_project3_solution.hierarchical_clustering(
            hierarchical_cluster_list, num_clusters)
        yvals1.append(compute_distortion(hierarchical_cluster_list,
                                         data_table))
        yvals2.append(
            compute_distortion(
                alg_project3_solution.kmeans_clustering(
                    singleton_list, num_clusters, 5), data_table))
    curve1 = [[xvals[idx], yvals1[idx]] for idx in range(len(xvals))]
    curve2 = [[xvals[idx], yvals2[idx]] for idx in range(len(xvals))]
    simpleplot.plot_lines(
        "The distortion of output clusters uesd " + str(len(data_table)) +
        "-county data set", 800, 600, "the number of output clusters",
        "the distortion associated with each output clustering",
        [curve1, curve2], True, ["hierarchical cluster", "kmeans cluster"])
Пример #9
0
def plot_performance(plot_length, plot_type):
    """
    Build list that estimates running of physics update for ball_list
    """

    simulation = Simulation()
    plot = []

    for index in range(10, plot_length):

        # add a ball to ball_list
        while simulation.num_balls() != index:
            simulation.add_ball([
                random.randrange(CANVAS_WIDTH),
                random.randrange(CANVAS_HEIGHT)
            ])

        # run update for all balls, num_updates times
        start_time = time.time()
        simulation.update()
        estimated_time = (time.time() - start_time) / float(NUM_UPDATES)

        if plot_type == TIME_PLOT:
            plot.append([index, estimated_time])
        else:
            plot.append([index, estimated_time / (index)])

    if plot_type == TIME_PLOT:
        simpleplot.plot_lines("Running time for linear update", 400, 400,
                              "# balls", "time to update", [plot])
    else:
        simpleplot.plot_lines("Comparison of running time to linear function",
                              400, 400, "# balls", "ratio", [plot])
Пример #10
0
def run_simulations():
    """
    Run simulations for several possible bribe increments

    Do some manual experimentation to locate an expression in d that grows at a similar rate
    to total salary earned when bribe_cost_increment == 0. 

    Compare the growth rates of the expressions below to the growth rate of total salary earned
    using the plotting technique described in the Math notes. 

    Which expression grows at approximately the same rate as total salary earned? 

    e**0.095d or e**9.5d or 9.5*d**4 or 95*d**2

    Answer: 9.5*d**4

    Find prove for question 8:
    https://class.coursera.org/principlescomputing1-004/forum/thread?thread_id=537
    """
    plot_type = LOGLOG
    days = 120
    inc_1000 = greedy_boss(days, 0, plot_type)
    inc_fx = fx(days, plot_type)
    simpleplot.plot_lines("Greedy boss", 600, 600, "days", "total earnings",
                          [inc_1000, inc_fx], False, [
                              "Bribe increment = 1000",
                              "Fx Q8 Simulation",
                          ])
def plot_performance(plot_length, plot_type):
    """
    Build list that estimates running of physics update for ball_list
    """

    simulation = Simulation()
    plot = []
    
    for index in range(10, plot_length):
        
        # add a ball to ball_list
        while simulation.num_balls() != index:
            simulation.add_ball([random.randrange(CANVAS_WIDTH), random.randrange(CANVAS_HEIGHT)])
        
        # run update for all balls, num_updates times
        start_time = time.time()
        simulation.update()
        estimated_time = (time.time() - start_time) / float(NUM_UPDATES)
        
        if plot_type == TIME_PLOT:
            plot.append([index, estimated_time])
        else:
            plot.append([index, estimated_time / (index)])
    
    if plot_type == TIME_PLOT:
        simpleplot.plot_lines("Running time for linear update", 400, 400, "# balls", "time to update", [plot])    
    else:
        simpleplot.plot_lines("Comparison of running time to linear function", 400, 400, "# balls", "ratio", [plot])    
Пример #12
0
def analyze_running_time():
    fast_target_order_list = []
    targeted_order_list = []
    xvals = []
    m = 5
    for n in range(10, 1000, 10):
        upa_graph = make_upa_graph(n, m)
        xvals.append(n)

        time1 = time.time()
        fast_target_order(upa_graph)
        time2 = time.time()
        fast_target_order_list.append(time2 - time1)

        time1 = time.time()
        targeted_order(upa_graph)
        time2 = time.time()
        targeted_order_list.append(time2 - time1)

    curve1 = [[xvals[idx], fast_target_order_list[idx]]
              for idx in range(len(xvals))]
    curve2 = [[xvals[idx], targeted_order_list[idx]]
              for idx in range(len(xvals))]
    simpleplot.plot_lines("CodeSkulptor running times ", 800, 600,
                          "the number of nodes", "running time",
                          [curve1, curve2], False,
                          ["fast_target_order", "targeted_order"])
Пример #13
0
def q1_legend(low, high):
    xvals = []
    slow = []
    fast = []
    for num_clusters in range(low, high, 100):
        xvals.append(num_clusters)
        cluster_list = gen_random_clusters(num_clusters)
        
        time1 = time.time()
        slow_closest_pair(cluster_list)
        time2 = time.time()
        slow.append(time2 - time1)
        
        time1 = time.time()
        fast_closest_pair(cluster_list)
        time2 = time.time()
        fast.append(time2 - time1)
        
    yvals1 = slow
    yvals2 = fast
    curve1 = [[xvals[idx], yvals1[idx]] for idx in range(len(xvals))]
    curve2 = [[xvals[idx], yvals2[idx]] for idx in range(len(xvals))]
    print curve1
    print curve2
    simpleplot.plot_lines("The running times of closest-pair-find functions", 
                          800, 600, "the number of initial clusters",
                          "the running time of the function in seconds",
                          [curve1, curve2], True, 
                          ["slow_closest_pair", 
                           "fast_closest_pair"])
def run_simulations():
    """
    Run simulations for several possible bribe increments
    """
    plot_type = LOGLOG
    days = 120
    inc_0 = greedy_boss(days, 0, plot_type)
    graph_1 = []
    graph_2 = []
    graph_3 = []
    graph_4 = []
    for point in inc_0:
        d = math.exp(point[0])
        graph_1.append((point[0], math.log(math.exp(0.095 * d))))
        #graph_2.append((point[0], math.log(95 * d * d)))
        #graph_3.append((point[0], math.log(math.exp(9.5 * d))))
        #graph_4.append((point[0], math.log(9.5 * d * d * d *d)))
    
    #inc_500 = greedy_boss(days, 500, plot_type)
    #inc_1000 = greedy_boss(days, 1000, plot_type)
    #inc_2000 = greedy_boss(days, 2000, plot_type)
#    simpleplot.plot_lines("Greedy boss", 600, 600, "days", "total earnings", 
#                          [inc_0, inc_500, inc_1000, inc_2000], False,
#                         ["Bribe increment = 0", "Bribe increment = 500",
#                          "Bribe increment = 1000", "Bribe increment = 2000"]
#                         )
    simpleplot.plot_lines("Greedy boss", 600, 600, "days", "total earnings", 
                          [inc_0, graph_1], False,
                         ["Bribe increment = 0", "graph_1"]
                         )
    x1 = -1
    y1 = -1
Пример #15
0
def target_attack_legend():
    """
    Plot three curves with legends
    """
    network_ugraph = load_graph(NETWORK_URL)
    num_network_nodes = len(network_ugraph)
    num_network_edges = sum(map(len, network_ugraph.values())) / 2
    max_network_edges = num_network_nodes * (num_network_nodes - 1) / 2
    prop = num_network_edges * 1.0 / max_network_edges

    er_graph = make_er_graph(num_network_nodes, prop)
    upa_graph = make_upa_graph(num_network_nodes, 2)

    yvals1 = target_attack(network_ugraph)
    yvals2 = target_attack(er_graph)
    yvals3 = target_attack(upa_graph)
    xvals = range(max(len(yvals1), len(yvals2), len(yvals3)))
    curve1 = [[xvals[idx], yvals1[idx]] for idx in range(len(yvals1))]
    curve2 = [[xvals[idx], yvals2[idx]] for idx in range(len(yvals2))]
    curve3 = [[xvals[idx], yvals3[idx]] for idx in range(len(yvals3))]

    simpleplot.plot_lines("Resilience of graphs under targeted attack", 800,
                          600, "the number of nodes removed",
                          "the size of the largest connect component",
                          [curve1, curve2, curve3], False, [
                              "network_ugraph", "er_graph (p = " + str(prop) +
                              ")", "upa_graph (m = 2)"
                          ])
Пример #16
0
def init():  # type: () -> None
    """Init list of shapes, corresponding to the current step."""
    global FPS  # pylint: disable=global-statement
    global FREEZED  # pylint: disable=global-statement
    global NB_SHAPES  # pylint: disable=global-statement
    global NB_FRAMES_DRAWED  # pylint: disable=global-statement
    global NB_SECONDS  # pylint: disable=global-statement
    global SHAPES  # pylint: disable=global-statement
    global TO_NEXT_STEP  # pylint: disable=global-statement

    if len(LIST_NB_SHAPES) == 0:
        TIMER.stop()

        final_result = dict_to_ordered_list(RESULTS)

        print('Results: {' + ', '
              .join(['%d: %d' % result for result in final_result]) + '}')

        try:
            FRAME.stop()
        except Exception as e:  # pylint: disable=broad-except
            # To avoid failed when run with simpleguitk
            print('FRAME.stop():' + str(e))

        if PLOT:
            try:
                simpleplot.plot_lines('Stress Balls', 800, 650,
                                      '# balls', 'FPS',
                                      (final_result, ), True)
                if SIMPLEGUICS2PYGAME:
                    simpleplot._block()  # pylint: disable=protected-access
            except Exception as e:  # pylint: disable=broad-except
                # To avoid fail if no simpleplot
                print('simpleplot.plot_lines():' + str(e))

        flush()

        return

    if LIST_NB_SHAPES:
        NB_SHAPES = LIST_NB_SHAPES.pop(0)

    assert isinstance(NB_SHAPES, int)

    FPS = 0
    FREEZED = False
    NB_FRAMES_DRAWED = 0
    NB_SECONDS = 0
    TO_NEXT_STEP = False

    SHAPES = tuple([Shape((47 + n % (WIDTH - 100),
                           47 + n % (HEIGHT - 100)),  # position
                          19 + n % 11,  # radius
                          n_to_rgba((n + 1) % len(RGB_COLORS),
                                    .2 + float(n % 13) / 15),  # color of border  # noqa
                          n_to_rgba((n + 2) % len(RGB_COLORS),
                                    .2 + float((n + 3) % 14) / 17),  # fill color  # noqa
                          (3 + n % 7, 2 + n % 5),  # velocity
                          (n + 2) % 6)  # shape
                    for n in range(NB_SHAPES)])
Пример #17
0
def make_plot(fun1, fun2, plot_length):
    """
    Create a plot relating the growth of fun1 vs. fun2
    """
    answer = []
    for index in range(10, plot_length):
        answer.append([index, fun1(index) / float(fun2(index))])
    simpleplot.plot_lines("Growth rate comparison", 300, 300, "n", "f(n)/g(n)", [answer])
Пример #18
0
def test():
    """
    Testing code for resources_vs_time
    """
    ## q10, q11
    data1 = resources_vs_time(-1, 45)
    data2 = resources_vs_time(1.0, 100)
    simpleplot.plot_lines("Growth", 600, 600, "time", "total resources", [data1, data2])
Пример #19
0
def test():
    """
    Testing code for resources_vs_time
    """
    data1 = resources_vs_time(0.5, 20)
    data2 = resources_vs_time(1.5, 10)
    print data1
    print data2
    simpleplot.plot_lines("Growth", 600, 600, "time", "total resources", [data1, data2])
Пример #20
0
def make_plot(fun1, fun2, plot_length):
    """
    Create a plot relating the growth of fun1 vs. fun2
    """
    answer = []
    for index in range(10, plot_length):
        answer.append([index, fun1(index) / float(fun2(index))])
    simpleplot.plot_lines("Growth rate comparison", 300, 300, "n", "f(n)/g(n)",
                          [answer])
Пример #21
0
def make_plot(fun1, fun2, plot_length):
    points = []
    fun1_points = [(x, fun1(x)) for x in range(1, plot_length)]
    fun2_points = [(x, fun2(x)) for x in range(1, plot_length)]
    for x in range(1, plot_length):
        points.append((x, float(fun1(x)) / fun2(x)))
    simpleplot.plot_lines("Growth rate comparison", 400, 600, "x",
                          "f(x) / g(x)", [points, fun1_points, fun2_points],
                          True, ["f(x) / g(x)", "f(x)", "g(x)"])
def test():
    """
    Testing code for resources_vs_time
    """
    data1 = resources_vs_time(1, 60)

    print data1

    simpleplot.plot_lines("Growth", 600, 600, "time", "total resources", [data1])
Пример #23
0
def test():
    """
    Testing code for resources_vs_time
    """
    data1 = resources_vs_time(0.0, 50)
    data2 = resources_vs_time(1.0, 10)
    data3 = resources_vs_time(2.0, 10)
    data4 = resources_vs_time(0.5, 10)
    print data1
    simpleplot.plot_lines("Growth", 600, 600, "time", "total resources", [data1])
Пример #24
0
def test2():
    """
    Testing code for resources_vs_time
    """
    data1 = resources_vs_time(1.0, 50)
    data2 = resources_vs_time2(0.15, 100)
    print(data1)
    print(data2)
    simpleplot.plot_lines("Growth", 600, 600, "time", "total resources",
                          [data1, data2])
Пример #25
0
def plot_pred_prey(populations, pred_name, prey_name):
    """
    This function plots the prey populations (x-axis) vs. 
    the predator populations (y-axis).
    """
    newlist = []
    for item in populations:
        newlist.append((item[1], item[2]))
    simpleplot.plot_lines('Populations', 400, 400, prey_name, pred_name,
                          [newlist])
Пример #26
0
def test():
    """
    Testing code for resources_vs_time
    """
    data1 = resources_vs_time(0.5, 20)
    data2 = resources_vs_time(1.5, 10)
    print data1
    print data2
    simpleplot.plot_lines("Growth", 600, 600, "time", "total resources",
                          [data1, data2])
def plot_example(length):
    global counter
    poly_func = []
    fib_func = []
    for iter in range(length):
        counter = 0
        poly_func.append([iter, 2 * iter - 1])
        answer = memoized_fib(iter, {0 : 0, 1 : 1})
        fib_func.append([iter, counter])
    simpleplot.plot_lines("Recurrence solutions", 600, 600, "number", "value", [poly_func, fib_func], legends = ["Ideal. Plot", "Fib plot"])
Пример #28
0
def plot_example(length):
    """
    Plot computed solutions to recurrences
    """
    rec_plot = []
    sol_plot = []
    sol = SOL_DICT[INDEX]
    for num in range(2, length):
        rec_plot.append([num, recur(num)])
        sol_plot.append([num, sol(num)])
    simpleplot.plot_lines("Recurrence solutions", 600, 600, "number", "value", [rec_plot, sol_plot], False, ["rec_plot", "sol_plot"])
def run_strategy(strategy_name, time, strategy):
    """
    Run a simulation for the given time with one strategy.
    """
    state = simulate_clicker(provided.BuildInfo(), time, strategy)
    print "\n", strategy_name, ":\n", state

    # Plot total cookies over time
    history = state.get_history()
    history = [(item[0], item[3]) for item in history]
    simpleplot.plot_lines(strategy_name, 1000, 400, "Time", "Total Cookies", [history], True)
def init():
    global balls
    global fps
    global freezed
    global nb_balls
    global nb_frames_drawed
    global nb_seconds
    global results
    global to_next_step

    if len(list_nb_balls) == 0:
        timer.stop()

        results = dict_to_ordered_list(results)

        print('Results: {' +
              ', '.join(['%d: %d' % result for result in results]) + '}')

        try:
            frame.stop()
        except Exception as e:  # to avoid simpleguitk failed
            print('frame.stop():' + str(e))

        try:
            simpleplot.plot_lines('Stress Balls', 800, 650, '# balls', 'FPS',
                                  (results, ), True)
            if SIMPLEGUICS2PYGAME:
                simpleplot._block()
        except Exception as e:  # to avoid fail if no simpleplot
            print('simpleplot.plot_lines():' + str(e))

        return

    if list_nb_balls:
        nb_balls = list_nb_balls.pop(0)

    fps = 0
    freezed = False
    nb_frames_drawed = 0
    nb_seconds = 0
    to_next_step = False

    balls = tuple([
        Ball(
            [47 + n % (WIDTH - 100), 47 + n % (HEIGHT - 100)],  # position
            19 + n % 11,  # radius
            n_to_rgba((n + 1) % len(RGB_COLORS),
                      .2 + float(n % 13) / 15),  # color of border
            n_to_rgba((n + 2) % len(RGB_COLORS), .2 + float(
                (n + 3) % 14) / 17),  # fill color
            [3 + n % 7, 2 + n % 5],  # velocity
            (n + 2) % 6)  # shape
        for n in range(nb_balls)
    ])
Пример #31
0
def test():
    """
    Testing code for resources_vs_time
    """
    data1 = resources_vs_time(0.0, 50)
    data2 = resources_vs_time(0.5, 40)
    data3 = resources_vs_time(1.0, 30)
    data4 = resources_vs_time(2.0, 20)
    # print data1
    # print data2
    simpleplot.plot_lines("Growth", 600, 600, "time", "total resources", [data1, data2, data3, data4])
def plot_example(length):
    """
    Plot computed solutions to recurrences
    """
    rec_plot = []
    sol_plot = []
    sol = SOL_DICT[INDEX]
    for num in range(2, length):
        rec_plot.append([num, recur(num)])
        sol_plot.append([num, sol(num)])
    simpleplot.plot_lines("Recurrence solutions", 600, 600, "number", "value", [rec_plot, sol_plot], legends = ["Approx. Plot", "Ideal plot"])
def run_strategy(strategy_name, time, strategy):
    """
    Run a simulation for the given time with one strategy.
    """
    state = simulate_clicker(provided.BuildInfo(), time, strategy)
    print strategy_name, ":", state

    # Plot total cookies over time
    history = state.get_history()
    history_item0_item3 = [(item[0], item[3]) for item in history]
    simpleplot.plot_lines(strategy_name, 1000, 400, 'Time', 'Total Cookies',
                          [history_item0_item3], True)
def test():
    """
    Testing code for resources_vs_time
    """
    loop = 20
    data1 = resources_vs_time(1.0, loop)
    #data2 = resources_vs_time(0.5, loop)
    #data3 = resources_vs_time(1.0, loop)
    #data4 = resources_vs_time(2.0, loop)
    print data1
    #print data2
    simpleplot.plot_lines("Growth", 600, 600, "time", "total resources", [data1])
def init():
    global balls
    global fps
    global freezed
    global nb_balls
    global nb_frames_drawed
    global nb_seconds
    global results
    global to_next_step

    if len(list_nb_balls) == 0:
        timer.stop()

        results = dict_to_ordered_list(results)

        print('Results: {' + ', '
              .join(['%d: %d' % result for result in results]) + '}')

        try:
            frame.stop()
        except Exception as e:  # to avoid simpleguitk failed
            print('frame.stop():' + str(e))

        try:
            simpleplot.plot_lines('Stress Balls', 800, 650,
                                  '# balls', 'FPS',
                                  (results, ), True)
            if SIMPLEGUICS2PYGAME:
                simpleplot._block()
        except Exception as e:  # to avoid fail if no simpleplot
            print('simpleplot.plot_lines():' + str(e))

        return

    if list_nb_balls:
        nb_balls = list_nb_balls.pop(0)

    fps = 0
    freezed = False
    nb_frames_drawed = 0
    nb_seconds = 0
    to_next_step = False

    balls = tuple([Ball([47 + n % (WIDTH - 100),
                         47 + n % (HEIGHT - 100)],  # position
                        19 + n % 11,  # radius
                        n_to_rgba((n + 1) % len(RGB_COLORS),
                                  .2 + float(n % 13)/15),  # color of border
                        n_to_rgba((n + 2) % len(RGB_COLORS),
                                  .2 + float((n + 3) % 14)/17),  # fill color
                        [3 + n % 7, 2 + n % 5],  # velocity
                        (n + 2) % 6)  # shape
                   for n in range(nb_balls)])
Пример #36
0
def run_simulations():
    """
    Run simulations for several possible bribe increments
    """
    plot_type = LOGLOG
    days = 150
    inc_0 = greedy_boss(days, 0, plot_type)
    inc_500 = greedy_boss(days, 500, plot_type)
    inc_1000 = greedy_boss(days, 1000, plot_type)
    inc_2000 = greedy_boss(days, 2000, plot_type)
    simpleplot.plot_lines("Greedy boss", 600, 600, "days", "total earnings",
                          [inc_0], False, ["Bribe increment = 0"])
Пример #37
0
def plot_time_populations(populations, pred_name, prey_name):
    """
    This function plots the predator and prey populations vs. 
    elapsed time.
    """
    pred_pops = []
    prey_pops = []
    for elapsedtime, preypop, predpop in populations:
        pred_pops.append((elapsedtime, predpop))
        prey_pops.append((elapsedtime, preypop))

    simpleplot.plot_lines('Populations', 400, 300, 'year', 'populations',
                          [pred_pops, prey_pops], True, [pred_name, prey_name])
Пример #38
0
def run():
    """
    Run the simulator.
    """
    cursor_broken = run_strategy("Cursor", SIM_TIME, strategy_cursor_broken)
    cheap = run_strategy("Cheap", SIM_TIME, strategy_cheap)
    expensive = run_strategy("Expensive", SIM_TIME, strategy_expensive)
    best = run_strategy("Best", SIM_TIME, strategy_best)

    simpleplot.plot_lines("Comparison of strategies", 1000, 400, 'Time',
                          'Total Cookies',
                          [cursor_broken, cheap, expensive, best], True,
                          ["cursor_broken", "cheap", "expensive", "best"])
def run_simulations():
    """
    Run simulations for several possible bribe increments
    """
    plot_type = STANDARD
    days = 80
    inc_0 = greedy_boss(days, 0, plot_type)
    #inc_500 = greedy_boss(days, 500, plot_type)
    #inc_1000 = greedy_boss(days, 1000, plot_type)
    #inc_2000 = greedy_boss(days, 2000, plot_type)
    simpleplot.plot_lines("Greedy boss", 600, 600, "days", "total earnings",
                          [inc_0], False,
                         ["Bribe increment = 0"])
Пример #40
0
def run_strategy(strategy_name, time, strategy):
    """
    Runs a simulation for the given time with the given strategy. Prints final
    strategy statistics to the console and graphs the time versus total cookies.
    """
    state = simulate_clicker(provided.BuildInfo(), time, strategy)
    print strategy_name, " Strategy:", state

    # Plot total cookies over time
    history = state.get_history()
    history = [(item[0], item[3]) for item in history]
    simpleplot.plot_lines(strategy_name, 1000, 400, 'Time', 'Total Cookies', [
        history], True)
def run_strategy(strategy_name, time, strategy):
    """
    Run a simulation for the given time with one strategy.
    """
    state = simulate_clicker(provided.BuildInfo(), time, strategy)
    print strategy_name, ":", state

    # Plot total cookies over time
    # Uncomment out the lines below to see a plot of total cookies vs. time
    # Be sure to allow popups, if you do want to see it
    history = state.get_history()
    history = [(item[0], item[3]) for item in history]
    simpleplot.plot_lines(strategy_name, 1000, 400, 'Time', 'Total Cookies', [history], True)
def run_example():
    """
    Load a data table, compute a list of clusters and 
    plot a list of clusters

    Set DESKTOP = True/False to use either matplotlib or simplegui
    """
    data_table = load_data_table(DATA_896_URL)

    singleton_list = []
    for line in data_table:
        singleton_list.append(
            alg_cluster.Cluster(set([line[0]]), line[1], line[2], line[3],
                                line[4]))

    #cluster_list = sequential_clustering(singleton_list, 15)
    #print "Displaying", len(cluster_list), "sequential clusters"

    #cluster_list = alg_project3_solution.hierarchical_clustering(singleton_list, 16)
    #print "Displaying", len(cluster_list), "hierarchical clusters"

    #cluster_list = alg_project3_solution.kmeans_clustering(singleton_list, 16, 5)
    #print "Displaying", len(cluster_list), "k-means clusters"

    kmeans = []
    for clusters_number in xrange(6, 21):
        cluster_list = alg_project3_solution.kmeans_clustering(
            singleton_list, clusters_number, 5)
        kmeans.append([
            clusters_number, 0.0 +
            alg_project3_solution.compute_distortion(cluster_list, data_table)
        ])

    #cluster_list = alg_project3_solution.hierarchical_clustering(singleton_list, 20)
    #hierarchical = [[20, alg_project3_solution.compute_distortion(cluster_list, data_table)]]
    hierarchical = []
    for clusters_number in xrange(20, 5, -1):
        cluster_list = alg_project3_solution.hierarchical_clustering(
            singleton_list, clusters_number)
        hierarchical.append([
            clusters_number, 0.0 +
            alg_project3_solution.compute_distortion(cluster_list, data_table)
        ])
    hierarchical.reverse()
    #print hierarchical[10], kmeans[10]

    simpleplot.plot_lines(
        "Distortion of the clusterings produced by hierarchical and k-means metods on 896 county data set",
        800, 600, "Number of clusters n [6 .. 20]", "Distortion",
        [hierarchical, kmeans], False,
        ["Hierarchical clustering", "k-means clustering with 5 iterations"])
Пример #43
0
def run():
    """
    Run the simulator.
    """
    #    run_strategy("Cursor", SIM_TIME, strategy_cursor_broken)

    # Add calls to run_strategy to run additional strategies
    plots = []
    plots.append(run_strategy("Cheap", 600, strategy_cheap))
    plots.append(run_strategy("Expensive", 600, strategy_expensive))
    plots.append(run_strategy("Best", 600, strategy_best))
    simpleplot.plot_lines("Growth rate", 1000, 400, 'Time', 'Total Cookies',
                          plots, True, ["Cheap", "Expensive", "Best"])
    return plots
Пример #44
0
def test():
    """
    Testing code for resources_vs_time
    """
    data1 = resources_vs_time(0.5, 20)
    data2 = resources_vs_time(1.5, 10)
    data3 = resources_vs_time(0.0, 10)
    data4 = resources_vs_time(1.0, 10)
    print(data1)
    print(data2)
    print(data3)
    print(data4)
    simpleplot.plot_lines("Growth", 600, 600, "time", "total resources",
                          [data1, data2, data3, data4])
def test():
    """
    Testing code for resources_vs_time
    """
    data1 = resources_vs_time(0.5, 20, STANDARD)
    data2 = resources_vs_time(1.5, 10, STANDARD)
    #print data1
    #print data2
    
    #test1 = [[1.0, 1], [1.75, 2.5], [2.41666666667, 4.5], [3.04166666667, 7.0], [3.64166666667, 10.0], [4.225, 13.5], [4.79642857143, 17.5], [5.35892857143, 22.0], [5.91448412698, 27.0], [6.46448412698, 32.5], [7.00993867244, 38.5], [7.55160533911, 45.0], [8.09006687757, 52.0], [8.62578116328, 59.5], [9.15911449661, 67.5], [9.69036449661, 76.0], [10.2197762613, 85.0], [10.7475540391, 94.5], [11.2738698286, 104.5], [11.7988698286, 115.0]]
    #test2 = [[1.0, 1], [2.25, 3.5], [3.58333333333, 7.5], [4.95833333333, 13.0], [6.35833333333, 20.0], [7.775, 28.5], [9.20357142857, 38.5], [10.6410714286, 50.0], [12.085515873, 63.0], [13.535515873, 77.5]]
    
    print "\n###############  Question 1  ##################"
    question1_a = resources_vs_time(0.0, 10, STANDARD)
    question1_b = resources_vs_time(1.0, 10, STANDARD)
    #print question1_a
    print question1_b
    #simpleplot.plot_lines("Growth", 600, 600, "time", "total resources", [data1, data2])
    #simpleplot.plot_lines("Growth", 600, 600, "time", "total resources", [test1, test2])

    
    print "\n###############  Question 2  ##################"
    question2_a = resources_vs_time(0.0, 100, STANDARD)
    question2_b = resources_vs_time(0.5, 18, STANDARD)
    question2_c = resources_vs_time(1.0, 14, STANDARD)
    question2_d = resources_vs_time(2.0, 10, STANDARD)
    #print question2_a
    #print question2_b
    #print question2_c
    #print question2_d
    simpleplot.plot_lines("Growth", 600, 600, "time", "total resources", [question2_a, question2_b, question2_c, question2_d])
    
    
    print "\n###############  Question 3  ##################"
    question3 = resources_vs_time(0.0, 10, LOGLOG)
    #print question3
    #simpleplot.plot_lines("Growth", 600, 600, "time", "total resources", [question3])
    
    
    print "\n###############  Question 7  ##################"
    question7 = resources_vs_time(1.0, 10, LOGLOG)
    print question7
    #simpleplot.plot_lines("Growth", 600, 600, "time", "total resources", [question1_b])
      
    print "\n###############  Question 9  ##################"
    question9a = resources_vs_time(1.0, 10, STANDARD)
    question9b = resources_vs_time(1.0, 20, STANDARD)
    print question9a
    print question9b
def plot(diagraph):
    """
    plot a diagraph
    """
    values = diagraph.values()
    summ = float(sum(values))
    logdiag = dict()
    for key,value in diagraph.items():
        if key != 0:
            key = math.log(key)
        value = math.log(value / summ)
        logdiag[key] = value
        
    simpleplot.plot_lines('A normalized distribution on a log/log scale', 400, 300,
                          'In degrees', 'Number of Nodes', [logdiag], True)
Пример #47
0
def run_simulations():
    """ Run simulations for several possible bribe increments """
    plot_type = LOGLOG  # we choose the logarithmic plot
    days = 70
    inc_0 = greedy_boss(days, 0, plot_type)
    inc_500 = greedy_boss(days, 500, plot_type)
    inc_1000 = greedy_boss(days, 1000, plot_type)
    inc_2000 = greedy_boss(days, 2000, plot_type)
    simpleplot.plot_lines(
        "Greedy boss", 600, 600, "days", "total earnings",
        [inc_0, inc_500, inc_1000, inc_2000], False, [
            "Bribe increment = 0", "Bribe increment = 500",
            "Bribe increment = 1000", "Bribe increment = 2000"
        ])
    simpleplot._block()
Пример #48
0
def test():
    """
    Testing code for resources_vs_time
    """
    #data1 = resources_vs_time(0.5, 20)
    #data2 = resources_vs_time(1.5, 10)
    data1 = resources_vs_time(1.0, 60)
    data2 = rvt(1.0, 60)
    #data3 = resources_vs_time(1.0, 10)
    #data4 = resources_vs_time(2.0, 5)
    print data1
    #print data2
    #print data3
    #print data4
    simpleplot.plot_lines("Growth", 600, 600, "time", "total resources", [data1, data2])
Пример #49
0
def test():
    """
    Testing code for resources_vs_time
    """
    data1 = resources_vs_time(0.0, 10)
    data2 = resources_vs_time(0.5, 10)
    data3 = resources_vs_time(1.0, 10)
    data4 = resources_vs_time(2.0, 10)
    data5 = cookie_clicker(10)
    print data1
    print data2
    print data3
    print data4
    print data5
    simpleplot.plot_lines("Growth", 600, 600, "time", "total resources", [data1, data2, data3, data4, data5])
def plot_example(length):
    global counter
    poly_func = []
    fib_func = []
    for iter in range(length):
        counter = 0
        poly_func.append([iter, 2 * iter - 1])
        answer = memoized_fib(iter, {0: 0, 1: 1})
        fib_func.append([iter, counter])
    simpleplot.plot_lines("Recurrence solutions",
                          600,
                          600,
                          "number",
                          "value", [poly_func, fib_func],
                          legends=["Ideal. Plot", "Fib plot"])
Пример #51
0
def plot_fairness(side, num_sides, max_trials):
    """
    Plot the mathematical probability for an outcome vs.
    computed estimate
    """
    plot = []
    for num_trials in range(TRIAL_STRIDE, max_trials, TRIAL_STRIDE):
        side_count = 0
        for _ in range(num_trials):
            if roll_die(num_sides) == side:
                side_count += 1
        mathematical = 1.0 / num_sides
        computed = float(side_count) / num_trials
        plot.append([num_trials, mathematical - computed])
    simpleplot.plot_lines("Fairness test", 400, 300, "number of rolls",
                          "mathematical - computed", [plot], False, ["plot"])
def create_plots_2(begin, end, stride):
    
    x_coords = []
    current_x = begin
    while current_x < end:
        x_coords.append(current_x)
        current_x += stride
        
    func1_plot = [(x, func1(x)) for x in x_coords]
    func2_plot = [(x, func2(x)) for x in x_coords]
    func3_plot = [(x, func3(x)) for x in x_coords]
    func4_plot = [(x, func4(x)) for x in x_coords]
    # plot the list of points
    simpleplot.plot_lines("Plots of four functions", 600, 400, "x", "f(x)",
                         [func1_plot, func2_plot, func3_plot, func4_plot], 
                         True, ["1", "2", "3", "4"])
Пример #53
0
def plot_fairness(side, num_sides, max_trials):
    """ 
    Plot the mathematical probability for an outcome vs. 
    computed estimate 
    """ 
    plot = [] 
    for num_trials in range(TRIAL_STRIDE, max_trials, TRIAL_STRIDE): 
        side_count = 0 
        for _ in range(num_trials): 
            if roll_die(num_sides) == side: 
                side_count += 1
        mathematical = 1.0 / num_sides 
        computed = float(side_count) / num_trials 
        plot.append([num_trials, mathematical - computed]) 
    simpleplot.plot_lines("Fairness test", 400, 300,
               "number of rolls", "mathematical - computed", [plot]) 
Пример #54
0
def run_simulations():
    """
    Run simulations for several possible bribe increments
    """
    plot_type = LOGLOG
    days = 70
    inc_0 = greedy_boss(days, 0, plot_type)
    #inc_500 = greedy_boss(days, 500, plot_type)
    inc_1000 = greedy_boss(days, 1000, plot_type)
    print inc_1000
    #inc_2000 = greedy_boss(days, 2000, plot_type)
    #simpleplot.plot_lines("Greedy boss", 600, 600, "days", "total earnings", 
    #                      [inc_0, inc_500, inc_1000, inc_2000], False,
    #                     ["Bribe increment = 0", "Bribe increment = 500",
    #                      "Bribe increment = 1000", "Bribe increment = 2000"])
    simpleplot.plot_lines("Greedy boss", 600, 600, "days", "total earnings", 
                          [ inc_1000], False,
                         ["Bribe increment = 1000"])
def run_strategy(strategy_name, time, strategy):
    """
    Run a simulation with one strategy
    """
    state = simulate_clicker(provided.BuildInfo(), time, strategy)
    print strategy_name, ":", state

    # Plot total cookies over time

    # Uncomment out the lines below to see a plot of total cookies vs. time
    # Be sure to allow popups, if you do want to see it

    history = state.get_history()
    history = [(item[0], item[3]) for item in history]
    
    #"undefined: TypeError: Cannot read property 'document' of undefined"
    #That error is Chrome blocking the pop-up window for simpleplot. Click the
    #red X in the right portion of the URL bar to unblock.
    simpleplot.plot_lines(strategy_name, 1000, 400, 'Time', 'Total Cookies', [history], True)
def run_example():
    """
    Load a data table, compute a list of clusters and 
    plot a list of clusters

    Set DESKTOP = True/False to use either matplotlib or simplegui
    """
    data_table = load_data_table(DATA_896_URL)
    
    singleton_list = []
    for line in data_table:
        singleton_list.append(alg_cluster.Cluster(set([line[0]]), line[1], line[2], line[3], line[4]))
        
    #cluster_list = sequential_clustering(singleton_list, 15)	
    #print "Displaying", len(cluster_list), "sequential clusters"

    #cluster_list = alg_project3_solution.hierarchical_clustering(singleton_list, 16)
    #print "Displaying", len(cluster_list), "hierarchical clusters"
 
    #cluster_list = alg_project3_solution.kmeans_clustering(singleton_list, 16, 5)	
    #print "Displaying", len(cluster_list), "k-means clusters"
    
    kmeans = []
    for clusters_number in xrange(6, 21):
        cluster_list = alg_project3_solution.kmeans_clustering(singleton_list, clusters_number, 5)
        kmeans.append([clusters_number, 0.0 + alg_project3_solution.compute_distortion(cluster_list, data_table)])

    #cluster_list = alg_project3_solution.hierarchical_clustering(singleton_list, 20)
    #hierarchical = [[20, alg_project3_solution.compute_distortion(cluster_list, data_table)]]
    hierarchical = []
    for clusters_number in xrange(20, 5, -1):
        cluster_list = alg_project3_solution.hierarchical_clustering(singleton_list, clusters_number)
        hierarchical.append([clusters_number, 0.0 + alg_project3_solution.compute_distortion(cluster_list, data_table)])
    hierarchical.reverse() 
    #print hierarchical[10], kmeans[10]
 
 
    
    
    simpleplot.plot_lines("Distortion of the clusterings produced by hierarchical and k-means metods on 896 county data set",
                      800, 600, "Number of clusters n [6 .. 20]", "Distortion",
                      [hierarchical, kmeans], False,
                      ["Hierarchical clustering", "k-means clustering with 5 iterations"])            
Пример #57
0
def run_simulations():
    """
    Run simulations for several possible bribe increments
    """
    plot_type = LOGLOG
    days = 150
    inc_0 = greedy_boss(days, 0, plot_type)
    inc_500 = greedy_boss(days, 500, plot_type)
    inc_1000 = greedy_boss(days, 1000, plot_type)
    inc_2000 = greedy_boss(days, 2000, plot_type)
    d1 = [(math.log(day), math.log(95*math.pow(day, 2))) for day in range(days)]
    d2 = [(math.log(day), math.log(math.exp(0.095*day))) for day in range(days)]
    d3 = [(math.log(day), math.log(math.exp(9.5*day))) for day in range(days)]
    d4 = [(math.log(day), math.log(9.5*math.pow(day, 4))) for day in range(days)]    
    simpleplot.plot_lines("Greedy boss", 600, 600, "days", "total earnings", 
                          #[inc_0, inc_500, inc_1000, inc_2000], False,
                          #[inc_1000], False,
                          [inc_0, d1, d2, d4], False,
                         ["Bribe increment = 0", "Bribe increment = 500",
                          "Bribe increment = 1000", "Bribe increment = 2000"])
def build_plot(plot_size, plot_function, plot_type = STANDARD):
    """
    Build plot of the number of increments in mystery function
    """
    global counter
    plot = []
    for input_val in range(2, plot_size):
        counter = 0
        plot_function(input_val)
        if plot_type == STANDARD:
            plot.append([input_val, counter])
        else:
            plot.append([math.log(input_val), math.log(counter)])
    return plot



###############################################
# plottting code
plot_type = STANDARD
plot_size = 40

# Pass name of mystery function in as a parameter
plot1 = build_plot(plot_size, mystery1, plot_type)
plot2 = build_plot(plot_size, mystery2, plot_type)
plot3 = build_plot(plot_size, mystery3, plot_type)
simpleplot.plot_lines("Iteration counts", 600, 600, 
                      "input", "counter", [plot1, plot2, plot3])


    r = []

    for nb in nb_balls:
        r.append((nb, data[nb]))

    datas.append(r)


# Display
print('|'.join(['%4d' % nb for nb in alls_nb]) + '|Environment')

print('----+'*len(alls_nb) + '-----------')
for legend in legends:
    l = []
    for nb in alls_nb:
        fps = all_results[legend].get(nb, None)
        l.append(('%4d' % fps if fps is not None
                  else ' '*4))
    print('|'.join(l) + '|' + legend)


# Graph
try:
    simpleplot.plot_lines('Stress Balls', 800, 650, '# balls', 'FPS',
                          datas, True, legends)
    if SIMPLEGUICS2PYGAME:
        simpleplot._block()
except Exception as e:  # to avoid fail if no simpleplot
    print('!simpleplot.plot_lines():' + str(e))
else:
    PYTHON_VERSION = 'CodeSkulptor'  # http://www.codeskulptor.org/
    MATPLOTLIB_VERSION = ''

datalist = [(1, 2), (2, 3), (5, 4), (8, 3), (9, 2)]
dataset = {1: 3, 2: 4, 5: 5, 8: 4, 9: 3}

filename = None

if SIMPLEGUICS2PYGAME:
    from sys import argv

    if len(argv) == 2:
        filename = argv[1]

simpleplot.plot_lines('Test plot_lines 1', 400, 400, 'x', 'y',
                      (datalist, dataset))

if filename is None:
    simpleplot.plot_lines('Test plot_lines 2', 400, 400, 'x', 'y',
                          (datalist, dataset),
                          True, ('datalist', 'dataset'))
else:
    simpleplot.plot_lines('Test plot_lines 2', 400, 400, 'x', 'y',
                          (datalist, dataset),
                          True, ('datalist', 'dataset'),
                          _filename=filename)

if SIMPLEGUICS2PYGAME and (len(argv) != 2):
    simpleplot._block()