Exemple #1
0
def optimize():
    state = [
        0, 3, 2, 1, 0, 3, 2, 3, 1, 2, 2, 2, 3, 2, 1, 3, 0, 0, 0, 1, 3, 2, 0, 2,
        0, 1, 0, 2, 2, 1, 2, 2, 0, 3
    ]
    annealer = Annealer(energy, move)
    schedule = annealer.auto(state, minutes=0.1)
    state, e = annealer.anneal(state,
                               schedule['tmax'],
                               schedule['tmin'],
                               schedule['steps'],
                               updates=6)
    print(state)  # the "final" solution
Exemple #2
0
    def __call__(self, azAltList):
        """Reorder the points in azAltList to make a short path from the first to the last.

        Start at the point closest to az=90 (center of wrap), so the telescope has
        unambiguous wrap for the first point.

        Inputs:
        - azAltList: a set of (x, y, ...?) data where x, y are positions on a plane
        - minToMax: if True, start from the smallest azimuth, else start at the largest
        """
        # numPoints = len(azAltList)
        begAzAltList = numpy.array(azAltList, dtype=float, copy=True)

        # find point closest to center of azimuth range and start with that
        ctrAz = 90
        minInd = numpy.argmin(numpy.square(begAzAltList[:, 0] - ctrAz))
        if minInd != 0:
            begAzAltList[0], begAzAltList[minInd] = tuple(begAzAltList[minInd]), tuple(begAzAltList[0])
        initialEnergy = self.computeEnergy(begAzAltList)
        annealer = Annealer(self.computeEnergy, self.changeState)
        azAltList = annealer.anneal(begAzAltList, initialEnergy, self.minTemp, self.nIter, self.nToPrint)[0]
        return azAltList
Exemple #3
0
    capitals = set( [geonameid.strip() for geonameid in open('Capitals.txt')] )
    places = load_places(countriesfile, inputfiles, fonts, zoom)

    print '-' * 80
    
    print len(places._moveable), 'moveable places vs.', len(places._places), 'others'

    print '-' * 80
    
    def state_energy(places):
        return places.energy()

    def state_move(places):
        places.move()
    
    places, e = Annealer(state_energy, state_move).auto(places, minutes, 50)

    print '-' * 80
    
    osm = Provider()
    point_features, label_features = [], []
    visible_places = []
    
    for place in sorted(places):
    
        is_visible = True
        
        for other in visible_places:
            if place.overlaps(other):
                print 'skip', place.name, 'because of', other.name
                is_visible = False
    # Create config parser to get various fields.
    configParser = ConfigParser.ConfigParser()
    configFilePath = config
    configParser.read(configFilePath)

    classes.init_classes(config)
    project_id_mappings = configParser.get('files', 'project_id_mappings')
    capacity = configParser.getint('valid_values', 'capacity')
    capacity_w = configParser.getint('valid_values', 'capacity_w')
    temp = configParser.getint('valid_values', 'temperature')
    iters = configParser.getint('valid_values', 'iterations')
    team_size = capacity

    # Creating the annealer with our energy and move functions.
    annealer = Annealer(pgd.energy, pgd.move)
    all_projects = util.generate_all_projects(config)
    students = util.create_students_from_input(input_file, config)

    sol = initial_solution.random_initial_solution_for_diversity(
        students, all_projects, num_teams)

    use_diversity = True
    use_file = False
    if (set_output_file):
        test.manual_schedule(use_file, students, sol, None, annealer,
                             use_diversity, input_file, temp, iters,
                             output_file)
    else:
        test.manual_schedule(use_file, students, sol, None, annealer,
                             use_diversity, input_file, temp, iters)
