Skip to content

Commit 07b000a

Browse files
authored
Add files via upload
Update for Python 3 compatibility
1 parent 589b6a9 commit 07b000a

53 files changed

Lines changed: 11763 additions & 614 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

Consts.py

Lines changed: 537 additions & 0 deletions
Large diffs are not rendered by default.

Crossovers.py

Lines changed: 810 additions & 0 deletions
Large diffs are not rendered by default.

DBAdapters.py

Lines changed: 792 additions & 0 deletions
Large diffs are not rendered by default.

FunctionSlot.py

Lines changed: 202 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,202 @@
1+
"""
2+
:mod:`FunctionSlot` -- function slots module
3+
==================================================================
4+
5+
The *function slot* concept is large used by Pyevolve, the idea
6+
is simple, each genetic operator or any operator, can be assigned
7+
to a slot, by this way, we can add more than simple one operator,
8+
we can have for example, two or more mutator operators at same time,
9+
two or more evaluation functions, etc. In this :mod:`FunctionSlot` module,
10+
you'll find the class :class:`FunctionSlot.FunctionSlot`, which is the slot class.
11+
12+
"""
13+
14+
from random import uniform as rand_uniform
15+
16+
from . import Util
17+
import collections
18+
19+
class FunctionSlot(object):
20+
""" FunctionSlot Class - The function slot
21+
22+
Example:
23+
>>> genome.evaluator.set(eval_func)
24+
>>> genome.evaluator[0]
25+
<function eval_func at 0x018C8930>
26+
>>> genome.evaluator
27+
Slot [Evaluation Function] (Count: 1)
28+
Name: eval_func
29+
>>> genome.evaluator.clear()
30+
>>> genome.evaluator
31+
Slot [Evaluation Function] (Count: 0)
32+
No function
33+
34+
You can add weight to functions when using the `rand_apply` paramter:
35+
>>> genome.evaluator.set(eval_main, 0.9)
36+
>>> genome.evaluator.add(eval_sec, 0.3)
37+
>>> genome.evaluator.setRandomApply()
38+
39+
In the above example, the function *eval_main* will be called with 90% of
40+
probability and the *eval_sec* will be called with 30% of probability.
41+
42+
There are another way to add functions too:
43+
>>> genome.evaluator += eval_func
44+
45+
:param name: the slot name
46+
:param rand_apply: if True, just one of the functions in the slot
47+
will be applied, this function is randomly picked based
48+
on the weight of the function added.
49+
50+
"""
51+
52+
def __init__(self, name="Anonymous Function", rand_apply=False):
53+
""" The creator of the FunctionSlot Class """
54+
self.funcList = []
55+
self.funcWeights = []
56+
self.slotName = name
57+
self.rand_apply = rand_apply
58+
59+
def __typeCheck(self, func):
60+
""" Used internally to check if a function passed to the
61+
function slot is callable. Otherwise raises a TypeError exception.
62+
63+
:param func: the function object
64+
"""
65+
if not isinstance(func, collections.Callable):
66+
Util.raiseException("The function must be a method or function", TypeError)
67+
68+
def __iadd__(self, func):
69+
""" To add more functions using the += operator
70+
71+
.. versionadded:: 0.6
72+
The __iadd__ method.
73+
"""
74+
self.__typeCheck(func)
75+
self.funcList.append(func)
76+
return self
77+
78+
def __getitem__(self, index):
79+
""" Used to retrieve some slot function index """
80+
return self.funcList[index]
81+
82+
def __setitem__(self, index, value):
83+
""" Used to set the index slot function """
84+
self.__typeCheck(value)
85+
self.funcList[index] = value
86+
87+
def __iter__(self):
88+
""" Return the function list iterator """
89+
return iter(self.funcList)
90+
91+
def __len__(self):
92+
""" Return the number of functions on the slot
93+
94+
.. versionadded:: 0.6
95+
The *__len__* method
96+
"""
97+
return len(self.funcList)
98+
99+
def setRandomApply(self, flag=True):
100+
""" Sets the random function application, in this mode, the
101+
function will randomly choose one slot to apply
102+
103+
:param flag: True or False
104+
105+
"""
106+
if not isinstance(flag, bool):
107+
Util.raiseException("Random option must be True or False", TypeError)
108+
109+
self.rand_apply = flag
110+
111+
def clear(self):
112+
""" Used to clear the functions in the slot """
113+
if len(self.funcList) > 0:
114+
del self.funcList[:]
115+
del self.funcWeights[:]
116+
117+
def add(self, func, weight=0.5):
118+
""" Used to add a function to the slot
119+
120+
:param func: the function to be added in the slot
121+
:param weight: used when you enable the *random apply*, it's the weight
122+
of the function for the random selection
123+
124+
.. versionadded:: 0.6
125+
The `weight` parameter.
126+
127+
"""
128+
self.__typeCheck(func)
129+
self.funcList.append(func)
130+
self.funcWeights.append(weight)
131+
132+
def isEmpty(self):
133+
""" Return true if the function slot is empy """
134+
return (len(self.funcList) == 0)
135+
136+
def set(self, func, weight=0.5):
137+
""" Used to clear all functions in the slot and add one
138+
139+
:param func: the function to be added in the slot
140+
:param weight: used when you enable the *random apply*, it's the weight
141+
of the function for the random selection
142+
143+
.. versionadded:: 0.6
144+
The `weight` parameter.
145+
146+
.. note:: the method *set* of the function slot remove all previous
147+
functions added to the slot.
148+
"""
149+
self.clear()
150+
self.__typeCheck(func)
151+
self.add(func, weight)
152+
153+
def apply(self, index, obj, **args):
154+
""" Apply the index function
155+
156+
:param index: the index of the function
157+
:param obj: this object is passes as parameter to the function
158+
:param args: this args dictionary is passed to the function
159+
160+
"""
161+
if len(self.funcList) <= 0:
162+
raise Exception("No function defined: " + self.slotName)
163+
return self.funcList[index](obj, **args)
164+
165+
def applyFunctions(self, obj=None, **args):
166+
""" Generator to apply all function slots in obj
167+
168+
:param obj: this object is passes as parameter to the function
169+
:param args: this args dictionary is passed to the function
170+
171+
"""
172+
if len(self.funcList) <= 0:
173+
Util.raiseException("No function defined: " + self.slotName)
174+
175+
if not self.rand_apply:
176+
for f in self.funcList:
177+
yield f(obj, **args)
178+
else:
179+
v = rand_uniform(0, 1)
180+
fobj = None
181+
for func, weight in zip(self.funcList, self.funcWeights):
182+
fobj = func
183+
if v < weight:
184+
break
185+
v = v - weight
186+
187+
yield fobj(obj, **args)
188+
189+
def __repr__(self):
190+
""" String representation of FunctionSlot """
191+
strRet = "Slot [%s] (Count: %d)\n" % (self.slotName, len(self.funcList))
192+
193+
if len(self.funcList) <= 0:
194+
strRet += "\t\tNo function\n"
195+
return strRet
196+
197+
for f, w in zip(self.funcList, self.funcWeights):
198+
strRet += "\t\tName: %s - Weight: %.2f\n" % (f.__name__, w)
199+
if f.__doc__:
200+
strRet += "\t\tDoc: " + f.__doc__ + "\n"
201+
202+
return strRet

