Beispiel #1
0
def call_random(i,
                x,
                training_data,
                testing_data,
                fold,
                goal="Max",
                eval_time=3600,
                lifes=5):
    # test_data = testing_data.values
    random_optimizer = Random(NP=10,
                              Goal=goal,
                              eval_time=eval_time,
                              num_lifes=lifes)
    v, num_evals, tuning_time = random_optimizer.solve(
        process, OrderedDict(param_grid[i]['learners_para_dic']),
        param_grid[i]['learners_para_bounds'],
        param_grid[i]['learners_para_categories'], param_grid[i]['model'], x,
        training_data, fold)
    params = v.ind.values()
    start_time = time.time()
    predicted_tune = param_grid[i]['model'](training_data.iloc[:, :-1],
                                            training_data.iloc[:, -1],
                                            testing_data.iloc[:, :-1], params)
    predicted_default = param_grid[i]['model'](training_data.iloc[:, :-1],
                                               training_data.iloc[:, -1],
                                               testing_data.iloc[:, :-1], None)
    val_tune = evaluation(x, predicted_tune, testing_data.iloc[:, -1],
                          testing_data.iloc[:, :-1])
    val_predicted = evaluation(x, predicted_default, testing_data.iloc[:, -1],
                               testing_data.iloc[:, :-1])
    print("For measure %s: default=%s, predicted=%s" %
          (x, val_predicted, val_tune))
    tuning_time += time.time() - start_time
    # print(val_tune, params, num_evals, tuning_time)
    return val_tune, params, num_evals, tuning_time
def test():
    """ Testing stuff to see it works properly """
    a = Random()
    b = Sequential()
    a.enter_name("Player Random")
    b.enter_name("Player Sequential")

    game = SingleGame(a, b)
    game.perform_game()
    game.show_result()
def calculer_next(previous, next):
	rand_nbr = Random()
	tab_to_return = []
	for i in range(0, (2**16)+1):
		for j in range(0,2):
			t = 0
			t = j
			t = t << 15 | previous
			t = t << 16 | i
			rand_nbr.srand(t)
			if (verif_next(rand_nbr.rand(), next)):
				tab_to_return.append(t)
	return tab_to_return
Beispiel #4
0
def compare_rate(req):
    parameters = get_parameters(req)

    params = {
        "bank1": parameters['Australian_Banks'],
        "bank2": parameters['Australian_Banks1'],
        "mortgage": parameters['Mortgage_types'],
        "year_fixed": parameters['year_fixed'],
        "ownership_status": parameters['ownership_status']
    }

    # TODO: Check if bank1 and bank2 are the same. if the same bank,
    # tell user that he/she put in the same name of bank.
    best_rate_bank1 = get_best_rate(params["bank1"] or None, params["mortgage"]
                                    or None, params["year_fixed"] or None,
                                    params['ownership_status'] or None)

    best_rate_bank2 = get_best_rate(
        params["bank2"] or None, params["mortgage"]
        or best_rate_bank1['repayment_type'], params["year_fixed"]
        or best_rate_bank1['year_fixed'], params['ownership_status']
        or best_rate_bank1['ownership_type'])

    response = Random.compare_bank(best_rate_bank1, best_rate_bank2)
    return response
