Example #1
0
def main():
    runs=10000
    start_temp,alpha=10000,0.9995
    city_file="test-input-1.txt"
    output_file = open("test-output-1.txt",'w')

    cities = getCities(city_file)
    if len(cities) > 1000:
        runs = 100000


    new_start = lambda: random_start(len(cities))
    routes = routing(cities)
    tour_function=lambda tour: -tour_length(routes,tour)
    
    
    score,path=anneal(new_start,random_tour_permutations,tour_function,runs,start_temp,alpha)
    score = score*-1
    score_str=str(score)
    output_file.write(score_str)
    output_file.write("\n")
    for city in path:
         city_str = str(city)
         output_file.write(city_str)
         output_file.write("\n")
    output_file.close()
def tracts_mapping1(tractography1, tractography2, loss_function, neighbour, iterations_anneal_now,pre_map_file):

    ann = [100, 200, 400, 600, 800, 1000]        
    iterations_anneal_pre = 0
    
    if iterations_anneal_now<=100:
        dm12 = bundles_distances_mam(tractography1, tractography2)
        mapping12_coregistration_1nn = np.argmin(dm12, axis=1)
    else:
        k = (iterations_anneal_now/200) - 1
        iterations_anneal_pre = ann[k]
        from dipy.io.pickles import load_pickle
        mapping12_coregistration_1nn = load_pickle(pre_map_file)
        
    iterations_anneal = iterations_anneal_now - iterations_anneal_pre
    
    print "Iteration: ", iterations_anneal_now, iterations_anneal_pre, iterations_anneal
    print "The previous coregistration gives a mapping12 with the following loss:"        
    loss_coregistration_1nn = loss_function(mapping12_coregistration_1nn)
    print "loss =", loss_coregistration_1nn

    #iterations_anneal = 100
    print "Simulated Annealing"
    np.random.seed(1) 
    initial_state =  mapping12_coregistration_1nn.copy()
    mapping12_best, energy_best = anneal(initial_state=initial_state, energy_function=loss_function, neighbour=neighbour, transition_probability=transition_probability, temperature=temperature_boltzmann, max_steps=iterations_anneal, energy_max=0.0, T0=200.0, log_every=1000)

    return mapping12_coregistration_1nn, loss_coregistration_1nn, mapping12_best, energy_best
Example #3
0
def optimise_func(graph):
    '''
    :param graph:
    :return:
    '''
    resources = model.Resources()
    medical = model.Medical()

    # for initial run
    LGAs = graph.nodes()
    numLGAs = len(LGAs)
    # random lists
    randList1 = np.random.rand(numLGAs)
    randList1 /= sum(randList1)
    randList2 = np.random.rand(numLGAs)
    randList2 /= sum(randList2)

    proposedInterventionDict = {
        LGA: {
            Nurses: numNurses,
            Specialists: numSpec
        }
        for LGA, Nurses, Specialists, numNurses, numSpec in zip(
            LGAs, ['Nurses'] * numLGAs, ['Specialists'] *
            numLGAs, resources.nurses * randList1, resources.specialists *
            randList2)
    }

    # get all the required lga medical features
    medicalList = [
        "GPs", "Specialists", "Hospitals", "DrugServices", "NSPs",
        "Undiagnosed", "ExpectedNewInfections"
    ]
    # dictionary to store
    medicalDict = {}

    for feature in medicalList:
        # assign all medical features to dictionary
        medicalDict[feature] = nx.get_node_attributes(graph, feature)

    # get forecasts separately
    forecasts = nx.get_node_attributes(graph, "Forecast")

    args = {
        'proposedInterventionDict': proposedInterventionDict,
        'forecasts': forecasts,
        'resources': resources,
        'medical': medical,
        'medicalServices': medicalDict
    }

    #### Run optimisation
    optimalSolution, optimalCost = sim_anneal.anneal(objective_func, **args)

    return optimalSolution, optimalCost
def tracts_mapping(tractography1, tractography2, loss_function, neighbour, iterations_anneal):
        
    print
    print "The best coregistration+1NN gives a mapping12 with the following loss:"
    dm12 = bundles_distances_mam(tractography1, tractography2)
    mapping12_coregistration_1nn = np.argmin(dm12, axis=1)
    loss_coregistration_1nn = loss_function(mapping12_coregistration_1nn)
    print "loss =", loss_coregistration_1nn

    #iterations_anneal = 100
    print "Simulated Annealing"
    np.random.seed(1) 
    initial_state =  mapping12_coregistration_1nn.copy()
    mapping12_best, energy_best = anneal(initial_state=initial_state, energy_function=loss_function, neighbour=neighbour, transition_probability=transition_probability, temperature=temperature_boltzmann, max_steps=iterations_anneal, energy_max=0.0, T0=200.0, log_every=1000)

    return mapping12_coregistration_1nn, loss_coregistration_1nn, mapping12_best, energy_best