G1DBinaryString.py

Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
"""
2+
:mod:`G1DBinaryString` -- the classical binary string chromosome
3+
=====================================================================
4+
5+
This is the classical chromosome representation on GAs, it is the 1D
6+
Binary String. This string looks like "00011101010".
7+
8+
9+
Default Parameters
10+
-------------------------------------------------------------
11+
12+
*Initializator*
13+
14+
:func:`Initializators.G1DBinaryStringInitializator`
15+
16+
The Binatry String Initializator for G1DBinaryString
17+
18+
*Mutator*
19+
20+
:func:`Mutators.G1DBinaryStringMutatorFlip`
21+
22+
The Flip Mutator for G1DBinaryString
23+
24+
*Crossover*
25+
26+
:func:`Crossovers.G1DBinaryStringXSinglePoint`
27+
28+
The Single Point Crossover for G1DBinaryString
29+
30+
31+
Class
32+
-------------------------------------------------------------
33+
34+
35+
"""
36+
37+
from .GenomeBase import GenomeBase, G1DBase
38+
from . import Consts
39+
from . import Util
40+
41+
class G1DBinaryString(G1DBase):
42+
""" G1DBinaryString Class - The 1D Binary String chromosome
43+
44+
Inheritance diagram for :class:`G1DBinaryString.G1DBinaryString`:
45+
46+
.. inheritance-diagram:: G1DBinaryString.G1DBinaryString
47+
48+
This chromosome class extends the :class:`GenomeBase.G1DBase` class.
49+
50+
Example:
51+
>>> genome = G1DBinaryString.G1DBinaryString(5)
52+
53+
:param length: the 1D Binary String size
54+
55+
"""
56+
__slots__ = ["stringLength"]
57+
58+
def __init__(self, length=10):
59+
""" The initializator of G1DList representation """
60+
super(G1DBinaryString, self).__init__(length)
61+
self.genomeList = []
62+
self.stringLength = length
63+
self.initializator.set(Consts.CDefG1DBinaryStringInit)
64+
self.mutator.set(Consts.CDefG1DBinaryStringMutator)
65+
self.crossover.set(Consts.CDefG1DBinaryStringCrossover)
66+
67+
def __setitem__(self, key, value):
68+
""" Set the specified value for an gene of List
69+
70+
>>> g = G1DBinaryString(5)
71+
>>> for i in xrange(len(g)):
72+
... g.append(1)
73+
>>> g[4] = 0
74+
>>> g[4]
75+
0
76+
77+
"""
78+
if isinstance(value, int) and value not in (0,1):
79+
Util.raiseException("The value must be zero (0) or one (1), used (%s)" % value, ValueError)
80+
elif isinstance(value, list) and not set(value) <= set([0, 1]):
81+
# if slice notation is used we check all passed values
82+
vals = set(value) - set([0, 1])
83+
Util.raiseException("The value must be zero (0) or one (1), used (%s)" % vals, ValueError)
84+
G1DBase.__setitem__(self, key, value)
85+
86+
def __repr__(self):
87+
""" Return a string representation of Genome """
88+
ret = GenomeBase.__repr__(self)
89+
ret += "- G1DBinaryString\n"
90+
ret += "\tString length:\t %s\n" % (self.getListSize(),)
91+
ret += "\tString:\t\t %s\n\n" % (self.getBinary(),)
92+
return ret
93+
94+
def getDecimal(self):
95+
""" Converts the binary string to decimal representation
96+
97+
Example:
98+
>>> g = G1DBinaryString(5)
99+
>>> for i in xrange(len(g)):
100+
... g.append(0)
101+
>>> g[3] = 1
102+
>>> g.getDecimal()
103+
2
104+
105+
:rtype: decimal value
106+
107+
"""
108+
return int(self.getBinary(), 2)
109+
110+
def getBinary(self):
111+
""" Returns the binary string representation
112+
113+
Example:
114+
>>> g = G1DBinaryString(2)
115+
>>> g.append(0)
116+
>>> g.append(1)
117+
>>> g.getBinary()
118+
'01'
119+
120+
:rtype: the binary string
121+
122+
"""
123+
return "".join(map(str, self))
124+
125+
def append(self, value):
126+
""" Appends an item to the list
127+
128+
Example:
129+
>>> g = G1DBinaryString(2)
130+
>>> g.append(0)
131+
132+
:param value: value to be added, 0 or 1
133+
134+
"""
135+
if value not in [0, 1]:
136+
Util.raiseException("The value must be 0 or 1", ValueError)
137+
G1DBase.append(self, value)
138+
139+
def copy(self, g):
140+
""" Copy genome to 'g'
141+
142+
Example:
143+
>>> g1 = G1DBinaryString(2)
144+
>>> g1.append(0)
145+
>>> g1.append(1)
146+
>>> g2 = G1DBinaryString(2)
147+
>>> g1.copy(g2)
148+
>>> g2[1]
149+
1
150+
151+
:param g: the destination genome
152+
153+
"""
154+
GenomeBase.copy(self, g)
155+
G1DBase.copy(self, g)
156+
157+
def clone(self):
158+
""" Return a new instace copy of the genome
159+
160+
Example:
161+
>>> g = G1DBinaryString(5)
162+
>>> for i in xrange(len(g)):
163+
... g.append(1)
164+
>>> clone = g.clone()
165+
>>> clone[0]
166+
1
167+
168+
:rtype: the G1DBinaryString instance clone
169+
170+
"""
171+
newcopy = G1DBinaryString(self.getListSize())
172+
self.copy(newcopy)
173+
return newcopy

0 commit comments

Comments
 (0)