def Cookie_Derp(Seedd, Ratee, Nmeass, Nexpp, OutputFileNamee):
    # default seed
    Seed = 5555

    # default rate parameter for cookie disappearance (rate =1, means a cookies per day)
    Rate = 1

    # default number of time measurements (time to next missing cookie) - per experiment
    Nmeas = 1

    # default number of experiments
    Nexp = 1

    # output file defaults
    doOutputFile = False

    # class instance of our Random class using seed
    Seed = int(Seedd)
    Rate = float(Ratee)
    Nmeas = int(Nmeass)
    Nexp = int(Nexpp)
    random = Random(Seed)
    doOutputFile = True
    
    if doOutputFile == True:
        OutputFileName = OutputFileNamee 
    else:
        OutputFileName = "Cookie.txt"

    if doOutputFile:
        outfile = open(OutputFileName, 'w+')
        outfile.write(str(Rate)+"\n")
        for e in range(0,Nexp):
            for t in range(0,Nmeas):
                outfile.write(str(random.Exponential(Rate))+" ")
            outfile.write(" \n")
        outfile.close()
    else:
        print(Rate)
        for e in range(0,Nexp):
            for t in range(0,Nmeas):
                print(random.Exponential(Rate), end=' ')
            print(" ")
	def setResult(self, value):
		"""
		Schreibt das Ergebnis des Wurfs in die GUI. Dabei wird auch je nach Erfolgsqualität bei dem dargestellten Würfel eine andere Augenzahl gezeigt.
		"""

		self.ui.statusBar.showMessage(self.tr("Result of diceroll is displayed."))

		if (value == DieResult.dramaticFailure):
			self.ui.label_resultText.setText(self.tr("Dramatic Failure"));
			self.ui.label_result.setPixmap(QPixmap(":/icons/actions/cnrdelete-all1.png"));
			self.displayDice(1)
		elif (value == DieResult.failure):
			self.ui.label_resultText.setText(self.tr("Failure"));
			self.ui.label_result.setPixmap(QPixmap(":/icons/actions/fileclose.png"));
			self.displayDice(Random.random(2, 7))
		elif (value == DieResult.success):
			self.ui.label_resultText.setText(self.tr("Success"));
			self.ui.label_result.setPixmap(QPixmap(":/icons/actions/ok.png"));
			self.displayDice(Random.random(8, 9))
		else:
			self.ui.label_resultText.setText(self.tr("Exceptional Success"));
			self.ui.label_result.setPixmap(QPixmap(":/icons/actions/bookmark.png"));
			self.displayDice(0)
Beispiel #7
0
def rate_followup(req):
    parameters = get_parameters(req)
    params = {
        "bank": parameters['Australian_Banks'],
        "mortgage": parameters['Mortgage_types'],
        "fixed_year": parameters['year_fixed'],
        "ownership_status": parameters['ownership_status']
    }
    best_rate = get_best_rate(params['bank'] or None, params['mortgage']
                              or None, params['fixed_year'] or None,
                              params['ownership_status'] or None)
    response = Random.best_bank(params, best_rate)

    return response
	def displayDice(self, value=None):
		"""
		@todo Der Würfel kann mehrmals in Folge das selbe Ergebnis anzeigen, was dazu führt, daß der Bildablauf zu stocken scheint.
		"""

		if (value == None):
			dieValue = Random.random(10)-1
		else:
			dieValue = value

		for item in self.scene.items():
			self.scene.removeItem(item)

		self.scene.addItem(self.dice[dieValue])
		self.view.setSceneRect(self.scene.itemsBoundingRect())
		self.view.fitInView(self.dice[dieValue])
Beispiel #9
0
def compare_followup(req):
    parameters = get_parameters(req)

    params = {
        "bank": parameters['Australian_Banks'],
        "mortgage": parameters['Mortgage_types'],
        "fixed_year": parameters['year_fixed'],
        "ownership_status": parameters['ownership_status']
    }

    context = get_contexts(req, pos=1)
    old_rate = context['parameters']['rate']

    new_best_rate = get_best_rate(params['bank'] or None, params['mortgage']
                                  or None, params['fixed_year'] or None,
                                  params['ownership_status'] or None)

    response = Random.best_rate_compare_followup(old_rate, new_best_rate)
    return response
