def genetic_algorithm(population, fitness_fn, ngen=1000, pmut=0.0):
"""[Fig. 4.7]"""
def reproduce(p1, p2):
c = random.randrange(len(p1))
return p1[:c] + p2[c:]
for i in range(ngen):
new_population = []
for i in len(population):
p1, p2 = random_weighted_selections(population, 2, fitness_fn)
child = reproduce(p1, p2)
if random.uniform(0,1) > pmut:
child.mutate()
new_population.append(child)
population = new_population
return argmax(population, fitness_fn)
python类uniform()的实例源码
def random_weighted_selection(seq, n, weight_fn):
"""Pick n elements of seq, weighted according to weight_fn.
That is, apply weight_fn to each element of seq, add up the total.
Then choose an element e with probability weight[e]/total.
Repeat n times, with replacement. """
totals = []; runningtotal = 0
for item in seq:
runningtotal += weight_fn(item)
totals.append(runningtotal)
selections = []
for s in range(n):
r = random.uniform(0, totals[-1])
for i in range(len(seq)):
if totals[i] > r:
selections.append(seq[i])
break
return selections
#_____________________________________________________________________________
# The remainder of this file implements examples for the search algorithms.
#______________________________________________________________________________
# Graphs and Graph Problems
def RandomGraph(nodes=range(10), min_links=2, width=400, height=300,
curvature=lambda: random.uniform(1.1, 1.5)):
"""Construct a random graph, with the specified nodes, and random links.
The nodes are laid out randomly on a (width x height) rectangle.
Then each node is connected to the min_links nearest neighbors.
Because inverse links are added, some nodes will have more connections.
The distance between nodes is the hypotenuse times curvature(),
where curvature() defaults to a random number between 1.1 and 1.5."""
g = UndirectedGraph()
g.locations = {}
## Build the cities
for node in nodes:
g.locations[node] = (random.randrange(width), random.randrange(height))
## Build roads from each city to at least min_links nearest neighbors.
for i in range(min_links):
for node in nodes:
if len(g.get(node)) < min_links:
here = g.locations[node]
def distance_to_node(n):
if n is node or g.get(node,n): return infinity
return distance(g.locations[n], here)
neighbor = argmin(nodes, distance_to_node)
d = distance(g.locations[neighbor], here) * curvature()
g.connect(node, neighbor, int(d))
return g
def rate(self, message_object, user):
'''
# totally not rigged or something
def isDevMentioned():
for u in message_object.mentions:
if u.name == "Theraga" or u.name == "Dynista":
return True
return False
if user == "theraga" or user == "Theraga" or user == "dynista" or user == "Dynista" or isDevMentioned():
await self.pm.client.send_message(message_object.channel, "I would rate **" + user + "** 100.00/100")
else:
'''
number = round(random.uniform(1, 100), 2)
print(message_object.mentions)
await self.pm.client.send_message(message_object.channel,
"I would rate " + "**" + user + "** " + str(number) + "/100")
def __call__(self, img):
for attempt in range(10):
area = img.size[0] * img.size[1]
target_area = random.uniform(0.9, 1.) * area
aspect_ratio = random.uniform(7. / 8, 8. / 7)
w = int(round(math.sqrt(target_area * aspect_ratio)))
h = int(round(math.sqrt(target_area / aspect_ratio)))
if random.random() < 0.5:
w, h = h, w
if w <= img.size[0] and h <= img.size[1]:
x1 = random.randint(0, img.size[0] - w)
y1 = random.randint(0, img.size[1] - h)
img = img.crop((x1, y1, x1 + w, y1 + h))
assert (img.size == (w, h))
return img.resize((self.size, self.size), self.interpolation)
# Fallback
scale = Scale(self.size, interpolation=self.interpolation)
crop = CenterCrop(self.size)
return crop(scale(img))
def __call__(self, img):
for attempt in range(10):
area = img.size[0] * img.size[1]
target_area = random.uniform(0.70, 0.98) * area
aspect_ratio = random.uniform(5. / 8, 8. / 5)
w = int(round(math.sqrt(target_area * aspect_ratio)))
h = int(round(math.sqrt(target_area / aspect_ratio)))
if random.random() < 0.5:
w, h = h, w
if w <= img.size[0] and h <= img.size[1]:
x1 = random.randint(0, img.size[0] - w)
y1 = random.randint(0, img.size[1] - h)
img = img.crop((x1, y1, x1 + w, y1 + h))
assert (img.size == (w, h))
return img.resize((self.size, self.size), self.interpolation)
# Fallback
scale = Scale(self.size, interpolation=self.interpolation)
crop = CenterCrop(self.size)
return crop(scale(img))
def __call__(self, img):
for attempt in range(10):
area = img.size[0] * img.size[1]
target_area = random.uniform(0.70, 0.98) * area
aspect_ratio = random.uniform(5. / 8, 8. / 5)
w = int(round(math.sqrt(target_area * aspect_ratio)))
h = int(round(math.sqrt(target_area / aspect_ratio)))
if random.random() < 0.5:
w, h = h, w
if w <= img.size[0] and h <= img.size[1]:
x1 = random.randint(0, img.size[0] - w)
y1 = random.randint(0, img.size[1] - h)
img = img.crop((x1, y1, x1 + w, y1 + h))
assert (img.size == (w, h))
return img.resize((self.size, self.size), self.interpolation)
# Fallback
scale = Scale(self.size, interpolation=self.interpolation)
crop = CenterCrop(self.size)
return crop(scale(img))
def __call__(self, img):
for attempt in range(10):
area = img.size[0] * img.size[1]
target_area = random.uniform(0.9, 1.) * area
aspect_ratio = random.uniform(7. / 8, 8. / 7)
w = int(round(math.sqrt(target_area * aspect_ratio)))
h = int(round(math.sqrt(target_area / aspect_ratio)))
if random.random() < 0.5:
w, h = h, w
if w <= img.size[0] and h <= img.size[1]:
x1 = random.randint(0, img.size[0] - w)
y1 = random.randint(0, img.size[1] - h)
img = img.crop((x1, y1, x1 + w, y1 + h))
assert (img.size == (w, h))
return img.resize((self.size, self.size), self.interpolation)
# Fallback
scale = Scale(self.size, interpolation=self.interpolation)
crop = CenterCrop(self.size)
return crop(scale(img))
def test_put():
sink = IntFloatDataSink()
values = [random.randint(-VALUES_MAX, VALUES_MAX) for _ in range(VALUES_COUNT)]
for value in values:
result = sink.put(int, value)
assert result is None
assert value in sink.items[int]
values = [random.uniform(-VALUES_MAX, VALUES_MAX) for _ in range(VALUES_COUNT)]
for value in values:
result = sink.put(float, value)
assert result is None
assert value in sink.items[float]
def test_wildcard_put():
sink = SimpleWildcardDataSink()
values = [random.randint(-VALUES_MAX, VALUES_MAX) for _ in range(VALUES_COUNT)]
for value in values:
result = sink.put(int, value)
assert result is None
assert value in sink.items[int]
values = [random.uniform(-VALUES_MAX, VALUES_MAX) for _ in range(VALUES_COUNT)]
for value in values:
result = sink.put(float, value)
assert result is None
assert value in sink.items[float]
#####################
# Put Many Function #
#####################
def test_put_many():
sink = IntFloatDataSink()
values = [random.randint(-VALUES_MAX, VALUES_MAX) for _ in range(VALUES_COUNT)]
for value in values:
items = (value for _ in range(VALUES_COUNT))
result = sink.put_many(int, items)
assert result is None
assert value in sink.items[int]
values = [random.uniform(-VALUES_MAX, VALUES_MAX) for _ in range(VALUES_COUNT)]
for value in values:
items = (value for _ in range(VALUES_COUNT))
result = sink.put_many(float, items)
assert result is None
assert value in sink.items[float]
def test_wildcard_put_many():
sink = SimpleWildcardDataSink()
values = [random.randint(-VALUES_MAX, VALUES_MAX) for _ in range(VALUES_COUNT)]
for value in values:
items = (value for _ in range(VALUES_COUNT))
result = sink.put_many(int, items)
assert result is None
assert value in sink.items[int]
values = [random.uniform(-VALUES_MAX, VALUES_MAX) for _ in range(VALUES_COUNT)]
for value in values:
items = (value for _ in range(VALUES_COUNT))
result = sink.put_many(float, items)
assert result is None
assert value in sink.items[float]
#####################
# CompositeDataSink #
#####################
def test_get():
source = IntFloatDataSource()
values = [random.randint(-VALUES_MAX, VALUES_MAX) for _ in range(VALUES_COUNT)]
for value in values:
query = {VALUE_KEY: value}
result = source.get(int, query)
assert type(result) is int
assert result == value
values = [random.uniform(-VALUES_MAX, VALUES_MAX) for _ in range(VALUES_COUNT)]
for value in values:
query = {VALUE_KEY: value}
result = source.get(float, query)
assert type(result) is float
assert result == value
def test_wildcard_get():
source = SimpleWildcardDataSource()
values = [random.randint(-VALUES_MAX, VALUES_MAX) for _ in range(VALUES_COUNT)]
for value in values:
query = {VALUE_KEY: value}
result = source.get(int, query)
assert type(result) is int
assert result == value
values = [random.uniform(-VALUES_MAX, VALUES_MAX) for _ in range(VALUES_COUNT)]
for value in values:
query = {VALUE_KEY: value}
result = source.get(float, query)
assert type(result) is float
assert result == value
#####################
# Get Many Function #
#####################
def mutation(cls, indiv):
newInd = indiv.duplicate()
nbMute = int(random.random()*(len(newInd.__x)-1))+1
toMute = []
for i, x in enumerate(indiv.__x):
if len(toMute) < nbMute:
toMute.append(i)
else:
iMin = 0
for im, i2 in enumerate(toMute):
if abs(indiv.__x[i2]) < abs(indiv.__x[toMute[iMin]]):
iMin = im
if abs(x) > abs(indiv.__x[toMute[iMin]]):
toMute[iMin] = i
for i in toMute:
newInd.__x[i] = random.uniform(cls.__BOUNDS[0], cls.__BOUNDS[1])
return newInd
def __generateRandomVarValue(cls, iVar):
# 1- Get the definition domain of the variable
defDomain = cls.VARIABLES_RANGES[iVar]
if defDomain is None:
randFloat = random.uniform(-sys.maxint-1, sys.maxint)
else:
# 2- Check the open/closed bounds
includeFirst = defDomain[0] == '['
includeLast = defDomain[-1] == ']'
# 3- Get a random number in the domain
defDomain = eval('[' + defDomain[1:-1] + ']')
randFloat = random.random()*(defDomain[1]-defDomain[0]) + defDomain[0]
# 4- Check the bounds
while (randFloat == defDomain[0] and not includeFirst) or\
(randFloat == defDomain[1] and not includeLast):
randFloat = random.random()*(defDomain[1]-defDomain[0]) + defDomain[0]
# 5- Cast the variable type
return cls.VARIABLES_TYPE(randFloat)
# ----------------------
def recaptcha(self):
""" Check if we need to solve a captcha.
This will open in the default browser.
If we choose to not solve the captcha should it be required,
we will then be considered a 'lurker' and we will not be able to chat
and our name will be shown as a guest name in the room.
"""
t = str(random.uniform(0.9, 0.10))
_url = 'https://tinychat.com/cauth/captcha?{0}'.format(t)
_response = util.web.http_get(url=_url, json=True, proxy=self.proxy)
log.debug('recaptcha response: %s' % _response)
if _response['json'] is not None:
if _response['json']['need_to_solve_captcha'] == 1:
link = 'https://tinychat.com/cauth/recaptcha?token={0}'.format(_response['json']['token'])
webbrowser.open(link, new=True)
print (link)
raw_input('Solve the captcha and click enter to continue.')
def mutation(self, mutation_type):
if mutation_type not in MUTATION_TYPES:
raise GenomeError("mutation type not supported")
threshold = random.uniform(self.mutation_lower_threshold, self.mutation_higher_threshold)
if threshold < self.mutation_threshold:
return
if mutation_type == "add_node":
self.mutate_add_node()
elif mutation_type == "remove_node":
self.mutate_remove_node()
elif mutation_type == "add_connection":
self.mutate_add_connection()
elif mutation_type == "remove_connection":
self.mutate_remove_connection()
else:
raise GenomeError("something wrong happened in mutation.")
def serviceB(context=None):
#reuse context if it exists, otherwise make a new one
context = context or zmq.Context.instance()
service = context.socket(zmq.DEALER)
#identify worker
service.setsockopt(zmq.IDENTITY,b'B')
service.connect("tcp://localhost:5560")
while True:
message = service.recv()
with myLock:
print "Service B got:"
print message
if message == "Service B":
#do some work
time.sleep(random.uniform(0,0.5))
service.send(b"Service B cleaned your room")
elif message == "END":
break
else:
with myLock:
print "the server has the wrong identities!"
break
def query(self, images):
if self.pool_size == 0:
return images
return_images = []
for image in images.data:
image = torch.unsqueeze(image, 0)
if self.num_imgs < self.pool_size:
self.num_imgs = self.num_imgs + 1
self.images.append(image)
return_images.append(image)
else:
p = random.uniform(0, 1)
if p > 0.5:
random_id = random.randint(0, self.pool_size-1)
tmp = self.images[random_id].clone()
self.images[random_id] = image
return_images.append(tmp)
else:
return_images.append(image)
return_images = Variable(torch.cat(return_images, 0))
return return_images