Example #5
0
def main(protein):

	protein_array = copy.deepcopy(protein)
	for i in range(4, len(protein)):
		best_score = 0
		best_protein = []
		for j in range(8):
			protein_object = functions.protein_place(protein[i])
			new_protein = simulated_annealing.anneal(protein_object, i+10*j, 1)
			print "result:"
			print i,new_protein[0], new_protein[1]
			# folder_iter.write_csv(new_protein[2], 'result_anneal%s' %(i+10*j))
			if new_protein[0]<best_score:
				best_score = new_protein[0]
				best_protein = copy.deepcopy(new_protein[1])
			functions.Visualizer2D(new_protein[1], protein[i], new_protein[0], i+10*j + 800)
		functions.Visualizer2D(best_protein, protein[i], best_score, i+10*j + 900)
Example #6
0
def main():

    # length = 50
    # h_concentration = 30
    # protein_array = copy.copy(protein_generator.protein_generator(length, h_concentration, 100))
    # result_array = []
    # for protein in protein_array:
    # 	protein_object = functions.protein_place(protein)
    # 	print protein_object
    # 	configurations = 500
    # 	start_pos = folder_iter.random_sampling(protein_object, configurations, 5)
    # 	# folder_iter.write_csv(start_pos, 'random_sampling%s' %protein)
    # 	theo = test.theo_score(protein)
    # 	score_saver = [protein, configurations] + [0]*(theo[0]+1)
    # 	print score_saver
    # 	for result in start_pos:
    # 		score_saver[abs(result[0])+2] += 1
    # 	high_score = protein_generator.highscorefreq(score_saver)
    # 	result_array.append(score_saver)
    # folder_iter.write_csv(result_array, 'randomsampling_overview%s_%s' %(length, h_concentration))
    protein_array = csv_move.make_array()
    # # csv_name =
    # f = open('results/final/randomsampling_overview50_20.csv','r')
    # data = csv.reader(f, delimiter=',')

    # for row in data:
    # 	if row[0] != 'protein':
    # 		protein_array.append(row[0])

    # print protein_array

    for j in range(len(protein_array)):
        protein_object = functions.protein_place(protein_array[j])
        print 'protein_object made'
        for i in range(14):
            new_protein = simulated_annealing.anneal(protein_object,
                                                     'test7%s' % (130 + i), 1)
            # print 'new_protein made'
            folder_iter.write_csv(
                new_protein[2],
                'SA_50_20_15/result_anneal%s' % (protein_array[j] + str(i)))
            # print 'written to csv'
            functions.Visualizer2D(new_protein[1], protein_array[j],
                                   new_protein[0],
                                   'anneal7%s' % (protein_array[j] + str(i)))
            print 'SA succes'
Example #7
0
def main(protein):

    protein_array = copy.deepcopy(protein)
    for j in range(len(protein_array)):
        protein_object = functions.protein_place(protein_array[j])
        print 'protein_object made'
        for i in range(20):
            new_protein = simulated_annealing.anneal(protein_object,
                                                     'test%s' % (130 + i), 1)
            # print 'new_protein made'
            folder_iter.write_csv(
                new_protein[2],
                'result_anneal%s' % (protein_array[j] + str(i)))
            # print 'written to csv'
            functions.Visualizer2D(new_protein[1], protein_array[j],
                                   new_protein[0],
                                   'anneal%s' % (protein_array[j] + str(i)))
            print 'hillclimber succes'
Example #8
0
def hybrid_system():
    # load data and functions
    slot_presentation, presentation_presentation, presentation_supervisor, supervisor_preference = dt.load()

    # initialize matrices
    slot_no = slot_presentation.shape[0]
    presentation_no = slot_presentation.shape[1]
    population_size = 10
    population = np.empty([population_size, slot_no, presentation_no], dtype=np.int8)
    penalty_points = np.empty(population_size, dtype=int)

    # create initial population
    for i in range(population_size):
        chromosome = ga.generate_chromosome(slot_presentation)
        population[i] = chromosome
        penalty_point = \
            penalty(chromosome, presentation_presentation, presentation_supervisor, supervisor_preference)[0]
        penalty_points[i] = penalty_point

    # sort initial population based on penalty points
    population = population[penalty_points.argsort()]
    penalty_points = penalty_points[penalty_points.argsort()]

    # run genetic algorithm for 100 generations
    ga_max_generations = 100
    population, penalty_points, ga_plot_data = \
        ga.reproduction(ga_max_generations, population, penalty_points, presentation_presentation,
                        presentation_supervisor, supervisor_preference)

    # run simulated annealing after running genetic algorithm
    temperature = penalty_points[population_size - 1] - penalty_points[0]
    candidate = population[0]
    penalty_point = penalty_points[0]
    best_candidate, best_penalty_point, sa_plot_data = \
        sa.anneal(temperature, candidate, penalty_point, presentation_presentation,
                  presentation_supervisor, supervisor_preference)

    # write result data
    constraint_counts = \
        penalty(best_candidate, presentation_presentation, presentation_supervisor, supervisor_preference)
    plot_data = np.concatenate([ga_plot_data, sa_plot_data])
    dt.write(best_candidate, supervisor_preference, constraint_counts, plot_data)