Beispiel #10
0
def best_rate(req):
    parameters = get_parameters(req)

    params = {
        "bank": parameters['Australian_Banks'],
        "mortgage": parameters['Mortgage_types'],
        "fixed_year": parameters['year_fixed'],
        "ownership_status": parameters['ownership_status']
    }

    best_rate = get_best_rate(params['bank'] or None, params['mortgage']
                              or None, params['fixed_year'] or None,
                              params['ownership_status'] or None)

    response = Random.best_bank(params, best_rate)

    # TODO: Static Output Contexts, there should be a better way of doing it.
    output_contexts = [{
        "name":
        "projects/ron-anpelr/agent/sessions/e1dc138a-9f22-7941-80de-8998ede6221b/contexts/showrate-followup",
        "lifespanCount": 5,
        "parameters": {
            "fixed_year": best_rate['year_fixed'],
            "Australian_Banks": best_rate['bank_name'],
            "repayment_type": best_rate['repayment_type'],
            "ownership_status": best_rate['ownership_type'],
            "rate": best_rate['interest_rate']
        }
    }, {
        "name":
        "projects/ron-anpelr/agent/sessions/e1dc138a-9f22-7941-80de-8998ede6221b/contexts/bestrate-followup",
        "lifespanCount": 5,
        "parameters": {
            "rate": best_rate['interest_rate']
        }
    }]

    return response, output_contexts
Beispiel #11
0
    def reproduceAndMutate(parentA, parentB, AMD):
        # // Now go through Parents parmaters and exchange gentic info
        # //  Also mutate select gene within the same loop
        # // no need having a seperte mutate function that loops through paramter matrices again
        #
        # // Loops can use child dimensions as all networks have fixed same topologies in this

        child = Agent(initEmpty=True,
                      xPos=AMD[2],
                      yPos=AMD[3],
                      xPos_range=AMD[4],
                      yPos_range=AMD[5],
                      vertical_fuel_depletion_rate=AMD[0],
                      horizontal_fuel_depletion_rate=AMD[1],
                      color=parentA.color)
        child.functional_system.name = parentA.functional_system.name

        for i in range(len(child.functional_system.layers)):

            rowsW = child.functional_system.layers[i]['weights'].shape[0]
            colsW = child.functional_system.layers[i]['weights'].shape[1]

            for j in range(rowsW):
                for k in range(colsW):

                    if np.random.rand() < GenticAlgorithm.crossOverRate:
                        # Use Parent A gene
                        child.functional_system.layers[i]['weights'][j][
                            k] = parentA.functional_system.layers[i][
                                'weights'][j][k]

                    else:
                        child.functional_system.layers[i]['weights'][j][
                            k] = parentB.functional_system.layers[i][
                                'weights'][j][k]

                    if np.random.rand() < GenticAlgorithm.mutateRate:
                        child.functional_system.layers[i]['weights'][j][
                            k] += Random.gaussian_distribution(mean=0,
                                                               sigma=0,
                                                               samples=1)

            # Reproduce and Mutate Baiases
            rowsB = child.functional_system.layers[i]['biases'].shape[0]
            colsB = child.functional_system.layers[i]['biases'].shape[1]

            for j in range(rowsB):
                for k in range(colsB):

                    if np.random.rand() < GenticAlgorithm.crossOverRate:
                        # Use Parent A gene
                        child.functional_system.layers[i]['biases'][j][
                            k] = parentA.functional_system.layers[i]['biases'][
                                j][k]

                    else:
                        child.functional_system.layers[i]['biases'][j][
                            k] = parentB.functional_system.layers[i]['biases'][
                                j][k]

                    if np.random.rand() < GenticAlgorithm.mutateRate:
                        child.functional_system.layers[i]['biases'][j][
                            k] += Random.gaussian_distribution(mean=0,
                                                               sigma=0,
                                                               samples=1)
        return child
        p = sys.argv.index('-Ntoss')
        Nt = int(sys.argv[p + 1])
        if Nt > 0:
            Ntoss = Nt
    if '-Nexp' in sys.argv:
        p = sys.argv.index('-Nexp')
        Ne = int(sys.argv[p + 1])
        if Ne > 0:
            Nexp = Ne
    if '-output' in sys.argv:
        p = sys.argv.index('-output')
        OutputFileName = sys.argv[p + 1]
        doOutputFile = True

    # class instance of our Random class using seed
    random = Random(seed)

    if doOutputFile:
        outfile = open(OutputFileName, 'w')
        for e in range(0, Nexp):
            for t in range(0, Ntoss):
                outfile.write(
                    str(random.random_triangular(prob, 0.6, 0.5)) + " ")
            outfile.write(" \n")
        outfile.close()
    else:
        for e in range(0, Nexp):
            for t in range(0, Ntoss):
                print(random.random_triangular(prob, 0.6, 0.5), end=' ')
            print(" ")
