def generator(num_exp, sky, read, sig):

    #############################################
    # Generator of Signal and Noise Distributions
    # Parameters:
    # num_exp = Number of exposures taken
    # sky = photon rate of the sky-background
    # read = photon rate of the read noise
    # sig = photon rate of the signal
    #############################################

    num_meas = 1

    # Calculate the total noise and signal rates

    tot_rate = sky + sig + read * num_exp
    tot_noise_rate = sky + read * num_exp

    noise_array = []

    signal_array = []

    #Initialize random class

    R = Random()

    #Get the samples for the different distributions

    noise = R.Poisson(lam=tot_noise_rate, size=(num_meas, num_exp))

    signal = R.Poisson(lam=tot_rate, size=(num_meas, num_exp))

    return (signal, noise)
Beispiel #2
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 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 choose_players():
    """ Let user choose players and player names in textual interface"""

    # Available picks
    player_type_list = ["H", "MC", "S", "R"]
    players = []
    while len(players) < 2:  # Until the player count is two
        i = len(players) + 1  # Number of current player
        while True:
            player_type_input = input(f"Player {i}: ")

            if player_type_input not in player_type_list:
                print("Invalid input! Please try again.")
                continue  # Loop will continue until valid input

            break

        if player_type_input == "H":
            while True:
                try:
                    memo = int(input("What will memory of Historian be? "))
                except:
                    continue
                if 1 <= memo <= 20:
                    break
            player = Historian(memo)

        if player_type_input == "MC":
            player = MostCommon()
        if player_type_input == "S":
            player = Sequential()
        if player_type_input == "R":
            player = Random()

        player_name = input("Player name: ")
        player.enter_name(player_name)

        players.append(player)
        i += 1

    return players  # List with players to enter tournament
Beispiel #6
0
    def get_algorithm(algorithm_type, alpha, clusters):
        if algorithm_type == AlgorithmType.Random:
            return Random(alpha, clusters)

        # elif algorithm_type == AlgorithmType.EFirst:
        # 	return EFirst(alpha, clusters)

        elif algorithm_type == AlgorithmType.EGreedy:
            return EGreedy(alpha, clusters)

        elif algorithm_type == AlgorithmType.EGreedy_Disjoint:
            return EGreedy_Disjoint(alpha, clusters)

        # elif algorithm_type == AlgorithmType.EGreedy_Hybrid:
        # 	return EGreedy_Hybrid(alpha, clusters)

        # elif algorithm_type == AlgorithmType.EGreedy_Seg:
        # 	return Combo_Seg(alpha, AlgorithmType.EGreedy)

        elif algorithm_type == AlgorithmType.LinUCB_Disjoint:
            return LinUCB_Disjoint(alpha, clusters)

        # elif algorithm_type == AlgorithmType.LinUCB_GP:
        # 	return LinUCB_GP(alpha, clusters)

        elif algorithm_type == AlgorithmType.LinUCB_GP_All:
            return LinUCB_GP_All(alpha, clusters)

        # elif algorithm_type == AlgorithmType.LinUCB_Hybrid:
        # return LinUCB_Hybrid(alpha, clusters)

        elif algorithm_type == AlgorithmType.UCB:
            return UCB(alpha, clusters)

        # elif algorithm_type == AlgorithmType.UCB_Seg:
        # 	return Combo_Seg(alpha, AlgorithmType.UCB)

        else:
            raise NotImplementedError("Non-implemented algorithm." +
                                      algorithm_type.name)
Beispiel #7
0
        p = sys.argv.index('-Nmeas')
        Nt = int(sys.argv[p + 1])
        if Nt > 0:
            Nmeas = 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')
        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(" ")
Beispiel #8
0
#! /usr/bin/env python
from Random import Random
import numpy as np
import matplotlib.pyplot as plt

if __name__ == "__main__":
    i = 0
    random = Random(66666)
    valuelist = []
    while i < 1000:

        #print (random.Exponential(i),"exponential")
        #print (random.Color_Baloon(),"my color")
        #color = random.Color_Baloon()
        x = random.parabolic_dist(10.)
        #x = random.Exponential(10.)
        #print (x)
        #color =random.Bernoulli(0.5)
        valuelist.append(x)
        #print (color)
        i = i + 1

    n, bins, patches = plt.hist(valuelist,
                                20,
                                density=True,
                                facecolor='r',
                                alpha=0.75)
    #print (n)
    plt.xlabel('x')
    plt.ylabel('Probability/20 bin')
    plt.title('Generated Random Numbers with parabolic distribution ')
# Cole Le Mahieu Project 3

# import packages
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
from scipy.stats import norm
from math import *
from Random import Random

# instantiate Random class
random = Random()

# default number experiments, measurements
Nexp = 500
Nroll = 100

# default slices to pull out of neymann construction
probA = 0.3
probB = 0.6

# user can input value for experiment or measurement number
if "-Nexp" in sys.argv:
    p = sys.argv.index("-Nexp")
    Ne = int(sys.argv[p + 1])
    if Ne > 0:
        Nexp = Ne
if "-Nroll" in sys.argv:
    p = sys.argv.index("-Nroll")
    Nt = int(sys.argv[p + 1])
