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
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
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
state[index] = random.randint(0, p-1) # we now have to reset this array for i in xrange(e): prev_equations[i] = satisfies(equations[i], state) from anneal import Annealer annealer = Annealer(energy, move) for file in range(2,3): fin = open("../%d.in" % file, "r") v, e, p = map(int, fin.readline().split()) # precompute modular inverses inverses = [None] + [pow(i, p-2, p) for i in xrange(1, p)] equations = [map(int, fin.readline().split()) for _ in xrange(e)] # index i matches to equation indices that include it includes = [ [] for _ in xrange(v) ] for i, eqn in enumerate(equations): a,b,c,d,e = eqn includes[b].append(i) includes[d].append(i) # initial state state = [random.randint(0, p-1) for _ in xrange(v)] # initial satisfied array prev_equations = [satisfies(eqn, state) for eqn in equations] changed_index = [0] state, e = annealer.anneal(state, 100, 100, 350000, updates=6) print " ".join(map(str, state)) print sum(satisfies(eqn, state) for eqn in equations) # the "final" score
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) # calculate data for graphs freqs = range(1000000) # response from 0 Hz to 1 MHz response = [dB(final_frf(f)) for f in freqs] natural = final_f0, dB(final_frf(final_f0)) target = target_freq, dB(final_frf(target_freq)) step_freqs, step_response = stepResponse(final_system)
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
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 = random.choice(hucs) 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] = float(watershed[fish]) else: # add for additional watersheds totals[fish] += float(watershed[fish]) # Incorporate Cost of including watershed energy += watershed["total_cost"] # incorporate penalties for missing species targets for fish in species: if run_target[fish] > 0: pct = totals[fish] / run_target[fish] else: pct = 1 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
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) # calculate data for graphs freqs = range(1000000) # response from 0 Hz to 1 MHz response = [dB(final_frf(f)) for f in freqs] natural = final_f0, dB(final_frf(final_f0)) target = target_freq, dB(final_frf(target_freq)) step_freqs, step_response = stepResponse(final_system)
# assign every other variable to satisfy most with this value for index # ignore any equation that does not include index scores = [ [0]*p for _ in xrange(v)] for eqn_ind in includes[index]: a, b, c, d, e = equations[eqn_ind] if index == b: satisfies = (-inverses[a] * (c * state[d] + e)) % p scores[d][satisfies] += 1 else: # index == d satisfies = (-inverses[c] * (a * state[b] + e)) % p scores[b][satisfies] += 1 for i in xrange(v): if i == index: continue # there will be ties. Choose randomly best_score = max(scores[i]) choices = [(value,score) for value,score in enumerate(scores[i]) if score == best_score] state[i] = random.choice(choices)[0] def move(state): # change one variable to something else ind = random.randint(0, v-1) changed_index[0] = ind state[ind] = random.randint(0, p-1) from anneal import Annealer annealer = Annealer(energy, move) state, e = annealer.anneal(state, 100, 0.001, 500000, updates=6) print sum(satisfies(eqn, state) for eqn in equations) # the "final" score
def move(state): i = random.randint(0, 5) if state[i] < 700 and state[i] > 0: state[i] = random.randint(state[i] - 1, state[i] + 1) else: state[i] = random.randint(0, 700) import time start_time = time.time() annealer = Annealer(energy, move) schedule = annealer.auto(state, minutes=5) state, e = annealer.anneal(state, schedule['tmax'], schedule['tmin'], schedule['steps'], updates=1000) state, e = annealer.anneal(state, 10000, 0.1, 100000, updates=30) # Parim klaaside kombinatsioon for i in range(len(state)): print(klaasid[i]) print(state[i]) # Minimeeritava funktsiooni väärtus, mis vastab parimale klaasi kombinatsioonile print('Minimeeritava funktsiooni väärtus:') print(energy(state)) np.savetxt("sub_uus.csv", state, delimiter=",")
def run(schedule=None): state = [] def reserve_move(state): """ 1st Random choice: Select watershed then Add watershed (if not already in state) OR remove it. This is the Marxan method """ huc = hucs[random.randint(num_hucs)] if huc in state: state.remove(huc) return ('r', huc) else: state.append(huc) return ('a', 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! """ energy = 0 totals = {} for huc in state: watershed = watersheds[huc] # Sum up total habitat for each fish for fish in species: print fish if energy == 0: # reset for new calcs totals[fish] = watershed[fish] print fish, totals else: totals[fish] += watershed[fish] print fish, totals # Incorporate Cost of including watershed energy += watershed['total_cost'] # incorporate penalties for missing species targets for fish in species: print totals print targets 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: # Automatically chosen temperature schedule schedule = annealer.auto(state, minutes=0.3) 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
def run(schedule=None): def reserve_move(state): """ 1st Random choice: Select watershed then Add watershed (if not already in state) OR remove it. This is the Marxan method """ cfkey = cfkeys[np.random.randint(num_cfs)] if cfkey in state: state.remove(cfkey) return ("r", cfkey) else: state.append(cfkey) return ("a", cfkey) 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! """ start = datetime.now() target_dict = {} penalty_dict = {} for cfkey in cfkeys: if cfkey in state: target_dict[cfkey] = 0.5 else: target_dict[cfkey] = 0 penalty_dict[cfkey] = 1.0 scalefactor = 5 name = ( str(len([k for k, v in target_dict.items() if v > 0])) + ": " + " ".join([x.split("---")[1] for x in state])[:100] ) wp = Scenario( input_targets=json.dumps(target_dict), input_penalties=json.dumps(penalty_dict), input_relativecosts=json.dumps(costs_dict), input_geography=json.dumps(geography_list), input_scalefactor=scalefactor, name=name, user=user, ) wp.save() url = wp.get_absolute_url() time.sleep(3) # assuming it takes at least X secs while not process_is_complete(url): time.sleep(0.2) wp.process_results() res = wp.results energy = res["surrogate"]["objective_score"] elapsed = datetime.now() - start print "Scenario %d\t\t%s secs\t\tscore = %s" % ( wp.id, elapsed.seconds + elapsed.microseconds / 1000000.0, energy, ) return energy # init # based on the single species chart and the best run of a previous cycle, # we know these are good starting points state = [ u"locally-endemic---chub-borax-lake", u"locally-endemic---whitefish-mountain", u"widespread-salmon---pink-odd-year-esu", u"widespread-salmon---chum-puget-soundstrait-of-georgia-esu", u"widespread-steelhead---steelhead-lower-columbia-river-winter-dps", u"widespread-steelhead---steelhead-oregon-coast-dps", u"locally-endemic---dace-longnose", u"locally-endemic---whitefish-pygmy", u"widespread-salmon---chinook-lower-columbia-river-spring-esu", u"locally-endemic---sculpin-shoshone", u"widespread-salmon---coho-southern-oregonnorthern-california-esu", u"locally-endemic---chub-blue", u"widespread-salmon---coho-southwest-washington-esu", u"widespread-steelhead---steelhead-olympic-peninsula-dps", u"widespread-salmon---sockeye-lake-wenatchee-esu", ] start_energy = reserve_energy(state) print "Starting energy is ", start_energy annealer = Annealer(reserve_energy, reserve_move) 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=int(schedule["steps"] / 10.0) ) print "Reserve cost = %r" % reserve_energy(state) state.sort() for key in state: print "\t", key return state, reserve_energy(state), schedule