예제 #1
0
def main():
    """
	Main function that initializes size for the random data set.
	Then calls sortTree and sortQueue by passing generated random dataset as input
	function also calculates final time for both operations
	these final times are available in different lists which will be given to graph as input
	"""
    size = 2500
    all_lengths = []
    tree_time = []
    queue_time = []

    for i in range(100):
        input_list = random_dataset(size)
        all_lengths.append(len(input_list))
        start_time_tree = current_milli_time()
        tree_list = sortTree(input_list)
        end_time_tree = current_milli_time()
        final_time_tree = end_time_tree - start_time_tree
        tree_time.append(final_time_tree)
        start_time_queue = current_milli_time()
        queue_list = sortQueue(input_list)
        end_time_queue = current_milli_time()
        final_time_queue = end_time_queue - start_time_queue
        queue_time.append(final_time_queue)

    print('Dataset sizes : ' + str(all_lengths))
    print('Tree time : ' + str(tree_time))
    print('Queue time : ' + str(queue_time))
    plot(all_lengths, tree_time, queue_time)
예제 #2
0
def variance_benchmark(args):
	cmd_lst = [bin, bin_args, file, func] + args[1:]
	print "executing command: %s, please wait..."%(" ".join(cmd_lst))
	res_lst_lst = []
	for j in range(3):
		print "running process at %d time:"%(j)
		p = subprocess.Popen(cmd_lst, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		out, err = p.communicate()
		lines = out.split("\n")

		res_lst = []
		for i in range(len(lines)/2 - 1):
			res_lst.append(int(lines[i*2+1]))
		res_lst_lst.append(res_lst)

	one_time = res_lst_lst[0]
	res = []
	for j in range(len(one_time)):
		tmp = []
		for data in res_lst_lst:
			tmp.append(data[j])
		res.append(statistics.mean(tmp))
	print res

	graph.plot(range(1,int(args[1])+1), res)
예제 #3
0
def draw_columns1(a_lst, height, column_width):
    graph.ouvre_fenetre(height, get_image_width(a_lst, column_width))
    for y in range(height):
        for x in range(get_image_width(a_lst, column_width)):
            if not a_lst[get_column_number(x, column_width)]:
                graph.plot(y, x)
    graph.attend_fenetre()
예제 #4
0
def noir(haut, larg):
    """
    Creation d'une fenetre __noire__ 400x600
    """
    for y in range(haut):  # parcourt les lignes y
        for x in range(larg):  # parcourt les colonnes x
            graph.plot(y, x)
    return
예제 #5
0
def damier(width, height, length):
    for y in range(height):
        offset = 0
        if get_column_number(y, length) % 2 != 0:
            offset = 1
        for x in range(width):
            if get_column_number(x, length) % 2 - offset != 0:
                graph.plot(y, x)
예제 #6
0
def bande_noire_gauche(haut, larg, larg_bande):
    """
    Colorie une bande noire de largeur larg_band a gauche de la fenetre
    """
    for y in range(haut):
        for x in range(larg):
            if x < larg_bande:
                graph.plot(y, x)
    return
예제 #7
0
def rectangle_noir(haut, larg, ymin, ymax, xmin, xmax):
    """
    Colorie un rectangle noir compris entre (xmin, xmax) horizontalement
    et (ymin, ymax) verticalement (fond blanc)
   """
    for y in range(ymin, ymax):
        for x in range(xmin, xmax):
            graph.plot(y, x)
    return
예제 #8
0
def conditional_checkerboard(height, length, box_width):
    for y in range(height):
        for x in range(length):
            if (x % (2 * box_width) < box_width or y %
                (2 * box_width) < box_width) and (x %
                                                  (2 * box_width) > box_width
                                                  or y %
                                                  (2 * box_width) > box_width):
                graph.plot(y, x)
예제 #9
0
def rectangle_blanc(haut, larg, ymin, ymax, xmin, xmax):
    """
    Colorie un rectangle blanc compris entre (xmin, xmax) horizontalement
    et (ymin, ymax) verticalement sur fond noir
   """
    for y in range(haut):
        for x in range(larg):
            if not (x >= xmin and x < xmax and y >= ymin and y < ymax):
                graph.plot(y, x)
    return
예제 #10
0
def dessine_bandes1(lst, hauteur, largeur_bandes):
    largeur = largeur_image(lst, largeur_bandes)
    graph.ouvre_fenetre(hauteur, largeur)

    # parcour pixels
    for y in range(hauteur):
        for x in range(largeur):
            nb = num_bande(x, y, largeur_bandes)
            if lst[nb] == 0:
                graph.plot(y, x)

    # graph.attend_fenetre()
    return
예제 #11
0
def rayures_verticales_naif(hauteur, largeur, larg_bande):
    """
    Dessine des rayures verticales de largeur larg_bande
    alternant blanc et noir sur une fenetre de taille
    hauteur x largeur.
    Il n'y a aucune condition necessaire pour larg_bande.

    **Algorithme naif**
    """
    for x in range(largeur):
        if bande_est_noire(numero_bande(x, larg_bande)):
            for y in range(hauteur):
                graph.plot(y, x)
    return
예제 #12
0
def rectangle_random(haut, larg, ymin, ymax, xmin, xmax):
    """
    Colorie un rectangle de couleur aleatoire compris entre (xmin, xmax)
    horizontalement et (ymin, ymax) verticalement (fond blanc)
    """
    couleurs = [
        "black", "white", "red", "green", "blue", "yellow", "cyan", "magenta",
        "orange", "darkgrey"
    ]
    # on choisit une couleur au hasard
    c = couleurs[int(random.random() * len(couleurs))]
    for y in range(ymin, ymax):
        for x in range(xmin, xmax):
            graph.plot(y, x, c)
    return
예제 #13
0
def updated_model_with_errors(parameter):
    layout = {
        'yaxis': {
            'range': [0, 450],
            'title': 'sales'
        },
        'xaxis': {
            'title': 'ad spend'
        }
    }
    inputs = list(range(1500, 4500, 250))

    predictions = list(
        map(lambda ad_spend: parameter * ad_spend, observed_ad_spends))
    data_trace = trace_values([2000, 3500, 4000], [260, 445, 490],
                              name='actual sales')
    predictions_trace = trace_values(observed_ad_spends,
                                     predictions,
                                     'lines',
                                     name='predictions')
    y_values_y_hats = list(zip(observed_sales, predictions))
    errors = list(map(lambda pair: pair[0] - pair[1], y_values_y_hats))
    error_traces = error_line_traces(observed_ad_spends, observed_sales,
                                     errors)
    return plot([data_trace, predictions_trace] + error_traces)
예제 #14
0
파일: data.py 프로젝트: JeffKatzy/notes
def plot_data_and_model():
    inputs = list(range(1500, 4500, 250))
    predictions = list(map(lambda input: .15*input,inputs))
    predictions_trace = trace_values(inputs, predictions, 'lines', name = 'predictions')
    data_trace = trace_values([2000, 3500, 4000], [260, 445, 490], name = 'actual sales')
    layout = {'yaxis': {'range': [0, 18], 'title': 'sales'}, 'xaxis': {'title': 'ad spend'}}
    return plot([data_trace, predictions_trace])
예제 #15
0
def damier_naif(hauteur, largeur, cote):
    """
    Dessine un damier de case carees de largeur cote
    alternant blanc et noir sur une fenetre de taille
    hauteur x largeur.
    Il n'y a aucune condition necessaire pour cote et la premiere case
    est blanche.

    **Algorithme naif**
    """
    for x in range(largeur):
        for y in range(hauteur):
            nv, nh = numero_case(x, y, cote)
            if case_est_noire(nv, nh):
                graph.plot(y, x)
    return
예제 #16
0
def rainbow_damier(width, height, length):
    cases = []
    last_column = -1
    for y in range(height):
        offset = 0
        y_column = get_column_number(y, length)
        if last_column != y_column:
            cases.append([get_random_color()])
            last_column = y_column
        if y_column % 2 != 0:
            offset = 1
        for x in range(width):
            x_column = get_column_number(x, length)
            if x_column == len(cases[y_column]):
                cases[y_column].append(get_random_color())
            if x_column % 2 - offset != 0:
                graph.plot(y, x, cases[y_column][x_column])
예제 #17
0
파일: data.py 프로젝트: JeffKatzy/notes
def plot_data_and_errors():
    inputs = list(range(1500, 4500, 250))
    predictions = list(map(lambda input: .15*input,inputs))
    predictions_trace = trace_values(inputs, predictions, 'lines', name = 'predictions')
    errors = [-40, -80, -110]
    ad_spends = [2000, 3500, 4000]
    sales = [260, 445, 490]
    error_traces = error_line_traces(ad_spends, sales, errors)
    return plot([data_trace, predictions_trace] + error_traces)
예제 #18
0
def predictFromFile2(fn,top):
	fn=sn.getSentenceFile(fn)
	global fl,csvdata
	csvdata=pd.DataFrame(columns=('line',"joy","trust","fear","surprise","sadness","disgust","anger","anticipation"))
	
	if fl ==0:
		init(top)
	f=open(fn,"r+")
	data = f.readlines()
	l=0
	for line in data:
		l+=1
		#top.pr  ("\n"+line)
		stemArr = getStems(line)
		#top.pr(predict2(stemArr))
		predict2(stemArr,l)

	csvdata.to_csv(fn+".csv",index=False)
	graph.plot(fn)
예제 #19
0
def measure_encrypt(message, bits_limit):
    """
    Realiza o benchmark do processo de geração de chaves, comparando fermat e miller.
    O resultado desse procedimento é gravado em um arquivo na pasta /time.
    message - mensagem a ser criptografada
    bits_limit - número de bits limite para realizar benchmark
    """
    timesAverage = 10
    fermatEncrypt, [] = rsa_benchmark(message,
                                      bits_limit,
                                      encryptMethod="fermat",
                                      timesAverage=timesAverage)
    millerEncrypt, [] = rsa_benchmark(message,
                                      bits_limit,
                                      encryptMethod="miller",
                                      timesAverage=timesAverage)
    plotEncrypt = {"fermat": fermatEncrypt, "miller": millerEncrypt}

    plot(valuesY=plotEncrypt, title="Encrypt", bits=bits_limit)
예제 #20
0
def plot_data_and_errors():
    inputs = [.30, .40, .50, .60, .70]
    predictions = list(map(lambda angle: 40 * angle, inputs))
    predictions_trace = trace_values(inputs,
                                     predictions,
                                     'lines',
                                     name='predictions')
    errors = [-4, -9, -11]
    error_traces = error_line_traces(observed_shot_angles, observed_distances,
                                     errors)
    return plot([data_trace, predictions_trace] + error_traces)
예제 #21
0
def rectangle_couleur(ymin,
                      ymax,
                      xmin,
                      xmax,
                      couleur,
                      outline_color="black",
                      outline_thick=0):
    for y in range(ymin, ymax):
        for x in range(xmin, xmax):
            graph.plot(y, x, couleur=couleur)
    for x in range(xmin, xmin + outline_thick):
        for y in range(ymin, ymax):
            graph.plot(y, x, couleur=outline_color)
    for x in range(xmax - outline_thick, xmax):
        for y in range(ymin, ymax):
            graph.plot(y, x, couleur=outline_color)
    for y in range(ymin, ymin + outline_thick):
        for x in range(xmin, xmax):
            graph.plot(y, x, couleur=outline_color)
    for y in range(ymax - outline_thick, ymax):
        for x in range(xmin, xmax):
            graph.plot(y, x, couleur=outline_color)
    return
예제 #22
0
def plot_data_and_model():
    model_trace = trace_values(angles,
                               predicted_distances,
                               mode='lines',
                               name='model')
    layout = {
        'yaxis': {
            'range': [0, 18],
            'title': 'shot distance'
        },
        'xaxis': {
            'title': 'shot angle'
        }
    }
    return plot([data_trace, model_trace])
예제 #23
0
def measure_break(message, bits_limit):
    """
    Realiza o benchmark do processo quebra de chaves.
    O resultado desse procedimento é gravado em um arquivo na pasta /time.
    message - mensagem a ser criptografada
    bits_limit - número de bits limite para realizar benchmark
    """
    timesAverage = 1

    pollardBreak = rsa_benchmark(message,
                                 bits_limit,
                                 breakMethod="pollard",
                                 timesAverage=timesAverage)
    pollardBreak = pollardBreak[1]

    bruteBreak = rsa_benchmark(message,
                               bits_limit,
                               breakMethod="brute",
                               timesAverage=timesAverage)
    bruteBreak = bruteBreak[1]

    plotBreak = {"pollard": pollardBreak, "brute force": bruteBreak}

    plot(valuesY=plotBreak, title="Break Key", bits=bits_limit)
def main():
    trainingparams = [0.01, 0.02, 0.03, 0.125, 0.625, 1]
    iterations = 5
    eta = 0.001
    epsilon = 0.001
    valuerange = 10
    params = []

    data = utils.getdata('breast-cancer-wisconsin.data.txt')
    nb = naivebayes.naivebayes(data, trainingparams, iterations, valuerange)
    nb['label'] = 'Naive Bayes'
    lr = logisticregression.logisticregression(data, trainingparams,
                                               iterations, eta, epsilon)
    lr['label'] = 'Logistic Regression'
    params.append(lr)
    params.append(nb)
    plot = graph.plot(params, 'Training Set', 'Accuracy')
    plot.show()

    return
예제 #25
0
def updated_model_with_errors(parameter):
    layout = {
        'yaxis': {
            'range': [0, 18],
            'title': 'shot distance'
        },
        'xaxis': {
            'title': 'shot angle'
        }
    }
    predictions = list(
        map(lambda angle: parameter * angle, observed_shot_angles))
    actual_trace = trace_values(observed_shot_angles,
                                observed_distances,
                                name='actual shots')
    predictions_trace = trace_values(observed_shot_angles,
                                     predictions,
                                     'lines',
                                     name='predictions')
    y_values_y_hats = list(zip(observed_distances, predictions))
    errors = list(map(lambda pair: pair[0] - pair[1], y_values_y_hats))
    error_traces = error_line_traces(observed_shot_angles, observed_distances,
                                     errors)
    return plot([actual_trace, predictions_trace] + error_traces)
예제 #26
0
        forces(f_spring, K, A, coords, species, cell, C=C)  # edge forces
        + forces(f_spring, pK_B, pA_B, coords, species, cell, C=C,
                 repel=False)  # B pseudoedge forces
        +
        forces(f_spring, pK_Si, pA_Si, coords, species, cell, C=C,
               repel=False)  # Si pseudoedge forces
    ][0]  # (wrapped in list only to facilitate commenting out pseudoedge lines)

    E_arr = energies(F)  # energy per node (F**2)
    E, E0 = np.sum(E_arr), E  # total energy
    print E, count, progress
    if E < Si_O * .001 * len(G.V) or count > 200 or progress < -5:
        break

    # broadcast E_arr (i.e. F_sq) to same shape as F
    Fsq_vector = np.vstack([E_arr] * len(coords)).transpose()

    # shift coords by step * unit vector
    """ is there a sensible way to include force magnitude somehow?"""
    shift = step * F / Fsq_vector**(0.5)
    coords += shift.transpose()

    # if cell boundaries were defined, enforce periodicity
    if cell != None:
        for i, length in enumerate(cell):
            coords[i] %= length

    step, progress = update_step(step, E, E0, progress)

