Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Python 3 compatibility #79

Open
wants to merge 25 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@

\.tox/

Pyevolve\.egg-info/

*.pyc

dist/

build/

\.idea/

\.coverage
11 changes: 11 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
language: python
python:
- "2.7"
- "3.5"
- "3.6"
- "pypy3.5"
install:
- pip install -r requirements_test.txt
- pip install tox-travis
script:
- tox
2 changes: 2 additions & 0 deletions README → README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
This is the new official Pyevolve repository.

The documentation (html rendered) is still hosted at sourceforge.net at http://pyevolve.sourceforge.net/0_6rc1/

[![Build Status](https://travis-ci.org/BubaVV/Pyevolve.svg?branch=master)](https://travis-ci.org/BubaVV/Pyevolve)
1 change: 1 addition & 0 deletions build_dist.bat
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ python setup.py build

python setup.py bdist_wininst --target-version="2.5"
python setup.py bdist_wininst --target-version="2.6"
python setup.py bdist_wininst --target-version="3.5"
python setup.py sdist --formats=gztar,zip
python setup.py bdist --formats=egg

Expand Down
1 change: 1 addition & 0 deletions build_dist.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
python setup.py build
python setup.py bdist_wininst --target-version="2.5"
python setup.py bdist_wininst --target-version="2.6"
python setup.py bdist_wininst --target-version="3.5"
python setup.py sdist
python setup.py bdist
python setup.py bdist_egg
Expand Down
5 changes: 3 additions & 2 deletions docs/source/ext/pyevolve_tooltip.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,17 @@
:license: PSF, see LICENSE for details.

"""
from sphinx.util.compat import Directive
from docutils import nodes
import re


def tip_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
matches = re.match("\<(?P<word>\w+)\> (?P<tip>.*)", text)
matches_tuple = matches.group("tip"), matches.group("word")
template = """<span class="ttip" title="%s">%s</span>""" % matches_tuple
node = nodes.raw('', template, format='html')
return [node], []


def setup(app):
app.add_role('tip', tip_role)
app.add_role('tip', tip_role)
13 changes: 8 additions & 5 deletions docs/source/sphinx06_code_patch.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,12 @@ def highlightlang_directive(name, arguments, options, content, lineno,
return [addnodes.highlightlang(lang=arguments[0].strip(),
linenothreshold=linenothreshold)]


highlightlang_directive.content = 0
highlightlang_directive.arguments = (1, 0, 0)
highlightlang_directive.options = {'linenothreshold': directives.unchanged}
directives.register_directive('highlight', highlightlang_directive)
directives.register_directive('highlightlang', highlightlang_directive) # old name
directives.register_directive('highlightlang', highlightlang_directive) # old name


# ------ code-block directive -------------------------------------------------------
Expand All @@ -50,6 +51,7 @@ def codeblock_directive(name, arguments, options, content, lineno,
literal['linenos'] = 'linenos' in options
return [literal]


codeblock_directive.content = 1
codeblock_directive.arguments = (1, 0, 0)
codeblock_directive.options = {'linenos': directives.flag}
Expand All @@ -59,7 +61,7 @@ def codeblock_directive(name, arguments, options, content, lineno,

# ------ literalinclude directive ---------------------------------------------------

def literalinclude_directive(name, arguments, options, content, lineno,
def literalinclude_directive(name, arguments, options, content, lineno, # noqa
content_offset, block_text, state, state_machine):
"""Like .. include:: :literal:, but only warns if the include file is not found."""
if not state.document.settings.file_insertion_enabled:
Expand Down Expand Up @@ -99,13 +101,13 @@ def literalinclude_directive(name, arguments, options, content, lineno,
'Object named %r not found in include file %r' %
(objectname, arguments[0]), line=lineno)]
else:
lines = lines[tags[objectname][1] - 1 : tags[objectname][2] - 1]
lines = lines[tags[objectname][1] - 1: tags[objectname][2] - 1]

linespec = options.get('lines')
if linespec is not None:
try:
linelist = parselinenos(linespec, len(lines))
except ValueError, err:
except ValueError as err: # TODO untested
return [state.document.reporter.warning(str(err), line=lineno)]
lines = [lines[i] for i in linelist]

Expand All @@ -126,7 +128,7 @@ def literalinclude_directive(name, arguments, options, content, lineno,

text = ''.join(lines)
text = re.sub("\r\n", "\n", text)

retnode = nodes.literal_block(text, text, source=fn)
retnode.line = 1
if options.get('language', ''):
Expand All @@ -136,6 +138,7 @@ def literalinclude_directive(name, arguments, options, content, lineno,
state.document.settings.env.note_dependency(rel_fn)
return [retnode]


literalinclude_directive.options = {'linenos': directives.flag,
'language': directives.unchanged_required,
'encoding': directives.encoding,
Expand Down
6 changes: 4 additions & 2 deletions examples/pyevolve_ex10_g1dbinstr.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from pyevolve import Selectors
from pyevolve import Mutators


# This function is the evaluation function, we want
# to give high score to more zero'ed chromosomes
def eval_func(chromosome):
Expand All @@ -15,6 +16,7 @@ def eval_func(chromosome):

return score


def run_main():
# Genome instance
genome = G1DBinaryString.G1DBinaryString(50)
Expand All @@ -33,8 +35,8 @@ def run_main():
ga.evolve(freq_stats=20)

# Best individual
print ga.bestIndividual()
print(ga.bestIndividual())


if __name__ == "__main__":
run_main()

12 changes: 7 additions & 5 deletions examples/pyevolve_ex11_allele.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from pyevolve import Initializators
from pyevolve import GAllele


# This function is the evaluation function, we want
# to give high score to more zero'ed chromosomes
def eval_func(chromosome):
Expand All @@ -26,22 +27,23 @@ def eval_func(chromosome):

return score


def run_main():
# Genome instance
setOfAlleles = GAllele.GAlleles()

# From 0 to 10 we can have only some
# defined ranges of integers
for i in xrange(11):
for i in range(11):
a = GAllele.GAlleleRange(0, i)
setOfAlleles.add(a)

# From 11 to 19 we can have a set
# of elements
for i in xrange(11, 20):
for i in range(11, 20):
# You can even add objects instead of strings or
# primitive values
a = GAllele.GAlleleList(['a','b', 'xxx', 666, 0])
a = GAllele.GAlleleList(['a', 'b', 'xxx', 666, 0])
setOfAlleles.add(a)

genome = G1DList.G1DList(20)
Expand All @@ -65,8 +67,8 @@ def run_main():
ga.evolve(freq_stats=5)

# Best individual
print ga.bestIndividual()
print(ga.bestIndividual())


if __name__ == "__main__":
run_main()
run_main()
105 changes: 58 additions & 47 deletions examples/pyevolve_ex12_tsp.py
Original file line number Diff line number Diff line change
@@ -1,103 +1,114 @@
from pyevolve import G1DList, GAllele
from math import sqrt

import os
import random

from pyevolve import G1DList
from pyevolve import GSimpleGA
from pyevolve import Mutators
from pyevolve import Crossovers
from pyevolve import Consts

import sys, random
random.seed(1024)
from math import sqrt

PIL_SUPPORT = None

try:
from PIL import Image, ImageDraw, ImageFont
PIL_SUPPORT = True
except:
except ImportError:
PIL_SUPPORT = False


cm = []
cm = []
coords = []
CITIES = 100
WIDTH = 1024
HEIGHT = 768
WIDTH = 1024
HEIGHT = 768
LAST_SCORE = -1


def cartesian_matrix(coords):
""" A distance matrix """
matrix={}
for i,(x1,y1) in enumerate(coords):
for j,(x2,y2) in enumerate(coords):
dx, dy = x1-x2, y1-y2
dist=sqrt(dx*dx + dy*dy)
matrix[i,j] = dist
matrix = {}
for i, (x1, y1) in enumerate(coords):
for j, (x2, y2) in enumerate(coords):
dx, dy = x1 - x2, y1 - y2
dist = sqrt(dx * dx + dy * dy)
matrix[i, j] = dist
return matrix


def tour_length(matrix, tour):
""" Returns the total length of the tour """
total = 0
t = tour.getInternalList()
for i in range(CITIES):
j = (i+1)%CITIES
j = (i + 1) % CITIES
total += matrix[t[i], t[j]]
return total


def write_tour_to_img(coords, tour, img_file):
""" The function to plot the graph """
padding=20
coords=[(x+padding,y+padding) for (x,y) in coords]
maxx,maxy=0,0
for x,y in coords:
maxx, maxy = max(x,maxx), max(y,maxy)
maxx+=padding
maxy+=padding
img=Image.new("RGB",(int(maxx),int(maxy)),color=(255,255,255))
font=ImageFont.load_default()
d=ImageDraw.Draw(img);
num_cities=len(tour)
padding = 20
coords = [(x + padding, y + padding) for (x, y) in coords]
maxx, maxy = 0, 0
for x, y in coords:
maxx, maxy = max(x, maxx), max(y, maxy)
maxx += padding
maxy += padding
img = Image.new("RGB", (int(maxx), int(maxy)), color=(255, 255, 255))
font = ImageFont.load_default()
d = ImageDraw.Draw(img)
num_cities = len(tour)
for i in range(num_cities):
j=(i+1)%num_cities
city_i=tour[i]
city_j=tour[j]
x1,y1=coords[city_i]
x2,y2=coords[city_j]
d.line((int(x1),int(y1),int(x2),int(y2)),fill=(0,0,0))
d.text((int(x1)+7,int(y1)-5),str(i),font=font,fill=(32,32,32))

for x,y in coords:
x,y=int(x),int(y)
d.ellipse((x-5,y-5,x+5,y+5),outline=(0,0,0),fill=(196,196,196))
j = (i + 1) % num_cities
city_i = tour[i]
city_j = tour[j]
x1, y1 = coords[city_i]
x2, y2 = coords[city_j]
d.line((int(x1), int(y1), int(x2), int(y2)), fill=(0, 0, 0))
d.text((int(x1) + 7, int(y1) - 5), str(i), font=font, fill=(32, 32, 32))

for x, y in coords:
x, y = int(x), int(y)
d.ellipse((x - 5, y - 5, x + 5, y + 5), outline=(0, 0, 0), fill=(196, 196, 196))
del d
img.save(img_file, "PNG")
print "The plot was saved into the %s file." % (img_file,)
print("The plot was saved into the %s file." % (img_file,))


def G1DListTSPInitializator(genome, **args):
""" The initializator for the TSP """
lst = [i for i in xrange(genome.getListSize())]
lst = [i for i in range(genome.getListSize())]
random.shuffle(lst)
genome.setInternalList(lst)


# This is to make a video of best individuals along the evolution
# Use mencoder to create a video with the file list list.txt
# mencoder mf://@list.txt -mf w=400:h=200:fps=3:type=png -ovc lavc
# -lavcopts vcodec=mpeg4:mbd=2:trell -oac copy -o output.avi
#
def evolve_callback(ga_engine):
global LAST_SCORE
try:
os.makedirs('tspimg')
except OSError:
pass
if ga_engine.getCurrentGeneration() % 100 == 0:
best = ga_engine.bestIndividual()
if LAST_SCORE != best.getRawScore():
write_tour_to_img( coords, best, "tspimg/tsp_result_%d.png" % ga_engine.getCurrentGeneration())
write_tour_to_img(coords, best, "tspimg/tsp_result_%d.png" % ga_engine.getCurrentGeneration())
LAST_SCORE = best.getRawScore()
return False


def main_run():
global cm, coords, WIDTH, HEIGHT

coords = [(random.randint(0, WIDTH), random.randint(0, HEIGHT))
for i in xrange(CITIES)]
cm = cartesian_matrix(coords)
for i in range(CITIES)]
cm = cartesian_matrix(coords)
genome = G1DList.G1DList(len(coords))

genome.evaluator.set(lambda chromosome: tour_length(cm, chromosome))
Expand All @@ -113,18 +124,18 @@ def main_run():
ga.setPopulationSize(80)

# This is to make a video
ga.stepCallback.set(evolve_callback)
if PIL_SUPPORT:
ga.stepCallback.set(evolve_callback)
# 21666.49
import psyco
psyco.full()

ga.evolve(freq_stats=500)
best = ga.bestIndividual()

if PIL_SUPPORT:
write_tour_to_img(coords, best, "tsp_result.png")
else:
print "No PIL detected, cannot plot the graph !"
print("No PIL detected, cannot plot the graph !")


if __name__ == "__main__":
main_run()
Loading