Beispiel #13
0
#! /usr/bin/env python

from Random import Random
import numpy as np
import matplotlib.pyplot as plt

random_number = Random(77777777)
myx = []

for x in range(1, 10000):
    faces = random_number.Category6()
    myx.append(faces)

# create histogram of our data
plt.figure()
plt.hist(myx,
         6,
         density=True,
         facecolor='green',
         histtype="barstacked",
         alpha=0.75)

# plot formating options
plt.xlabel('Dice faces')
plt.ylabel('Probability', fontweight="bold", fontsize="17")
plt.title('Categorical Distribution', fontweight="bold", fontsize="17")
plt.grid(True, color='r')

# save and show figure
plt.savefig("Dice.png")
#plt.show()
Beispiel #14
0
        p = sys.argv.index('-seed')
        seed = sys.argv[p+1]

    if '-trial_b' in sys.argv:
        p = sys.argv.index('-trial_b')
        trial_b = sys.argv[p+1]
        trial_b = int(sys.argv[p+1])

    if '-trial_n' in sys.argv:
        p = sys.argv.index('-trial_n')
        trial_n = sys.argv[p+1]
        trial_n = int(sys.argv[p+1])

#class instance for random class

random_number = Random(seed)
myx = []


for x in range(0,trial_b):
    faces = random_number.Category6()
    myx.append(int(faces))
    

# writing array in the file 
f = open("biased_dice.txt", "w")
np.savetxt(f,myx)
f.close()

# making a dict and setting counter for each number as 0 and looping and adding # count
counter = {1:0,2:0,3:0,4:0,5:0,6:0}
Beispiel #15
0
        p = sys.argv.index('-outputH1')
        OutputFileNameH1 = sys.argv[p + 1]
        doOutputFileH1 = True

    #create p6 using the probability inputs, if H0
    p6 = 1 - (p1 + p2 + p3 + p4 + p5)

    #entering probabilities into list format
    prob_list = [p1, p2, p3, p4, p5, p6]
    prob1a_list = [p1a_1, p1a_2, p1a_3, p1a_4, p1a_5, p1a_6]
    prob1b_list = [p1b_1, p1b_2, p1b_3, p1b_4, p1b_5, p1b_6]
    print('probabilities of unfair die one: ', prob1a_list)
    print('probabilities of unfair die two: ', prob1b_list)

    # class instance of our Random class using seed
    random = Random(seed)

    a = 7
    b = 3

    #plot beta distribution

    #    x = np.arange (0.01, 1, 0.01)
    #    y = scipybeta.pdf(x,a,b)
    #    plt.figure()
    #    plt.plot(x,y,label = r'$\alpha =$' + str(a) +', '+ r'$\beta =$' + str(b))
    #    plt.axvline(0.5,color='r',linestyle='--')
    #    plt.text(0.2,1.5,'P1',fontsize=20)
    #    plt.text(0.7,1.5,'P2',fontsize=20)
    #    plt.xlabel('x',fontsize=16)
    #    plt.ylabel(r'Beta($\alpha, \beta$)',fontsize=16)

if __name__ == "__main__":
	"""
	Main du programme rand
	"""
	login = sys.argv[1]

	if "-debug" in sys.argv:
		debug_mode = True
	else:
		debug_mode = False

	server = Server("http://pac.bouillaguet.info/TP3/rand/")

	rand_nbr = Random()

	inverse_modulaire = mod_inv(1103515245, 2**32)

	IV = server.query('/challenge/' + login)

	if debug_mode:
		print("IV[0] : {0}".format(IV["IV"][0]))
		print("IV[1] : {0}".format(IV["IV"][1]))

	#1er envoi
	k3_possibles = calculer_next(IV["IV"][0], IV["IV"][1])

	if debug_mode:
		print("Liste des k3 possibles: ", end = "")
		print("{0}".format(k3_possibles))