for rep in range(REP):
    rand_state = np.random.randint(low = 1, high = 1000)
    np.random.seed(rand_state)
    divideFold = KFold(10, random_state = rand_state, shuffle = True)

    reg_models = {}
    reg_models["gradient_boosting"] = lambda: ensemble.GradientBoostingRegressor()
    reg_models["neural_network"] = lambda: neural_network.MLPRegressor()
    reg_models["ridge"] = lambda: linear_model.Ridge()
    reg_models["gradient_descent"] = lambda: linear_model.SGDRegressor()
    reg_models["svm"] = lambda: svm.SVR(gamma = "auto")
    reg_models["knn"] = lambda: neighbors.KNeighborsRegressor(weights = "distance")
    reg_models["random_forest"] = lambda: ensemble.RandomForestRegressor(random_state = rand_state)
    reg_models["gaussian_process"] = lambda: gaussian_process.GaussianProcessRegressor()
    reg_models["decision_tree"] = lambda: tree.DecisionTreeRegressor(random_state = rand_state)
    reg_models["random"] = lambda: Random()
    reg_models["default"] = lambda: Default()

    results = {}
    for baseline in ["default", "random"]:
        results[baseline] = {}
        # Loop through all regressors, except the baseline
        for regressor_type in filter(lambda reg: not reg in ["random", "default"], constants.REGRESSORS):
            # results[baseline][regressor_type] = {}
            kfold = 0
            results[baseline][regressor_type] = []
            # Divide datasets in train and test
            for train_indx, test_indx in divideFold.split(datasets):
                # results[baseline][regressor_type][kfold] = []
                # Only get pymfe calculated features for train datasets
                targets = data[data.name.isin(list(datasets.iloc[train_indx]))]
