Ejemplo n.º 1
0
 def fn(p):
     all_params.update(zip(optim_params, p))
     try:
         p_stats = simulate(all_params, n=1000)
         return stats_error(p_stats, old_stats)
     except InvalidModelParam:
         return np.inf
Ejemplo n.º 2
0
def breed(population, fitness_scores):
    newPopulation = []
    newFitnessScores = []
    remaining = C.PopulationSize
    while remaining > 0:
        if C.Replacement:
            p = select_pair(population, fitness_scores, C.PopulationSize)
        else:
            p, population = select_pair(population, fitness_scores, remaining)
        p1 = p[0]
        p2 = p[1]
        r = random.randrange(1, C.statespace)
        c1 = p1[:r] + p2[r:]
        c2 = p2[:r] + p1[r:]
        if random.random() < C.MutationPct:
            g1 = random.randrange(C.statespace)
            g2 = random.randrange(C.statespace)
            c1[g1], c1[g2] = c1[g2], c1[g1]
        if random.random() < C.MutationPct:
            g1 = random.randrange(C.statespace)
            g2 = random.randrange(C.statespace)
            c2[g1], c2[g2] = c2[g2], c2[g1]
        if C.Elitism:
            p1score = fitness_scores[population.index(p[0])]
            p2score = fitness_scores[population.index(p[1])]
            c1score = main.simulate(main.newGameContainer(), c1)
            c2score = main.simulate(main.newGameContainer(), c2)
            contenderscores = [p1score, p2score, c1score, c2score]
            contenders = [p1, p2, c1, c2]
            m1 = contenderscores.index(max(contenderscores))
            newFitnessScores.append(contenderscores[m1])
            newPopulation.append(contenders.pop(m1))
            del contenderscores[m1]
            m2 = contenderscores.index(max(contenderscores))
            newFitnessScores.append(contenderscores[m2])
            newPopulation.append(contenders.pop(m2))
        else:
            newPopulation.append(c1)
            newPopulation.append(c2)
        remaining -= 2
        print("remaining: ", remaining)
    return newPopulation, newFitnessScores
Ejemplo n.º 3
0
def main(argv):
    try:
        opts, args = getopt.getopt(argv,"ht:a:s:p:",['type=', 'archi=', 'sim=', 'proc=']) # h for help
    except getopt.GetoptError:
        print('Usage : ')
        print('main.py -t <type> -a <path_to_cfg_architecture> -s <path_to_cfg_simulation> -p <path_to_cfg_processing>')   
        sys.exit(2)

    if(len(opts)==0):
        print('Usage : ')
        print('main.py -t <type> -a <path_to_cfg_architecture> -s <path_to_cfg_simulation> -p <path_to_cfg_processing>')   
        sys.exit()

    if(opts[0][0] == '-h'):
        print('Usage : ')
        print('main.py -t <type> -a <path_to_cfg_architecture> -s <path_to_cfg_simulation> -p <path_to_cfg_processing>')   
        sys.exit()

    elif opts[0][0] in ('-t','--type'):
        # resolve allows to go in absolute path (and note relative anymore)
        mod_path = Path(__file__).resolve().parents[0]
        #print(opts)
        if(opts[1][0] in ('-a','--archi') and \
            opts[2][0] in ('-s','--sim') and \
                opts[3][0] in ('-p','--proc')):
            system = (mod_path/Path(opts[1][1])).resolve()
            simu = (mod_path/Path(opts[2][1])).resolve()
            proc = (mod_path/Path(opts[3][1])).resolve()
            #print(system, simu, proc)
            if(opts[0][1] == 'simulation'):
                simulate(system, simu, proc)
            elif(opts[0][1]  == 'processing'):
                processing_only(system, simu, proc)
        else :
            print('Please precise path to cfg files.')
            print('Usage : ')
            print('main.py -t <type> -a <path_to_cfg_architecture> -s <path_to_cfg_simulation> -p <path_to_cfg_processing>')   
            sys.exit()
    else :
        pass
def classify(castles,
             trials=10000,
             threshold=.95,
             name="None",
             use_print=False):
    prob_distr, points_won, opponent_points, wins_by_three, opponents_win_by_three = m.simulate(
        trials, c1=castles, print_result=False, print_castles=False)
    print("Strategy Type" + "[" + name + "]" + ": " + str(wins_by_three))
    if wins_by_three >= threshold and use_print == True:
        print("Aggresive")
    else:
        if use_print == True:
            print("Conservative")
    return wins_by_three