Example #9
0
import sys, os
import time
base_path = os.getcwd()

if __name__ == '__main__':
    if len(sys.argv) > 1:
        rel_path = sys.argv[1]
    else:
        rel_path = 'data/kroA100.tsp'
    full_path = '/'.join((base_path, rel_path))
    headers, cities = process_data(file_path=full_path)

    dists = Distances(
        cities=cities,
        total=headers['DIMENSION'],
        custom_alg=headers['EDGE_WEIGHT_TYPE'],
    )

    start = time.time()
    solution = anneal(
        T=10000,
        min_T=0.00001,
        alpha=0.99,
        iterations=100,
        distances=dists,
        cities=cities,
        dimension=headers['DIMENSION'],
        # plot=True,
    )
    print(time.time() - start)
        print "Random Search."
        np.random.seed(1) # this is the random seed of the optimization process
        mapping12_best_rs, energy_best_rs = random_search(loss_function=loss_function, random_state_function=informed_random_mapping, iterations=iterations_random)
        print "Best loss:", energy_best_rs

    print
    print "The best coregistration+1NN gives a mapping12 with the following loss:"
    dm12 = bundles_distances_mam(tractography1, tractography2)
    mapping12_coregistration_1nn = np.argmin(dm12, axis=1)
    loss_coregistration_1nn = loss_function(mapping12_coregistration_1nn)
    print "loss =", loss_coregistration_1nn

    if do_simulated_annealing:
        print
        print "Simulated Annealing"
        np.random.seed(1) # this is the random seed of the optimization process
        # initial_state = random_mapping(size1, size2)
        #initial_state = mapping12_best_rs.copy()
        initial_state =  mapping12_coregistration_1nn.copy()
        mapping12_best, energy_best = anneal(initial_state=initial_state, energy_function=loss_function, neighbour=neighbour4, transition_probability=transition_probability, temperature=temperature_boltzmann, max_steps=iterations_anneal, energy_max=0.0, T0=200.0, log_every=1000)
    
    ren = fvtk.ren() 
    ren = visualize(ren,tractography1[:6],tractography2,mapping12_best)
    fvtk.show(ren)
    
    ren1 = fvtk.ren() 
    ren1 = visualize(ren1,tractography1[6:12],tractography2,mapping12_best[6:])
    fvtk.show(ren1)
    
    
# Fix schedule such as the time for sleeping
schedule.put_act("Sleep", "00:00", "08:00")
schedule.put_act("Lunch", "12:00", "13:00")
schedule.put_act("Nap", "15:00", "16:00")
schedule.put_act("Dinner", "18:00", "20:00")

# Take in tasks
tasks = set()
tasks.add(
    Task("Essay",
         priority=3,
         end_date="2018-01-14",
         estimated_time=8 * 60,
         category="Assignment"))
tasks.add(
    Task("Programming",
         priority=3,
         end_date="2018-01-19",
         estimated_time=4 * 60,
         category="Assignment"))
tasks.add(
    Task("Writing",
         priority=3,
         end_date="2018-01-30",
         estimated_time=8 * 60,
         category="Assignment"))

# Generate the Schedule and check with Machine Learning algorithm
hill_climbing(schedule, tasks)
schedule = anneal(schedule, list(tasks), 0.1, 0.1, 0.9)
print(schedule)
Example #12
0
def anneal(new_start,random_tour_permutations,tour_function,runs,start_temp,alpha):
    from simulated_annealing import anneal
    score,path=anneal(new_start,random_tour_permutations,tour_function,runs,start_temp,alpha)
    return score,path
Example #13
0
# tasks.add(Task("Essay", priority=3, end_date="2018-01-20", estimated_time=10*60, category="Assignment"))
# tasks.add(Task("Programming", priority=3, end_date="2018-01-20", estimated_time=10*60, category="Assignment"))
# tasks.add(Task("Writing", priority=3, end_date="2018-01-20", estimated_time=10*60, category="Assignment"))
# tasks.add(Task("Manga", priority=3, end_date="2018-01-20", estimated_time=10*60, category="Assignment"))

training_x = []
training_y = []

while True:
    var_score, deadline_score, cont_score = random(), random(), random()

    # Generate the Schedule
    # Use machine learning algorithm to check the variability, deadline and continuity preference

    hill_climbing(schedule, tasks)
    schedule = anneal(schedule, list(tasks), var_score, deadline_score,
                      cont_score)

    if len(training_x) < 100:
        print(schedule)

    else:
        prediction = predict(np.array([var_score, deadline_score, cont_score]),
                             np.array(training_x), np.array(training_y))
        if not prediction:
            continue
        else:
            print(schedule)

    satisfied = input("Are you satisfied with the schedule? (Y/N)\n")
    answer = None
    if satisfied == "Y":