def _set_attrs(self,l,d):
self.names = d['NAME']
self.desc = d['DESC'][0]
self.obsolete = d['OBSOLETE']!=None
self.oc = d['OC'][0]
self.must = d['MUST']
self.may = d['MAY']
assert type(self.names)==TupleType
assert self.desc is None or type(self.desc)==StringType
assert type(self.obsolete)==BooleanType and (self.obsolete==0 or self.obsolete==1)
assert type(self.oc)==StringType
assert type(self.must)==TupleType
assert type(self.may)==TupleType
return
python类BooleanType()的实例源码
def _set_attrs(self,l,d):
self.names = d['NAME']
self.desc = d['DESC'][0]
self.obsolete = d['OBSOLETE']!=None
self.syntax = d['SYNTAX'][0]
assert type(self.names)==TupleType
assert self.desc is None or type(self.desc)==StringType
assert type(self.obsolete)==BooleanType and (self.obsolete==0 or self.obsolete==1)
assert self.syntax is None or type(self.syntax)==StringType
return
def _set_attrs(self,l,d):
self.names = d['NAME']
self.desc = d['DESC'][0]
self.obsolete = d['OBSOLETE']!=None
self.applies = d['APPLIES']
assert type(self.names)==TupleType
assert self.desc is None or type(self.desc)==StringType
assert type(self.obsolete)==BooleanType and (self.obsolete==0 or self.obsolete==1)
assert type(self.applies)==TupleType
return
def _set_attrs(self,l,d):
self.names = d['NAME']
self.desc = d['DESC'][0]
self.obsolete = d['OBSOLETE']!=None
self.form = d['FORM'][0]
self.sup = d['SUP']
assert type(self.names)==TupleType
assert self.desc is None or type(self.desc)==StringType
assert type(self.obsolete)==BooleanType and (self.obsolete==0 or self.obsolete==1)
assert type(self.form)==StringType
assert type(self.sup)==TupleType
return
def _set_attrs(self,l,d):
self.names = d['NAME']
self.desc = d['DESC'][0]
self.obsolete = d['OBSOLETE']!=None
self.oc = d['OC'][0]
self.must = d['MUST']
self.may = d['MAY']
assert type(self.names)==TupleType
assert self.desc is None or type(self.desc)==StringType
assert type(self.obsolete)==BooleanType and (self.obsolete==0 or self.obsolete==1)
assert type(self.oc)==StringType
assert type(self.must)==TupleType
assert type(self.may)==TupleType
return
def isTrue(v):
if type(v) == types.BooleanType:
return v
elif type(v) == types.StringType:
return v.lower() in ("yes", "true", "t", "1")
else:
return False
def str2bool(v):
if type(v) == types.BooleanType:
return v
return v.lower() in ("yes", "true", "t", "1")
def tobool(val):
"""Convert `val` to boolean value True or False.
Parameters
----------
val : bool, string, integer
'.true.', '1', 'true', 'on', 'yes', integers != 0 -> True
'.false.','0', 'false', 'off', 'no', integers == 0 -> False
Returns
-------
True or False
Notes
-----
All string vals are case-insensitive.
"""
if isinstance(val, types.BooleanType):
if val == True:
return True
else:
return False
got_str = False
got_int = False
if isinstance(val, types.StringType):
got_str = True
val = val.lower()
elif isinstance(val, types.IntType):
got_int = True
else:
raise StandardError, "input value must be string or integer"
if (got_str and (val in ['.true.', 'true', 'on', 'yes', '1'])) \
or (got_int and (val != 0)):
ret = True
elif (got_str and (val in ['.false.', 'false', 'off', 'no', '0'])) \
or (got_int and (val == 0)):
ret = False
else:
raise StandardError("illegal input value '%s'" %frepr(val))
return ret
def dict_to_JsonObject(the_dict, name=None, ctx=None):
'''
Create a JsonObject from a dictionary.
The context parameter is used for recursive calls,
no need to pass it from outside.
:param the_dict: dictionary to base the `JsonObject` on
:param ctx: context for the parser (default: None)
:rtype: :class:`~katnip.legos.json.JsonObject`
:return: JSON object that represents the dictionary
'''
if type(the_dict) != dict:
raise ValueError('expecting dictionary as first argument')
if ctx is None:
ctx = _JsonStringContext()
members = {}
for (k, v) in the_dict.items():
if v is None:
val = JsonNull(name=ctx.uname(k), fuzzable=False)
elif isinstance(v, types.BooleanType):
val = JsonBoolean(name=ctx.uname(k), value=v, fuzzable=True)
elif isinstance(v, types.StringTypes):
val = JsonString(name=ctx.uname(k), value=v, fuzzable=True)
elif isinstance(v, types.ListType):
val = list_to_JsonArray(v, k, ctx)
elif isinstance(v, types.DictionaryType):
val = dict_to_JsonObject(v, k, ctx)
elif isinstance(v, types.IntType):
val = SInt32(v, encoder=ENC_INT_DEC, name=ctx.uname(k))
else:
raise ValueError('type not supported: %s' % type(v))
members[k] = val
if name is None:
name = 'obj'
return JsonObject(name=ctx.uname(name, False), member_dict=members, fuzz_keys=False)
def list_to_JsonArray(the_list, name=None, ctx=None):
'''
Create a JsonArray from a list.
The context parameter is used for recursive calls,
no need to pass it from outside.
:param the_list: list to base the JsonArray on
:param ctx: context for the parser (default: None)
:rtype: :class:`~katnip.legos.json.JsonArray`
:return: JSON object that represents the list
'''
if type(the_list) != list:
raise ValueError('expecting list as first argument')
if ctx is None:
ctx = _JsonStringContext()
elements = []
for v in the_list:
if v is None:
elements.append(JsonNull(ctx.uname('null'), fuzzable=False))
elif isinstance(v, types.BooleanType):
elements.append(JsonBoolean(ctx.uname('bool'), value=v, fuzzable=True))
elif isinstance(v, types.StringTypes):
elements.append(JsonString(ctx.uname('string'), v, fuzzable=True))
elif isinstance(v, types.ListType):
elements.append(list_to_JsonArray(v, None, ctx))
elif isinstance(v, types.DictionaryType):
elements.append(dict_to_JsonObject(v, None, ctx))
elif isinstance(v, types.IntType):
elements.append(SInt32(v, encoder=ENC_INT_DEC, name=ctx.uname('int')))
else:
raise ValueError('type not supported: %s' % type(v))
if name is None:
name = 'array'
return JsonArray(name=ctx.uname(name, False), values=elements)
def testReturnTypeMutateFuzzable(self):
field = self.get_default_field(fuzzable=True)
self.assertIsInstance(field.mutate(), types.BooleanType)
field.reset()
self.assertIsInstance(field.mutate(), types.BooleanType)
def testReturnTypeMutateNotFuzzable(self):
field = self.get_default_field(fuzzable=False)
self.assertIsInstance(field.mutate(), types.BooleanType)
field.reset()
self.assertIsInstance(field.mutate(), types.BooleanType)
def get_bool_key_map(cls, key_map):
bool_key_map = {}
for (key,value) in key_map.items():
if type(value) == types.BooleanType:
bool_key_map[key] = value
elif type(value) == types.DictType:
for (key2,value2) in value.items():
if type(value2) == types.BooleanType:
bool_key_map[key2] = value2
return bool_key_map
def dump(self, pickler):
pickler.dump(self.tag)
pickler.dump(self._what)
pickler.dump(self._extra)
pickler.dump(self._comment)
if self.prop: # Skip system variables
pickler.dump([x for x in self.prop.items()
if type(x[1]) in (IntType, LongType, FloatType, BooleanType, StringType, UnicodeType)])
else:
pickler.dump(None)
pickler.dump(self.enable)
# ----------------------------------------------------------------------
# Load card from unpickler
# ----------------------------------------------------------------------
def humannum(data, unit=None, include=None, exclude=None):
if isinstance(data, types.DictType):
data = data.copy()
keys = set(data.keys())
if include is not None:
keys = keys & set(include)
if exclude is not None:
keys = keys - set(exclude)
for k in keys:
data[k] = humannum(data[k])
return data
elif isinstance(data, types.BooleanType):
# We have to deal with bool because for historical reason bool is
# subclass of int.
# When bool is introduced into python 2.2 it is represented with int,
# similar to C.
return data
elif isinstance(data, types.ListType):
return [humannum(x) for x in data]
elif isinstance(data, types.StringTypes):
return data
elif isinstance(data, integer_types):
return humannum_int(data, unit=unit)
elif isinstance(data, types.FloatType):
if data > 999:
return humannum_int(int(data), unit=unit)
elif abs(data) < 0.0000000001:
return '0'
else:
return '%.2f' % (data)
else:
return data
def __init__(self, genome, interactiveMode=True):
""" Initializator of GSimpleGA """
#if seed is not None: random.seed(seed) # used to be like this
if type(interactiveMode) != BooleanType:
utils.raiseException("Interactive Mode option must be True or False", TypeError)
if not isinstance(genome, GenomeBase):
utils.raiseException("The genome must be a GenomeBase subclass", TypeError)
self.internalPop = GPopulation(genome)
self.nGenerations = constants.CDefGAGenerations
self.pMutation = constants.CDefGAMutationRate
self.pCrossover = constants.CDefGACrossoverRate
self.nElitismReplacement = constants.CDefGAElitismReplacement
self.setPopulationSize(constants.CDefGAPopulationSize)
self.minimax = constants.minimaxType["maximize"]
self.elitism = True
# NEW
self.new_population = None
# Adapters
self.dbAdapter = None
self.migrationAdapter = None
self.time_init = None
self.max_time = None
self.interactiveMode = interactiveMode
self.interactiveGen = -1
self.GPMode = False
self.selector = FunctionSlot("Selector")
self.stepCallback = FunctionSlot("Generation Step Callback")
self.terminationCriteria = FunctionSlot("Termination Criteria")
self.selector.set(constants.CDefGASelector)
self.allSlots = (self.selector, self.stepCallback, self.terminationCriteria)
self.internalParams = {}
self.currentGeneration = 0
# GP Testing
for classes in constants.CDefGPGenomes:
if isinstance(self.internalPop.oneSelfGenome, classes):
self.setGPMode(True)
break
log.debug("A GA Engine was created, nGenerations=%d", self.nGenerations)
# New
self.path = None
# -----------------------------------------------------------------
def setMultiProcessing(self, flag=True, full_copy=False, max_processes=None):
""" Sets the flag to enable/disable the use of python multiprocessing module.
Use this option when you have more than one core on your CPU and when your
evaluation function is very slow.
Pyevolve will automaticly check if your Python version has **multiprocessing**
support and if you have more than one single CPU core. If you don't have support
or have just only one core, Pyevolve will not use the **multiprocessing**
feature.
Pyevolve uses the **multiprocessing** to execute the evaluation function over
the individuals, so the use of this feature will make sense if you have a
truly slow evaluation function (which is commom in GAs).
The parameter "full_copy" defines where the individual data should be copied back
after the evaluation or not. This parameter is useful when you change the
individual in the evaluation function.
:param flag: True (default) or False
:param full_copy: True or False (default)
:param max_processes: None (default) or an integer value
.. warning:: Use this option only when your evaluation function is slow, so you'll
get a good tradeoff between the process communication speed and the
parallel evaluation. The use of the **multiprocessing** doesn't means
always a better performance.
.. note:: To enable the multiprocessing option, you **MUST** add the *__main__* check
on your application, otherwise, it will result in errors. See more on the
`Python Docs <http://docs.python.org/library/multiprocessing.html#multiprocessing-programming>`__
site.
.. versionadded:: 0.6
The `setMultiProcessing` method.
"""
if type(flag) != BooleanType:
utils.raiseException("Multiprocessing option must be True or False", TypeError)
if type(full_copy) != BooleanType:
utils.raiseException("Multiprocessing 'full_copy' option must be True or False", TypeError)
self.internalPop.setMultiProcessing(flag, full_copy, max_processes)
# -----------------------------------------------------------------
def setMultiProcessing(self, flag=True, full_copy=False, max_processes=None):
""" Sets the flag to enable/disable the use of python multiprocessing module.
Use this option when you have more than one core on your CPU and when your
evaluation function is very slow.
Pyevolve will automaticly check if your Python version has **multiprocessing**
support and if you have more than one single CPU core. If you don't have support
or have just only one core, Pyevolve will not use the **multiprocessing**
feature.
Pyevolve uses the **multiprocessing** to execute the evaluation function over
the individuals, so the use of this feature will make sense if you have a
truly slow evaluation function (which is commom in GAs).
The parameter "full_copy" defines where the individual data should be copied back
after the evaluation or not. This parameter is useful when you change the
individual in the evaluation function.
:param flag: True (default) or False
:param full_copy: True or False (default)
:param max_processes: None (default) or an integer value
.. warning:: Use this option only when your evaluation function is slow, so you'll
get a good tradeoff between the process communication speed and the
parallel evaluation. The use of the **multiprocessing** doesn't means
always a better performance.
.. note:: To enable the multiprocessing option, you **MUST** add the *__main__* check
on your application, otherwise, it will result in errors. See more on the
`Python Docs <http://docs.python.org/library/multiprocessing.html#multiprocessing-programming>`__
site.
.. versionadded:: 0.6
The `setMultiProcessing` method.
"""
if type(flag) != BooleanType:
utils.raiseException("Multiprocessing option must be True or False", TypeError)
if type(full_copy) != BooleanType:
utils.raiseException("Multiprocessing 'full_copy' option must be True or False", TypeError)
self.internalPop.setMultiProcessing(flag, full_copy, max_processes)
# -----------------------------------------------------------------
def _set_attrs(self,l,d):
self.names = d['NAME']
self.desc = d['DESC'][0]
self.obsolete = d['OBSOLETE']!=None
self.sup = d['SUP']
self.equality = d['EQUALITY'][0]
self.ordering = d['ORDERING'][0]
self.substr = d['SUBSTR'][0]
try:
syntax = d['SYNTAX'][0]
except IndexError:
self.syntax = None
self.syntax_len = None
else:
if syntax is None:
self.syntax = None
self.syntax_len = None
else:
try:
self.syntax,syntax_len = d['SYNTAX'][0].split("{")
except ValueError:
self.syntax = d['SYNTAX'][0]
self.syntax_len = None
for i in l:
if i.startswith("{") and i.endswith("}"):
self.syntax_len=long(i[1:-1])
else:
self.syntax_len = long(syntax_len[:-1])
self.single_value = d['SINGLE-VALUE']!=None
self.collective = d['COLLECTIVE']!=None
self.no_user_mod = d['NO-USER-MODIFICATION']!=None
try:
self.usage = AttributeUsage[d['USAGE'][0]]
except KeyError:
raise
self.usage = AttributeUsage.get(d['USAGE'][0],0)
assert type(self.names)==TupleType
assert self.desc is None or type(self.desc)==StringType
assert type(self.sup)==TupleType,'attribute sup has type %s' % (type(self.sup))
assert type(self.obsolete)==BooleanType and (self.obsolete==0 or self.obsolete==1)
assert type(self.single_value)==BooleanType and (self.single_value==0 or self.single_value==1)
assert type(self.no_user_mod)==BooleanType and (self.no_user_mod==0 or self.no_user_mod==1)
assert self.syntax is None or type(self.syntax)==StringType
assert self.syntax_len is None or type(self.syntax_len)==type(0L)
return
def _set_attrs(self,l,d):
self.names = d['NAME']
self.desc = d['DESC'][0]
self.obsolete = d['OBSOLETE']!=None
self.sup = d['SUP']
self.equality = d['EQUALITY'][0]
self.ordering = d['ORDERING'][0]
self.substr = d['SUBSTR'][0]
try:
syntax = d['SYNTAX'][0]
except IndexError:
self.syntax = None
self.syntax_len = None
else:
if syntax is None:
self.syntax = None
self.syntax_len = None
else:
try:
self.syntax,syntax_len = d['SYNTAX'][0].split("{")
except ValueError:
self.syntax = d['SYNTAX'][0]
self.syntax_len = None
for i in l:
if i.startswith("{") and i.endswith("}"):
self.syntax_len=long(i[1:-1])
else:
self.syntax_len = long(syntax_len[:-1])
self.single_value = d['SINGLE-VALUE']!=None
self.collective = d['COLLECTIVE']!=None
self.no_user_mod = d['NO-USER-MODIFICATION']!=None
try:
self.usage = AttributeUsage[d['USAGE'][0]]
except KeyError:
raise
self.usage = AttributeUsage.get(d['USAGE'][0],0)
assert type(self.names)==TupleType
assert self.desc is None or type(self.desc)==StringType
assert type(self.sup)==TupleType,'attribute sup has type %s' % (type(self.sup))
assert type(self.obsolete)==BooleanType and (self.obsolete==0 or self.obsolete==1)
assert type(self.single_value)==BooleanType and (self.single_value==0 or self.single_value==1)
assert type(self.no_user_mod)==BooleanType and (self.no_user_mod==0 or self.no_user_mod==1)
assert self.syntax is None or type(self.syntax)==StringType
assert self.syntax_len is None or type(self.syntax_len)==type(0L)
return