plot(coords, A, G.nSi, G.nB, G.nO, cell)
예제 #27
0
            "partitions",
            "VAR",
            "sum u(x)",
            "cor_cost",
            "sp2_cost",
            "cor_means",
            "sp2_means",
            "time_coreset",
            "time_kmeans",
            "time_cost",
            "time_spark",
        ],
    )
    dump(
        "avg",
        data1,
        [runtag, "ref-cost: ", ref_cost, " total-time:", r(total_time, 1)],
        ["partitions", "VAR", "coreset weights avg", "coreset avg cost", "uniform avg cost"],
    )
    dump(
        "mis",
        data2,
        [runtag, "ref-cost:", ref_cost],
        ["partitions", "VAR", "cset weights avg", "cset mistake", "spark mis", "time cset", "time spark"],
    )

    un = [y_un, t_un] if run["uni"] else None
    graph.plot(
        x_ax, [y_cs, t_cs, t_csg], [y_sp2, t_sp], None, un, show=plot["result"], labels=[xlabel, runtg[1], runtg[2]]
    )
예제 #28
0
		sendStr += str(strftime("%H:%M", gmtime()))
		sendStr += " "
		sendStr += str(data)
		f.write(sendStr) # python will convert \n to os.linesep
		f.close() # you can omit in most cases as the destructor will call it

		s.send('5')
		f1 = s.makefile()
		data = str(f1.readline())
		print "HS2: ",data
		f1 = open('plotVal2','a')
		sendStr = ""
		sendStr += str(strftime("%H:%M", gmtime()))
		sendStr += " "
		sendStr += str(data)
		f1.write(sendStr)
		f1.close()
		