Beispiel #11
0
    users_to_update = list()
    clicks_to_update = list()
    user_recommendation_size = int(len(user_ids) * part)

    print("Starting evaluation of {0} with recommendation of size: {1}".format(
        algoName, part))
    input = open(
        "{0}//{1}//Processed//sorted_time_impressions.csv".format(path, name),
        "r")
    input.readline()  # get rid of header
    line = input.readline()
    hour_begin_timestamp = datetime.datetime.fromtimestamp(
        int(line.split(",")[2]) / 1000)
    warmup = True

    algo = Random(alpha, user_embeddings, user_ids)
    recommended_users = list()
    for line in input:
        total_impressions += 1
        parts = line.split(",")
        user_id = int(parts[0])
        click = int(parts[1])
        timestamp = datetime.datetime.fromtimestamp(int(parts[2]) / 1000)

        if warmup and (timestamp - hour_begin_timestamp
                       ).seconds < time_between_updates_in_seconds:
            users_to_update.append(user_id)
            clicks_to_update.append(click)
            continue

        if (timestamp - hour_begin_timestamp
Beispiel #12
0
 def __init__(self, seed=5555):
     self.m_random = Random(seed)
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()
    reg_models[
        "gradient_boosting"] = lambda: ensemble.GradientBoostingRegressor()
    reg_models["neural_network"] = lambda: neural_network.MLPRegressor()
    reg_models["ridge"] = lambda: linear_model.Ridge()
    reg_models["gradient_descent"] = lambda: linear_model.SGDRegressor()
    reg_models["svm"] = lambda: svm.SVR(gamma="auto")
    reg_models["knn"] = lambda: neighbors.KNeighborsRegressor(weights=
                                                              "distance")
    reg_models["random_forest"] = lambda: ensemble.RandomForestRegressor(
        random_state=rand_state)
    reg_models[
        "gaussian_process"] = lambda: gaussian_process.GaussianProcessRegressor(
        )
    reg_models["decision_tree"] = lambda: tree.DecisionTreeRegressor(
        random_state=rand_state)
    reg_models["random"] = lambda: Random(random_seed=rand_state)
    reg_models["default"] = lambda: Default()

    predictions = []
    # Divide datasets in train and test
    for train_indx, test_indx in divideFold.split(datasets):
        models = {}
        # Selecting only data for test
        tests = meta_base[meta_base.name.isin(list(datasets.iloc[test_indx]))]
        # Selecting only data from train
        train_data = meta_base[meta_base.name.isin(
            list(datasets.iloc[train_indx]))]
        targets = train_data.drop(combinations_strings + ["name"],
                                  axis=1).values
        # Training block
        for comb in combinations_strings:
Beispiel #15
0
def generator_Of_Random_Coin(Seedd, Probb, Ntosss, Nexpp, Outputt):
    #Assignments of defaults
    Seed = 53422

    # Single coin-toss probability for "1"
    Prob = 0.3

    # number of coin tosses (per experiment)
    Ntoss = 10

    # number of experiments
    Nexp = 10

    # output file defaults
    doOutputFile = False

    # read the user-provided seed from the command line (if there)
    if '-seed' in sys.argv:
        p = sys.argv.index('-seed')
        seed = sys.argv[p+1]
    if '-prob' in sys.argv:
        p = sys.argv.index('-prob')
        ptemp = float(sys.argv[p+1])
        if ptemp >= 0 and ptemp <= 1:
            prob = ptemp
    if '-Ntoss' in sys.argv:
        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
    Seed = int(Seedd)
    Prob = float(Probb)
    Ntoss = int(Ntosss)
    Nexp = int(Nexpp)
    random = Random(Seed)
    doOutputFile = True
    
    if doOutputFile == True:
         outfile = Outputt 
    else:
        outfile = "Flips.txt"
    
    if doOutputFile: #flag to check if there is file
        outfile = open(outfile, 'w+')
        for e in range(0,Nexp):
            for t in range(0,Ntoss):
                outfile.write(str(random.Geometric(Prob))+" ")
            outfile.write(" \n")
        outfile.close()
    else:
        for e in range(0,Nexp):
            for t in range(0,Ntoss):
                print(random.Geometric(Prob), end=' ')
            print(" ")
    return (outfile)
    # default seed
    seed = 5555

    # default type of dice roll
    type = "nb"

    # default number of coin tosses (per experiment)
    Ntoss = 1

    # default number of experiments
    Nexp = 1

    # output file defaults
    doOutputFile = False

    random_number = Random(seed)

    # read the user-provided seed from the command line (if there)
    if '-seed' in sys.argv:
        p = sys.argv.index('-seed')
        seed = sys.argv[p + 1]
    if '-type' in sys.argv:
        p = sys.argv.index('-type')
        ptemp = sys.argv[p + 1]
        type = ptemp

    if '-Ntoss' in sys.argv:
        p = sys.argv.index('-Ntoss')
        Nt = int(sys.argv[p + 1])
        if Nt > 0:
            Ntoss = Nt
Beispiel #17
0
    def get_algorithm(algorithm_type, alpha):
        if algorithm_type == AlgorithmType.Random:
            return Random(alpha)

        elif algorithm_type == AlgorithmType.EFirst:
            return EFirst(alpha)

        elif algorithm_type == AlgorithmType.EGreedy:
            return EGreedy(alpha)

        elif algorithm_type == AlgorithmType.EGreedy_Disjoint:
            return EGreedy_Disjoint(alpha)

        elif algorithm_type == AlgorithmType.EGreedy_Hybrid:
            return EGreedy_Hybrid(alpha)

        elif algorithm_type == AlgorithmType.EGreedy_Seg:
            return Combo_Seg(alpha, AlgorithmType.EGreedy)

        elif algorithm_type == AlgorithmType.LinUCB_Disjoint:
            return LinUCB_Disjoint(alpha)

        elif algorithm_type == AlgorithmType.LinUCB_GP:
            return LinUCB_GP(alpha)

        elif algorithm_type == AlgorithmType.LinUCB_GP_All:
            return LinUCB_GP_All(alpha)

        elif algorithm_type == AlgorithmType.LinUCB_Hybrid:
            return LinUCB_Hybrid(alpha)

        elif algorithm_type == AlgorithmType.UCB:
            return UCB(alpha)

        elif algorithm_type == AlgorithmType.UCB_Seg:
            return Combo_Seg(alpha, AlgorithmType.UCB)

        elif algorithm_type == AlgorithmType.EGreedy_Lin:
            return EGreedy_Lin(alpha)

        elif algorithm_type == AlgorithmType.EGreedy_Seg_Lin:
            return Combo_Seg(alpha, AlgorithmType.EGreedy_Lin)

        elif algorithm_type == AlgorithmType.EGreedy_Lin_Hybrid:
            return EGreedy_Lin_Hybrid(alpha)

        elif algorithm_type == AlgorithmType.TS:
            return TS(alpha)

        elif algorithm_type == AlgorithmType.TS_Bootstrap:
            return TS_Bootstrap(alpha)

        elif algorithm_type == AlgorithmType.TS_Lin:
            return TS_Lin(alpha)

        elif algorithm_type == AlgorithmType.TS_Seg:
            return Combo_Seg(alpha, AlgorithmType.TS)

        elif algorithm_type == AlgorithmType.TS_Disjoint:
            return TS_Disjoint(alpha)

        elif algorithm_type == AlgorithmType.TS_Hybrid:
            return TS_Hybrid(alpha)

        elif algorithm_type == AlgorithmType.TS_Truncated:
            return TS_Truncated(alpha)

        elif algorithm_type == AlgorithmType.EGreedy_TS:
            return EGreedy_TS(alpha)

        elif algorithm_type == AlgorithmType.TS_Gibbs:
            return TS_Gibbs(alpha)

        elif algorithm_type == AlgorithmType.TS_Laplace:
            return TS_Laplace(alpha)

        elif algorithm_type == AlgorithmType.EGreedy_Annealing:
            return EGreedy_Annealing(alpha)

        elif algorithm_type == AlgorithmType.NN:
            return NN(alpha)

        elif algorithm_type == AlgorithmType.Ensemble:
            return Ensemble(alpha)

        elif algorithm_type == AlgorithmType.TS_RLR:
            return TS_RLR(alpha)

        else:
            raise NotImplementedError("Non-implemented algorithm." +
                                      algorithm_type.name)