def run(schedule=None):
    state = []

    def reserve_move(state):
        """
        Select random watershed
        then
        Add watershed (if not already in state) OR remove it. 
        * This is the Marxan technique as well
        """
        huc = hucs[int(random.random() * num_hucs)]
        #huc = hucs[random.randint(0,num_hucs-1)]

        if huc in state:
            state.remove(huc)
        else:
            state.append(huc)

    def reserve_energy(state):
        """
        The "Objective Function"...
        Calculates the 'energy' of the reserve.
        Should incorporate costs of reserve and penalties 
        for not meeting species targets. 

        Note: This example is extremely simplistic compared to 
        the Marxan objective function (see Appendix B in Marxan manual)
        but at least we have access to it!
        """
        # Initialize variables
        energy = 0
        totals = {}
        for fish in species:
            totals[fish] = 0

        # Get total cost and habitat in current state
        for huc in state:
            watershed = watersheds[huc]
            # Sum up total habitat for each fish
            for fish in species:
                if energy == 0:
                    # reset for new calcs ie first watershed
                    totals[fish] = watershed[fish]
                else:
                    # add for additional watersheds
                    totals[fish] += watershed[fish]

            # Incorporate Cost of including watershed
            energy += watershed['watershed_cost']

        # incorporate penalties for missing species targets
        for fish in species:
            pct = totals[fish] / targets[fish]
            if pct < 1.0: # if missed target, ie total < target
                if pct < 0.1:
                    # Avoid zerodivision errors 
                    # Limits the final to 10x specified penalty
                    pct = 0.1
                penalty = int(penalties[fish] / pct)
                energy += penalty 
        
        return energy

    annealer = Annealer(reserve_energy, reserve_move)
    if schedule is None:
       print('----\nAutomatically determining optimal temperature schedule')
       schedule = annealer.auto(state, minutes=6)

    try:
        schedule['steps'] = NUMITER
    except:
        pass # just keep the auto one

    print( '---\nAnnealing from %.2f to %.2f over %i steps:' % (schedule['tmax'],
            schedule['tmin'], schedule['steps']))

    state, e = annealer.anneal(state, schedule['tmax'], schedule['tmin'], 
                               schedule['steps'], updates=6)

    print("Reserve cost = %r" % reserve_energy(state))
    state.sort()
    for watershed in state:
        print("\t", watershed, watersheds[watershed])
    return state, reserve_energy(state), schedule
Exemple #6
0
        index = random.randrange(0, len(cvalues))
        system[1] = cvalues[index]
    elif component == 2:
        index = random.randrange(0, len(rvalues))
        system[2] = rvalues[index]
    elif component == 3:
        index = random.randrange(0, len(rvalues))
        system[3] = rvalues[index]


if __name__ == '__main__':

    # set up simulated annealing algorithm
    units = ('F', 'F', u'Ω', u'Ω')  # units of the values in the system
    initial_system = [cvalues[0], cvalues[0], rvalues[0], rvalues[0]]
    annealer = Annealer(energy, move)
    schedule = annealer.auto(initial_system, minutes=0.1)

    # run simulated annealing algorithm and compute properties of the final system
    final_system, error = annealer.anneal(initial_system,
                                          schedule['tmax'],
                                          schedule['tmin'],
                                          schedule['steps'],
                                          updates=100)
    final_frf = frf(final_system)
    final_f0 = f0(final_system)
    final_q = q(final_system)
    final_vals = [metric_prefix(*s) for s in zip(final_system, units)]

    print 'Soln: (%s), Remaining Energy: %s' % (', '.join(final_vals), error)
Exemple #7
0
    # Create a ConfigParser to get various fields from the config file.
    configParser = ConfigParser.ConfigParser()
    configFilePath = config
    configParser.read(configFilePath)

    classes.init_classes(config)
    project_id_mappings = configParser.get('files', 'project_id_mappings')
    capacity = configParser.getint('valid_values', 'capacity')
    capacity_w = configParser.getint('valid_values', 'capacity_w')
    temp = configParser.getint('valid_values', 'temperature')
    iters = configParser.getint('valid_values', 'iterations')
    team_size = capacity

    # Creating the annealer with our energy and move functions.
    if mode == "cc":
        annealer = Annealer(pg.energy, pg.move)
    elif mode == "co":
        annealer = Annealer(pg.energy_co, pg.move_co)
    else:
        raise FieldError("Unknown algorithm mode")
    all_projects = util.generate_all_projects(config)

    students = util.create_students_from_input(input_file, config)
    feasibles = util.create_feasible_projects(students, all_projects)

    sol = test.do_greedy_initial_solutions(students, all_projects, annealer,
                                           project_id_mappings, config)
    use_file = False
    use_diversity = False
    if (set_output_file):
        test.manual_schedule(use_file, students, sol, feasibles, annealer,