#        f2 = open('plotValues','a')
#        f2.write(data) # python will convert \n to os.linesep
#        f2.close() # you can omit in most cases as the destructor will call it

		gr.plot(0,0)
		gr.plot(0,1)
		s.close()
	except socket.error, exc:
		print "Caught exception socket.error : %s" % exc

	time.sleep (10)

예제 #29
0
def white_rectangle(height, length, y1, y2, x1, x2):
    for y in range(height):
        for x in range(length):
            if x <= x1 or x >= x2 or y <= y1 or y >= y2:
                graph.plot(y, x)
예제 #30
0
        sendStr = ""
        sendStr += str(strftime("%H:%M", gmtime()))
        sendStr += " "
        sendStr += str(data)
        f.write(sendStr)  # python will convert \n to os.linesep
        f.close()  # you can omit in most cases as the destructor will call it

        s.send('5')
        f1 = s.makefile()
        data = str(f1.readline())
        print "HS2: ", data
        f1 = open('plotVal2', 'a')
        sendStr = ""
        sendStr += str(strftime("%H:%M", gmtime()))
        sendStr += " "
        sendStr += str(data)
        f1.write(sendStr)
        f1.close()

        #        f2 = open('plotValues','a')
        #        f2.write(data) # python will convert \n to os.linesep
        #        f2.close() # you can omit in most cases as the destructor will call it

        gr.plot(0, 0)
        gr.plot(0, 1)
        s.close()
    except socket.error, exc:
        print "Caught exception socket.error : %s" % exc

    time.sleep(10)
예제 #31
0
def noir(height, length):
    for y in range(height):
        for x in range(length):
            graph.plot(y, x)
예제 #32
0
def profMethod_vertical_strip(height, length, band_width):
    for l in range(height):
        for c in range(length):
            if c % (2 * band_width) > band_width:
                graph.plot(l, c)