Ejemplo n.º 5
0
def generate():
    # obtain variables passed from html page
    lat = float(request.form['lat'])
    long = float(request.form['long'])
    rate = float(request.form['rate'])
    result = ast.literal_eval(request.form['affectedCities'])
    explored = ast.literal_eval(request.form['savedLocs'])
    # use inputted coordinates if this is the first execution
    if result == []:
        result = [(lat, long)]
    # determine affected cities/routes in the next cycle
    result, explored = main.simulate(result, rate, explored)
    # separate affected routes and cities (for visualization)
    cities_road = [list(city) for city in result if len(city) == 4]
    cities_air = [list(city) for city in result if len(city) == 3]
    # calculate affected population
    population = sum([x[2] for x in cities_road])
    return render_template('layout_map.html', **locals())
Ejemplo n.º 6
0
data_a = []
data_e0 = []
data_e1 = []
data_e2 = []
data_e3 = []
data_e4 = []
data_e5 = []

bx_s = [(float(i)/10000000000.0) for i in range(1000000500,1000005000)]
for bx in bx_s:

    i += 1
    # dx = L_so/L
    if i%10 == 0:
        print(i)
    es = simulate(L=L, dx=dx, t=t, mu=mu, Bx=0.0, By=bx, delta=delta, alpha=alpha)
    # min(e, key=func)
    # print(e)
    # print(min(map(lambda x: abs(x), e)))
    # print("%9.f" %(min(e)))
    # data.append((min(map(lambda x: abs(x), e)), alpha, delta))
    # data_x.append(bx/E_so)
    data_x.append(bx)
    data_a.append(alpha)
    # data_y.append(by)
    # e = list(map(lambda x: abs(x), es))

    # e.sort()
    # eigen = min(map(lambda x: abs(x), es))
    # print(len(es))
    # data_e.append(eigen)
Ejemplo n.º 7
0
 def test_int_to_hex(self):
     X_14 = main.simulate(10, 100)
     X_14_bind = X_14[0]
     X_14_conc = X_14[1]
     self.assertEqual(True, abs(X_14_bind - 0.0047378863875207665) < 0.01)
     self.assertEqual(True, abs(X_14_conc - 0) < 0.00001)
Ejemplo n.º 8
0
import main

# Run main method
main.simulate("genomeSample.fa", 100, 4, 7, 10)

# Tests

# Test if sample genome is correctly extracted from FASTA file
valid_genome_file = open('genome.txt', 'r')
valid_genome = [line.rstrip('\n') for line in valid_genome_file.readlines()]
i = 0
#for sequence_name, sequence in main.genome.items():
#assert sequence == valid_genome[i]
#i += 1

# Test reverse read
read = "ACGTTTANAGAC"
reversed_read = main.reverse_read(read)
assert (reversed_read == "CAGANATTTGCA")

# Test complement read
complemented_read = main.complement_read(read)
assert (complemented_read == "TGCAAATNTCTG")

# Test get quality
avg_quality = 15
sigma = 5
read_length = 5
qualities = main.get_quality(avg_quality, sigma, read_length)
print(qualities)
for quality in qualities:
def performance_vs_aggressiveness(trials, castle):
    for x in range(trials):
        opponent = m.select_random_castles()
        opponent_aggressiveness = cst.classify(opponent, 250, .95,
                                               "Opponent " + str(x))
        prob, castle_avg_score, opponent_avg_score, castle_wins_by_three, opponent_wins_by_three = m.simulate(
            200, castle, c2=opponent, print_result=False, print_castles=False)
        arr_prob.append(prob)
        arr_castle_avg_score.append(castle_avg_score)
        arr_opponent_avg_score.append(opponent_avg_score)
        arr_castle_wins_by_three.append(castle_wins_by_three)
        arr_opponent_wins_by_three.append(opponent_wins_by_three)
        arr_opponent_aggressiveness.append(opponent_aggressiveness)
    my_file.append(arr_prob)
    my_file.append(arr_castle_avg_score)
    #my_file.append(arr_opponent)
    my_file.append(arr_opponent_avg_score)
    my_file.append(arr_castle_wins_by_three)
    my_file.append(arr_opponent_wins_by_three)
    my_file.append(arr_opponent_aggressiveness)
    return my_file
Ejemplo n.º 10
0
import os

import main

print("Testing started...")

# Run simulate method with simple sequence sample
main.simulate("genomeSample.fa", 60, 10, 4, 7)

# Tests

# Test if sample sequence is correctly extracted from FASTA file as one string
# Valid genome sequence should be in genomeSample.txt in one line
valid_genome_file = open('genomeSample.txt', 'r')
valid_genome = {}
genome_name = ''
lines = valid_genome_file.read().split()
for line in lines:
    if line[0] == '>':
        genome_name = line[1::]
        valid_genome[genome_name] = ''
    else:
        valid_genome[genome_name] = line
for sequence_name, sequence in main.genome.items():
    assert sequence == valid_genome[sequence_name]

# Sample reads
reads = ["ACCTAG", "ACACGGGTACC", "ACCCAGTTTTACGT", "ACGACG"]

# Test reverse read
reverse_reads = ["GATCCA", "CCATGGGCACA", "TGCATTTTGACCCA", "GCAGCA"]